diff --git a/build.gradle b/build.gradle index bf2977c69966..b6e1b8a03fcd 100644 --- a/build.gradle +++ b/build.gradle @@ -69,7 +69,7 @@ configure(allprojects) { project -> testCompile("junit:junit:${junitVersion}") testCompile("org.hamcrest:hamcrest-all:1.3") testCompile("org.mockito:mockito-core:1.9.5") - if (project.name in ["spring", "spring-jms", + if (project.name in ["spring", "spring-orm-hibernate4", "spring-oxm", "spring-struts", "spring-test", "spring-test-mvc", "spring-tx", "spring-web", "spring-webmvc", "spring-webmvc-portlet", "spring-webmvc-tiles3"]) { diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java index 49cf841b4ea9..a8c89b525e87 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java @@ -16,20 +16,28 @@ package org.springframework.jms.config; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + 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.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.parsing.ComponentDefinition; import org.springframework.beans.factory.parsing.CompositeComponentDefinition; @@ -42,6 +50,7 @@ import org.springframework.jca.endpoint.GenericMessageEndpointManager; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.jms.listener.endpoint.JmsMessageEndpointManager; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ErrorHandler; /** @@ -49,7 +58,7 @@ * @author Juergen Hoeller * @author Christian Dupuis */ -public class JmsNamespaceHandlerTests extends TestCase { +public class JmsNamespaceHandlerTests { private static final String DEFAULT_CONNECTION_FACTORY = "connectionFactory"; @@ -58,17 +67,18 @@ public class JmsNamespaceHandlerTests extends TestCase { private ToolingTestApplicationContext context; - @Override - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { this.context = new ToolingTestApplicationContext("jmsNamespaceHandlerTests.xml", getClass()); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { this.context.close(); } + @Test public void testBeansCreated() { Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class); assertEquals("Context should contain 3 JMS listener containers", 3, containers.size()); @@ -77,6 +87,7 @@ public void testBeansCreated() { assertEquals("Context should contain 3 JCA endpoint containers", 3, containers.size()); } + @Test public void testContainerConfiguration() throws Exception { Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class); ConnectionFactory defaultConnectionFactory = context.getBean(DEFAULT_CONNECTION_FACTORY, ConnectionFactory.class); @@ -102,6 +113,7 @@ else if (container.getConnectionFactory().equals(explicitConnectionFactory)) { assertEquals("2 containers should have the explicit connectionFactory", 2, explicitConnectionFactoryCount); } + @Test public void testListeners() throws Exception { TestBean testBean1 = context.getBean("testBean1", TestBean.class); TestBean testBean2 = context.getBean("testBean2", TestBean.class); @@ -111,36 +123,28 @@ public void testListeners() throws Exception { assertNull(testBean2.getName()); assertNull(testBean3.message); - MockControl control1 = MockControl.createControl(TextMessage.class); - TextMessage message1 = (TextMessage) control1.getMock(); - control1.expectAndReturn(message1.getText(), "Test1"); - control1.replay(); + TextMessage message1 = mock(TextMessage.class); + given(message1.getText()).willReturn("Test1"); 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(); + TextMessage message2 = mock(TextMessage.class); + given(message2.getText()).willReturn("Test2"); 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(); + TextMessage message3 = mock(TextMessage.class); MessageListener listener3 = getListener(DefaultMessageListenerContainer.class.getName() + "#0"); listener3.onMessage(message3); assertSame(message3, testBean3.message); - control3.verify(); } + @Test public void testErrorHandlers() { ErrorHandler expected = this.context.getBean("testErrorHandler", ErrorHandler.class); ErrorHandler errorHandler1 = getErrorHandler("listener1"); @@ -151,6 +155,7 @@ public void testErrorHandlers() { assertNull(defaultErrorHandler); } + @Test public void testPhases() { int phase1 = getPhase("listener1"); int phase2 = getPhase("listener2"); @@ -182,6 +187,7 @@ public int getPhase(String containerBeanName) { return ((Phased) container).getPhase(); } + @Test 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")); @@ -192,6 +198,7 @@ public void testComponentRegistration() { context.containsComponentDefinition(JmsMessageEndpointManager.class.getName() + "#0")); } + @Test public void testSourceExtraction() { Iterator iterator = context.getRegisteredComponents(); while (iterator.hasNext()) { diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java index 78c0de6e9fda..cd53ab37a313 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,14 @@ package org.springframework.jms.connection; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -30,9 +38,8 @@ import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Test; import org.springframework.jms.StubQueue; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.JmsTemplate102; @@ -50,30 +57,23 @@ * @author Juergen Hoeller * @since 26.07.2004 */ -public class JmsTransactionManagerTests extends TestCase { +public class JmsTransactionManagerTests { + + @After + public void verifyTransactionSynchronizationManager() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + } + + @Test 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(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -87,33 +87,19 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test 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(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -127,33 +113,19 @@ public Object doInJms(Session sess) { }); tm.rollback(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).rollback(); + verify(session).close(); + verify(con).close(); } + @Test 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(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -180,33 +152,19 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test 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(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -240,39 +198,21 @@ public Object doInJms(Session sess) { // expected } - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).rollback(); + verify(session).close(); + verify(con).close(); } + @Test 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(); + final ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + final Session session2 = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(con.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session2); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -307,41 +247,21 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(session2).close(); + verify(con, times(2)).close(); } + @Test 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(); + final ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + final Session session2 = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session, session2); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -376,48 +296,27 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session2).commit(); + verify(session).close(); + verify(session2).close(); + verify(con, times(2)).close(); } + @Test 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(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + Session session = mock(Session.class); + MessageProducer producer = mock(MessageProducer.class); + final Message message = mock(Message.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(session.createProducer(dest)).willReturn(producer); + given(session.getTransacted()).willReturn(true); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -430,34 +329,22 @@ public Message createMessage(Session session) throws JMSException { }); tm.commit(ts); - producerControl.verify(); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(producer).send(message); + verify(session).commit(); + verify(producer).close(); + verify(session).close(); + verify(con).close(); } + @Test + @Deprecated 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(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + final QueueSession session = mock(QueueSession.class); + + given(cf.createQueueConnection()).willReturn(con); + given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager102(cf, false); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -471,33 +358,20 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test + @Deprecated 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(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + final TopicSession session = mock(TopicSession.class); + + given(cf.createTopicConnection()).willReturn(con); + given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager102(cf, true); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -511,15 +385,8 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } - - @Override - protected void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java index 19912ccc3958..a1a40d51e44b 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,14 @@ package org.springframework.jms.connection; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.ExceptionListener; @@ -28,27 +36,17 @@ import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.Test; /** * @author Juergen Hoeller * @since 26.07.2004 */ -public class SingleConnectionFactoryTests extends TestCase { +public class SingleConnectionFactoryTests { + @Test public void testWithConnection() throws JMSException { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(Connection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); Connection con1 = scf.createConnection(); @@ -61,21 +59,15 @@ public void testWithConnection() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithQueueConnection() throws JMSException { - MockControl conControl = MockControl.createControl(QueueConnection.class); - Connection con = (QueueConnection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(QueueConnection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); QueueConnection con1 = scf.createQueueConnection(); @@ -88,21 +80,15 @@ public void testWithQueueConnection() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithTopicConnection() throws JMSException { - MockControl conControl = MockControl.createControl(TopicConnection.class); - Connection con = (TopicConnection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(TopicConnection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); TopicConnection con1 = scf.createTopicConnection(); @@ -115,26 +101,18 @@ public void testWithTopicConnection() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -145,27 +123,18 @@ public void testWithConnectionFactory() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -176,27 +145,18 @@ public void testWithQueueConnectionFactoryAndJms11Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + + given(cf.createQueueConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createQueueConnection(); @@ -207,27 +167,18 @@ public void testWithQueueConnectionFactoryAndJms102Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -238,27 +189,18 @@ public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + + given(cf.createTopicConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createTopicConnection(); @@ -269,29 +211,18 @@ public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setClientId("myId"); @@ -303,32 +234,21 @@ public void testWithConnectionFactoryAndClientId() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).setClientID("myId"); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.getExceptionListener()).willReturn(listener); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); @@ -343,18 +263,18 @@ public void testWithConnectionFactoryAndExceptionListener() throws JMSException con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).setExceptionListener(listener); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test public void testWithConnectionFactoryAndReconnectOnException() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); TestConnection con = new TestConnection(); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setReconnectOnException(true); @@ -366,21 +286,18 @@ public void testWithConnectionFactoryAndReconnectOnException() throws JMSExcepti con2.start(); scf.destroy(); // should trigger actual close - cfControl.verify(); assertEquals(2, con.getStartCount()); assertEquals(2, con.getCloseCount()); } + @Test public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); TestConnection con = new TestConnection(); - TestExceptionListener listener = new TestExceptionListener(); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + TestExceptionListener listener = new TestExceptionListener(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); scf.setReconnectOnException(true); @@ -392,29 +309,17 @@ public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException con2.start(); scf.destroy(); // should trigger actual close - cfControl.verify(); assertEquals(2, con.getStartCount()); assertEquals(2, con.getCloseCount()); assertEquals(1, listener.getCount()); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + + given(cf.createQueueConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory102(cf, false); QueueConnection con1 = scf.createQueueConnection(); @@ -425,27 +330,18 @@ public void testConnectionFactory102WithQueue() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + + given(cf.createTopicConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory102(cf, true); TopicConnection con1 = scf.createTopicConnection(); @@ -456,45 +352,23 @@ public void testConnectionFactory102WithTopic() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test 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, 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + Session txSession = mock(Session.class); + Session nonTxSession = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -516,47 +390,25 @@ public void testCachingConnectionFactory() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).commit(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test 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, 1); - txSession.rollback(); - txSessionControl.setVoidCallable(1); - txSession.close(); - txSessionControl.setVoidCallable(1); - con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); - conControl.setReturnValue(nonTxSession, 1); - nonTxSession.close(); - nonTxSessionControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + QueueSession txSession = mock(QueueSession.class); + QueueSession nonTxSession = mock(QueueSession.class); + + given(cf.createQueueConnection()).willReturn(con); + given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -578,45 +430,25 @@ public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).rollback(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test 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, 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(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + TopicSession txSession = mock(TopicSession.class); + TopicSession nonTxSession = mock(TopicSession.class); + + given(cf.createTopicConnection()).willReturn(con); + given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -638,10 +470,11 @@ public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java index 12f01be2b5d2..cbf03b7abaf2 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java @@ -16,6 +16,15 @@ package org.springframework.jms.core; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; @@ -39,9 +48,8 @@ import javax.naming.Context; import javax.naming.NamingException; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.InvalidClientIDException; import org.springframework.jms.InvalidDestinationException; import org.springframework.jms.InvalidSelectorException; @@ -65,105 +73,54 @@ * @author Andre Biryukov * @author Mark Pollack */ -public class JmsTemplate102Tests extends TestCase { - - private Context mockJndiContext; - private MockControl mockJndiControl; - - private MockControl queueConnectionFactoryControl; - private QueueConnectionFactory mockQueueConnectionFactory; - - private MockControl queueConnectionControl; - private QueueConnection mockQueueConnection; - - private MockControl queueSessionControl; - private QueueSession mockQueueSession; - - private MockControl queueControl; - private Queue mockQueue; - - private MockControl topicConnectionFactoryControl; - private TopicConnectionFactory mockTopicConnectionFactory; - - private MockControl topicConnectionControl; - private TopicConnection mockTopicConnection; - - private MockControl topicSessionControl; - private TopicSession mockTopicSession; - - private MockControl topicControl; - private Topic mockTopic; +public class JmsTemplate102Tests { + + private Context jndiContext; + private QueueConnectionFactory queueConnectionFactory; + private QueueConnection queueConnection; + private QueueSession queueSession; + private Queue queue; + private TopicConnectionFactory topicConnectionFactory; + private TopicConnection topicConnection; + private TopicSession topicSession; + private Topic topic; private int deliveryMode = DeliveryMode.PERSISTENT; private int priority = 9; private int timeToLive = 10000; - /** - * Create the mock objects for testing. - */ - @Override - protected void setUp() throws Exception { - mockJndiControl = MockControl.createControl(Context.class); - mockJndiContext = (Context) this.mockJndiControl.getMock(); - + @Before + public void setUpMocks() throws Exception { + jndiContext = mock(Context.class); createMockForQueues(); createMockForTopics(); - - mockJndiContext.close(); - mockJndiControl.replay(); } private void createMockForTopics() throws JMSException, NamingException { - topicConnectionFactoryControl = MockControl.createControl(TopicConnectionFactory.class); - mockTopicConnectionFactory = (TopicConnectionFactory) topicConnectionFactoryControl.getMock(); - - topicConnectionControl = MockControl.createControl(TopicConnection.class); - mockTopicConnection = (TopicConnection) topicConnectionControl.getMock(); + topicConnectionFactory = mock(TopicConnectionFactory.class); + topicConnection = mock(TopicConnection.class); + topic = mock(Topic.class); + topicSession = mock(TopicSession.class); - topicControl = MockControl.createControl(Topic.class); - mockTopic = (Topic) topicControl.getMock(); - - topicSessionControl = MockControl.createControl(TopicSession.class); - mockTopicSession = (TopicSession) topicSessionControl.getMock(); - - mockTopicConnectionFactory.createTopicConnection(); - topicConnectionFactoryControl.setReturnValue(mockTopicConnection); - topicConnectionFactoryControl.replay(); - - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - topicConnectionControl.setReturnValue(mockTopicSession); - mockTopicSession.getTransacted(); - topicSessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testTopic"); - mockJndiControl.setReturnValue(mockTopic); + given(topicConnectionFactory.createTopicConnection()).willReturn(topicConnection); + given(topicConnection.createTopicSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(topicSession); + given(topicSession.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testTopic")).willReturn(topic); } private void createMockForQueues() throws JMSException, NamingException { - queueConnectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class); - mockQueueConnectionFactory = (QueueConnectionFactory) queueConnectionFactoryControl.getMock(); - - queueConnectionControl = MockControl.createControl(QueueConnection.class); - mockQueueConnection = (QueueConnection) queueConnectionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - queueSessionControl = MockControl.createControl(QueueSession.class); - mockQueueSession = (QueueSession) queueSessionControl.getMock(); - - mockQueueConnectionFactory.createQueueConnection(); - queueConnectionFactoryControl.setReturnValue(mockQueueConnection); - queueConnectionFactoryControl.replay(); + queueConnectionFactory = mock(QueueConnectionFactory.class); + queueConnection = mock(QueueConnection.class); + queue = mock(Queue.class); + queueSession = mock(QueueSession.class); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - queueConnectionControl.setReturnValue(mockQueueSession); - mockQueueSession.getTransacted(); - queueSessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testQueue"); - mockJndiControl.setReturnValue(mockQueue); + given(queueConnectionFactory.createQueueConnection()).willReturn(queueConnection); + given(queueConnection.createQueueSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(queueSession); + given(queueSession.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testQueue")).willReturn(queue); } private JmsTemplate102 createTemplate() { @@ -172,7 +129,7 @@ private JmsTemplate102 createTemplate() { destMan.setJndiTemplate(new JndiTemplate() { @Override protected Context createInitialContext() { - return mockJndiContext; + return jndiContext; } }); template.setDestinationResolver(destMan); @@ -189,21 +146,13 @@ protected boolean useTransactedTemplate() { } + @Test public void testTopicSessionCallback() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicSessionControl.replay(); - topicConnectionControl.replay(); - template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { @@ -212,39 +161,24 @@ public Object doInJms(Session session) throws JMSException { } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the execute(ProducerCallback) using a topic. */ + @Test public void testTopicProducerCallback() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); + TopicPublisher topicPublisher = mock(TopicPublisher.class); - mockTopicSession.createPublisher(null); - topicSessionControl.setReturnValue(mockTopicPublisher); - - mockTopicPublisher.getPriority(); - topicPublisherControl.setReturnValue(4); - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicPublisherControl.replay(); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(null)).willReturn(topicPublisher); + given(topicPublisher.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -255,45 +189,27 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the execute(ProducerCallback) using a topic. */ + @Test public void testTopicProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); - - mockTopicSession.createPublisher(null); - topicSessionControl.setReturnValue(mockTopicPublisher); + TopicPublisher topicPublisher = mock(TopicPublisher.class); - mockTopicPublisher.setDisableMessageID(true); - topicPublisherControl.setVoidCallable(1); - mockTopicPublisher.setDisableMessageTimestamp(true); - topicPublisherControl.setVoidCallable(1); - mockTopicPublisher.getPriority(); - topicPublisherControl.setReturnValue(4); - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicPublisherControl.replay(); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(null)).willReturn(topicPublisher); + given(topicPublisher.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -304,30 +220,24 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicPublisher).setDisableMessageID(true); + verify(topicPublisher).setDisableMessageTimestamp(true); + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the method execute(SessionCallback action) with using the * point to point domain as specified by the value of isPubSubDomain = false. */ + @Test public void testQueueSessionCallback() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSessionControl.replay(); - queueConnectionControl.replay(); - template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { @@ -336,39 +246,24 @@ public Object doInJms(Session session) throws JMSException { } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSession).close(); + verify(queueConnection).close(); } /** * Test the method execute(ProducerCallback) with a Queue. */ + @Test public void testQueueProducerCallback() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain. - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - - mockQueueSession.createSender(null); - queueSessionControl.setReturnValue(mockQueueSender); - - mockQueueSender.getPriority(); - queueSenderControl.setReturnValue(4); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); + QueueSender queueSender = mock(QueueSender.class); - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(queueSession.createSender(null)).willReturn(queueSender); + given(queueSender.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -380,42 +275,24 @@ public Object doInJms(Session session, MessageProducer producer) } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } + @Test public void testQueueProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain. - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); template.afterPropertiesSet(); - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); - mockQueueSession.createSender(null); - queueSessionControl.setReturnValue(mockQueueSender); - - mockQueueSender.setDisableMessageID(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.setDisableMessageTimestamp(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.getPriority(); - queueSenderControl.setReturnValue(4); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(queueSession.createSender(null)).willReturn(queueSender); + given(queueSender.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -426,19 +303,22 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSender).setDisableMessageID(true); + verify(queueSender).setDisableMessageTimestamp(true); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } /** * Test the setting of the JmsTemplate properties. */ + @Test public void testBeanProperties() throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); - assertTrue("connection factory ok", template.getConnectionFactory() == mockQueueConnectionFactory); + assertTrue("connection factory ok", template.getConnectionFactory() == queueConnectionFactory); JmsTemplate102 s102 = createTemplate(); try { @@ -452,7 +332,7 @@ public void testBeanProperties() throws Exception { // The default is for the JmsTemplate102 to send to queues. // Test to make sure exeception is thrown and has reasonable message. s102 = createTemplate(); - s102.setConnectionFactory(mockTopicConnectionFactory); + s102.setConnectionFactory(topicConnectionFactory); try { s102.afterPropertiesSet(); fail("IllegalArgumentException not thrown. Mismatch of Destination and ConnectionFactory types."); @@ -462,7 +342,7 @@ public void testBeanProperties() throws Exception { } s102 = createTemplate(); - s102.setConnectionFactory(mockQueueConnectionFactory); + s102.setConnectionFactory(queueConnectionFactory); s102.setPubSubDomain(true); try { s102.afterPropertiesSet(); @@ -477,6 +357,7 @@ public void testBeanProperties() throws Exception { * Test the method send(String destination, MessgaeCreator c) using * a queue and default QOS values. */ + @Test public void testSendStringQueue() throws Exception { sendQueue(true, false, false, true); } @@ -485,6 +366,7 @@ public void testSendStringQueue() throws Exception { * Test the method send(String destination, MessageCreator c) when * explicit QOS parameters are enabled, using a queue. */ + @Test public void testSendStringQueueWithQOS() throws Exception { sendQueue(false, false, false, false); } @@ -492,6 +374,7 @@ public void testSendStringQueueWithQOS() throws Exception { /** * Test the method send(MessageCreator c) using default QOS values. */ + @Test public void testSendDefaultDestinationQueue() throws Exception { sendQueue(true, false, true, true); } @@ -499,6 +382,7 @@ public void testSendDefaultDestinationQueue() throws Exception { /** * Test the method send(MessageCreator c) using explicit QOS values. */ + @Test public void testSendDefaultDestinationQueueWithQOS() throws Exception { sendQueue(false, false, true, false); } @@ -507,6 +391,7 @@ public void testSendDefaultDestinationQueueWithQOS() throws Exception { * Test the method send(String destination, MessageCreator c) using * a topic and default QOS values. */ + @Test public void testSendStringTopic() throws Exception { sendTopic(true, false); } @@ -515,6 +400,7 @@ public void testSendStringTopic() throws Exception { * Test the method send(String destination, MessageCreator c) using explicit * QOS values. */ + @Test public void testSendStringTopicWithQOS() throws Exception { sendTopic(false, false); } @@ -523,6 +409,7 @@ public void testSendStringTopicWithQOS() throws Exception { * Test the method send(Destination queue, MessgaeCreator c) using * a queue and default QOS values. */ + @Test public void testSendQueue() throws Exception { sendQueue(true, false, false, true); } @@ -531,6 +418,7 @@ public void testSendQueue() throws Exception { * Test the method send(Destination queue, MessageCreator c) sing explicit * QOS values. */ + @Test public void testSendQueueWithQOS() throws Exception { sendQueue(false, false, false, false); } @@ -539,6 +427,7 @@ public void testSendQueueWithQOS() throws Exception { * Test the method send(Destination queue, MessgaeCreator c) using * a topic and default QOS values. */ + @Test public void testSendTopic() throws Exception { sendTopic(true, false); } @@ -547,6 +436,7 @@ public void testSendTopic() throws Exception { * Test the method send(Destination queue, MessageCreator c) using explicity * QOS values. */ + @Test public void testSendTopicWithQOS() throws Exception { sendQueue(false, false, false, true); } @@ -560,62 +450,30 @@ private void sendQueue( throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); if (useDefaultDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } if (disableIdAndTimestamp) { template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); } - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); + TextMessage message = mock(TextMessage.class); - if (disableIdAndTimestamp) { - mockQueueSender.setDisableMessageID(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.setDisableMessageTimestamp(true); - queueSenderControl.setVoidCallable(1); - } - mockQueueSession.createSender(this.mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("just testing"); - queueSessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); - } + given(queueSession.createSender(this.queue)).willReturn(queueSender); + given(queueSession.createTextMessage("just testing")).willReturn(message); - if (ignoreQOS) { - mockQueueSender.send(mockMessage); - } - else { + if (!ignoreQOS) { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockQueueSender.send(mockMessage, deliveryMode, priority, timeToLive); } - queueSenderControl.setVoidCallable(1); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); if (useDefaultDestination) { template.send(new MessageCreator() { @@ -627,7 +485,7 @@ public Message createMessage(Session session) throws JMSException { } else { if (explicitQueue) { - template.send(mockQueue, new MessageCreator() { + template.send(queue, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("just testing"); @@ -645,61 +503,54 @@ public Message createMessage(Session session) } } - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); - queueSenderControl.verify(); + if (disableIdAndTimestamp) { + verify(queueSender).setDisableMessageID(true); + verify(queueSender).setDisableMessageTimestamp(true); + } + + if (useTransactedTemplate()) { + verify(queueSession).commit(); + } + + if (ignoreQOS) { + verify(queueSender).send(message); + } + else { + verify(queueSender).send(message, deliveryMode, priority, timeToLive); + } + + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } private void sendTopic(boolean ignoreQOS, boolean explicitTopic) throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); - - mockTopicSession.createPublisher(this.mockTopic); - topicSessionControl.setReturnValue(mockTopicPublisher); - mockTopicSession.createTextMessage("just testing"); - topicSessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockTopicSession.commit(); - topicSessionControl.setVoidCallable(1); - } - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - + TopicPublisher topicPublisher = mock(TopicPublisher.class); + TextMessage message = mock(TextMessage.class); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(this.topic)).willReturn(topicPublisher); + given(topicSession.createTextMessage("just testing")).willReturn(message); if (ignoreQOS) { - mockTopicPublisher.publish(mockMessage); + topicPublisher.publish(message); } else { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockTopicPublisher.publish(mockMessage, deliveryMode, priority, timeToLive); + topicPublisher.publish(message, deliveryMode, priority, timeToLive); } - topicPublisherControl.replay(); template.setPubSubDomain(true); if (explicitTopic) { - template.send(mockTopic, new MessageCreator() { + template.send(topic, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { @@ -717,163 +568,175 @@ public Message createMessage(Session session) }); } - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); - topicPublisherControl.verify(); + if (useTransactedTemplate()) { + verify(topicSession).commit(); + } + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); + verify(jndiContext).close(); } + @Test public void testConverter() throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); + TextMessage message = mock(TextMessage.class); - mockQueueSession.createSender(this.mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("Hello world"); - queueSessionControl.setReturnValue(mockMessage); + given(queueSession.createSender(this.queue)).willReturn(queueSender); + given(queueSession.createTextMessage("Hello world")).willReturn(message); + + template.convertAndSend(queue, s); if (useTransactedTemplate()) { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); + verify(queueSession).commit(); } - - mockQueueSender.send(mockMessage); - queueSenderControl.setVoidCallable(1); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); - - template.convertAndSend(mockQueue, s); - - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); - queueSenderControl.verify(); + verify(queueSender).send(message); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } + @Test public void testQueueReceiveDefaultDestination() throws Exception { doTestReceive(false, false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveDestination() throws Exception { doTestReceive(false, true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(false, true, false, false, true, false, false, 1000); } + @Test public void testQueueReceiveStringDestination() throws Exception { doTestReceive(false, false, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(false, false, true, false, false, true, true, 1000); } + @Test public void testQueueReceiveDestinationWithSelector() throws Exception { doTestReceive(false, true, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(false, true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveStringDestinationWithSelector() throws Exception { doTestReceive(false, false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(false, false, true, true, false, false, false, 1000); } + @Test public void testQueueReceiveAndConvertStringDestination() throws Exception { doTestReceive(false, false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDestination() throws Exception { doTestReceive(false, true, false, true, false, false, true, 1000); } + @Test public void testQueueReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(false, false, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveAndConvertStringDestinationWithSelector() throws Exception { doTestReceive(false, false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(false, true, false, true, false, true, false, 1000); } + @Test public void testTopicReceiveDefaultDestination() throws Exception { doTestReceive(true, false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveDestination() throws Exception { doTestReceive(true, true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(true, true, false, false, true, false, false, 1000); } + @Test public void testTopicReceiveStringDestination() throws Exception { doTestReceive(true, false, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testTopicReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(true, false, true, false, false, true, true, 1000); } + @Test public void testTopicReceiveDestinationWithSelector() throws Exception { doTestReceive(true, true, false, false, false, true, false, 1000); } + @Test public void testTopicReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(true, true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveStringDestinationWithSelector() throws Exception { doTestReceive(true, false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(true, false, true, true, false, false, false, 1000); } + @Test public void testTopicReceiveAndConvertStringDestination() throws Exception { doTestReceive(true, false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDestination() throws Exception { doTestReceive(true, true, false, true, false, false, true, 1000); } + @Test public void testTopicReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(true, false, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testTopicReceiveAndConvertStringDestinationWithSelector() throws Exception { doTestReceive(true, false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(true, true, false, true, false, true, false, 1000); } @@ -886,41 +749,38 @@ private void doTestReceive( JmsTemplate102 template = createTemplate(); template.setPubSubDomain(pubSub); - if (pubSub) { - template.setConnectionFactory(mockTopicConnectionFactory); - } - else { - template.setConnectionFactory(mockQueueConnectionFactory); - } + template.setConnectionFactory(pubSub ? topicConnectionFactory : queueConnectionFactory); // Override the default settings for client ack used in the test setup. // Can't use Session.getAcknowledgeMode() if (pubSub) { - topicConnectionControl.reset(); + reset(topicConnection); if (clientAcknowledge) { template.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE); + given(topicConnection.createTopicSession( + useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE)).willReturn(topicSession); } else { template.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); + given(topicConnection.createTopicSession( + useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE)).willReturn(topicSession); } - topicConnectionControl.setReturnValue(mockTopicSession); } else { - queueConnectionControl.reset(); + reset(queueConnection); if (clientAcknowledge) { template.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE); + given(queueConnection.createQueueSession( + useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE)).willReturn(queueSession); } else { template.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); + given(queueConnection.createQueueSession( + useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE)).willReturn(queueSession); } - queueConnectionControl.setReturnValue(mockQueueSession); } - Destination dest = pubSub ? (Destination) mockTopic : (Destination) mockQueue; + Destination dest = pubSub ? (Destination) topic : (Destination) queue; if (useDefaultDestination) { template.setDefaultDestination(dest); @@ -930,94 +790,38 @@ private void doTestReceive( } template.setReceiveTimeout(timeout); - if (pubSub) { - mockTopicConnection.start(); - topicConnectionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - } - else { - mockQueueConnection.start(); - queueConnectionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - } String selectorString = "selector"; - MockControl messageConsumerControl = null; - MessageConsumer mockMessageConsumer = null; - - if (pubSub) { - messageConsumerControl = MockControl.createControl(TopicSubscriber.class); - TopicSubscriber mockTopicSubscriber = (TopicSubscriber) messageConsumerControl.getMock(); - mockMessageConsumer = mockTopicSubscriber; - mockTopicSession.createSubscriber(mockTopic, messageSelector ? selectorString : null, noLocal); - topicSessionControl.setReturnValue(mockTopicSubscriber); - } - else { - messageConsumerControl = MockControl.createControl(QueueReceiver.class); - QueueReceiver mockQueueReceiver = (QueueReceiver) messageConsumerControl.getMock(); - mockMessageConsumer = mockQueueReceiver; - mockQueueSession.createReceiver(mockQueue, messageSelector ? selectorString : null); - queueSessionControl.setReturnValue(mockQueueReceiver); - } - - if (useTransactedTemplate()) { - if (pubSub) { - mockTopicSession.commit(); - topicSessionControl.setVoidCallable(1); - } - else { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); - } - } + MessageConsumer messageConsumer = null; if (pubSub) { - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); + TopicSubscriber topicSubscriber = mock(TopicSubscriber.class); + messageConsumer = topicSubscriber; + given(topicSession.createSubscriber(topic, + messageSelector ? selectorString : null, noLocal)).willReturn(topicSubscriber); } else { - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); + QueueReceiver queueReceiver = mock(QueueReceiver.class); + messageConsumer = queueReceiver; + given(queueSession.createReceiver(queue, + messageSelector ? selectorString : null)).willReturn(queueReceiver); } - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + TextMessage textMessage = mock(TextMessage.class); if (testConverter) { - mockMessage.getText(); - messageControl.setReturnValue("Hello World!"); - } - if (!useTransactedSession() && clientAcknowledge) { - mockMessage.acknowledge(); - messageControl.setVoidCallable(1); - } - - if (pubSub) { - topicSessionControl.replay(); - topicConnectionControl.replay(); - } - else { - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(textMessage.getText()).willReturn("Hello World!"); } - messageControl.replay(); if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) { - mockMessageConsumer.receiveNoWait(); + given(messageConsumer.receiveNoWait()).willReturn(textMessage); } else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { - mockMessageConsumer.receive(); + given(messageConsumer.receive()).willReturn(textMessage); } else { - mockMessageConsumer.receive(timeout); + given(messageConsumer.receive(timeout)).willReturn(textMessage); } - messageConsumerControl.setReturnValue(mockMessage); - mockMessageConsumer.close(); - messageConsumerControl.setVoidCallable(1); - - messageConsumerControl.replay(); Message message = null; String textFromMessage = null; @@ -1056,112 +860,123 @@ else if (explicitDestination) { } } - if (pubSub) { - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + if (testConverter) { + assertEquals("Message text should be equal", "Hello World!", textFromMessage); } else { - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + assertEquals("Messages should refer to the same object", message, textMessage); } - messageConsumerControl.verify(); - messageControl.verify(); - if (testConverter) { - assertEquals("Message text should be equal", "Hello World!", textFromMessage); + if (pubSub) { + verify(topicConnection).start(); + verify(topicConnection).close(); + verify(topicSession).close(); } else { - assertEquals("Messages should refer to the same object", message, mockMessage); + verify(queueConnection).start(); + verify(queueConnection).close(); + verify(queueSession).close(); + } + + + if (useTransactedTemplate()) { + if (pubSub) { + verify(topicSession).commit(); + } + else { + verify(queueSession).commit(); + } + } + + if (!useTransactedSession() && clientAcknowledge) { + verify(textMessage).acknowledge(); } + + verify(messageConsumer).close(); } + @Test public void testIllegalStateException() throws Exception { doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class); } + @Test public void testInvalidClientIDException() throws Exception { doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class); } + @Test public void testInvalidDestinationException() throws Exception { doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class); } + @Test public void testInvalidSelectorException() throws Exception { doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class); } + @Test public void testJmsSecurityException() throws Exception { doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class); } + @Test public void testMessageEOFException() throws Exception { doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class); } + @Test public void testMessageFormatException() throws Exception { doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class); } + @Test public void testMessageNotReadableException() throws Exception { doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class); } + @Test public void testMessageNotWriteableException() throws Exception { doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class); } + @Test public void testResourceAllocationException() throws Exception { doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class); } + @Test public void testTransactionInProgressException() throws Exception { doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class); } + @Test public void testTransactionRolledBackException() throws Exception { doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class); } + @Test 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(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); - - queueSessionControl.reset(); - mockQueueSession.createSender(mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("Hello world"); - queueSessionControl.setReturnValue(mockMessage); - - mockQueueSender.send(mockMessage); - queueSenderControl.setThrowable(original, 1); - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); + QueueSender queueSender = mock(QueueSender.class); + TextMessage textMessage = mock(TextMessage.class); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); + reset(queueSession); + given(queueSession.createSender(queue)).willReturn(queueSender); + given(queueSession.createTextMessage("Hello world")).willReturn(textMessage); - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + willThrow(original).given(queueSender).send(textMessage); try { - template.convertAndSend(mockQueue, s); + template.convertAndSend(queue, s); fail("Should have thrown JmsException"); } catch (JmsException wrappedEx) { @@ -1170,10 +985,9 @@ protected void doTestJmsException(JMSException original, Class thrownExceptionCl assertEquals(original, wrappedEx.getCause()); } - queueSenderControl.verify(); - queueSessionControl.verify(); - queueConnectionControl.verify(); - queueConnectionFactoryControl.verify(); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java index 2ff2c9afda06..1ac040f3f86d 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java @@ -16,6 +16,16 @@ package org.springframework.jms.core; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; @@ -32,11 +42,9 @@ 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.junit.Before; +import org.junit.Test; import org.springframework.jms.InvalidClientIDException; import org.springframework.jms.InvalidDestinationException; import org.springframework.jms.InvalidSelectorException; @@ -66,22 +74,13 @@ * @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; +public class JmsTemplateTests { - private MockControl sessionControl; - private Session mockSession; - - private MockControl queueControl; - private Destination mockQueue; + private Context jndiContext; + private ConnectionFactory connectionFactory; + private Connection connection; + private Session session; + private Destination queue; private int deliveryMode = DeliveryMode.PERSISTENT; private int priority = 9; @@ -91,41 +90,19 @@ public class JmsTemplateTests extends TestCase { /** * Create the mock objects for testing. */ - @Override - 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(); + @Before + public void setupMocks() throws Exception { + jndiContext = mock(Context.class); + connectionFactory = mock(ConnectionFactory.class); + connection = mock(Connection.class); + session = mock(Session.class); + queue = mock(Queue.class); - 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); + given(connectionFactory.createConnection()).willReturn(connection); + given(connection.createSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(session.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testDestination")).willReturn(queue); } private JmsTemplate createTemplate() { @@ -134,7 +111,7 @@ private JmsTemplate createTemplate() { destMan.setJndiTemplate(new JndiTemplate() { @Override protected Context createInitialContext() { - return mockJndiContext; + return jndiContext; } }); template.setDestinationResolver(destMan); @@ -151,6 +128,7 @@ protected boolean useTransactedTemplate() { } + @Test public void testExceptionStackTrace() { JMSException jmsEx = new JMSException("could not connect"); Exception innerEx = new Exception("host not found"); @@ -163,29 +141,14 @@ public void testExceptionStackTrace() { assertTrue("inner jms exception not found", trace.indexOf("host not found") > 0); } + @Test public void testProducerCallback() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); - 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(); + MessageProducer messageProducer = mock(MessageProducer.class); + given(session.createProducer(null)).willReturn(messageProducer); + given(messageProducer.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -196,40 +159,21 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } + @Test public void testProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); 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(); + MessageProducer messageProducer = mock(MessageProducer.class); + given(session.createProducer(null)).willReturn(messageProducer); + given(messageProducer.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -240,26 +184,20 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(messageProducer).setDisableMessageID(true); + verify(messageProducer).setDisableMessageTimestamp(true); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } /** * Test the method execute(SessionCallback action). */ + @Test 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.setConnectionFactory(connectionFactory); template.execute(new SessionCallback() { @Override @@ -269,35 +207,16 @@ public Object doInJms(Session session) throws JMSException { } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(session).close(); + verify(connection).close(); } + @Test public void testSessionCallbackWithinSynchronizedTransaction() throws Exception { - SingleConnectionFactory scf = new SingleConnectionFactory(mockConnectionFactory); + SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); JmsTemplate template = createTemplate(); template.setConnectionFactory(scf); - mockConnection.start(); - connectionControl.setVoidCallable(1); - // 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() { @@ -315,8 +234,8 @@ public Object doInJms(Session session) throws JMSException { } }); - assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, null, false)); - assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)); + assertSame(session, ConnectionFactoryUtils.getTransactionalSession(scf, null, false)); + assertSame(session, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)); TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf); Connection tac = tacf.createConnection(); @@ -339,15 +258,20 @@ public Object doInJms(Session session) throws JMSException { } assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(connection).start(); + if (useTransactedTemplate()) { + verify(session).commit(); + } + verify(session).close(); + verify(connection).stop(); + verify(connection).close(); } /** * Test sending to a destination using the method * send(Destination d, MessageCreator messageCreator) */ + @Test public void testSendDestination() throws Exception { doTestSendDestination(true, false, true, false); } @@ -356,6 +280,7 @@ public void testSendDestination() throws Exception { * Test seding to a destination using the method * send(String d, MessageCreator messageCreator) */ + @Test public void testSendDestinationName() throws Exception { doTestSendDestination(false, false, true, false); } @@ -364,6 +289,7 @@ public void testSendDestinationName() throws Exception { * Test sending to a destination using the method * send(Destination d, MessageCreator messageCreator) using QOS parameters. */ + @Test public void testSendDestinationWithQOS() throws Exception { doTestSendDestination(true, false, false, true); } @@ -372,6 +298,7 @@ public void testSendDestinationWithQOS() throws Exception { * Test sending to a destination using the method * send(String d, MessageCreator messageCreator) using QOS parameters. */ + @Test public void testSendDestinationNameWithQOS() throws Exception { doTestSendDestination(false, false, false, true); } @@ -379,6 +306,7 @@ public void testSendDestinationNameWithQOS() throws Exception { /** * Test sending to the default destination. */ + @Test public void testSendDefaultDestination() throws Exception { doTestSendDestination(true, true, true, true); } @@ -386,6 +314,7 @@ public void testSendDefaultDestination() throws Exception { /** * Test sending to the default destination name. */ + @Test public void testSendDefaultDestinationName() throws Exception { doTestSendDestination(false, true, true, true); } @@ -393,6 +322,7 @@ public void testSendDefaultDestinationName() throws Exception { /** * Test sending to the default destination using explicit QOS parameters. */ + @Test public void testSendDefaultDestinationWithQOS() throws Exception { doTestSendDestination(true, true, false, false); } @@ -400,6 +330,7 @@ public void testSendDefaultDestinationWithQOS() throws Exception { /** * Test sending to the default destination name using explicit QOS parameters. */ + @Test public void testSendDefaultDestinationNameWithQOS() throws Exception { doTestSendDestination(false, true, false, false); } @@ -414,13 +345,13 @@ private void doTestSendDestination( boolean ignoreQOS, boolean disableIdAndTimestamp) throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); String destinationName = "testDestination"; if (useDefaultDestination) { if (explicitDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } else { template.setDefaultDestinationName(destinationName); @@ -431,51 +362,18 @@ private void doTestSendDestination( 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(); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - 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); - } + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("just testing")).willReturn(textMessage); - if (ignoreQOS) { - mockMessageProducer.send(mockMessage); - } - else { + if (!ignoreQOS) { 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() { @@ -487,7 +385,7 @@ public Message createMessage(Session session) throws JMSException { } else { if (explicitDestination) { - template.send(mockQueue, new MessageCreator() { + template.send(queue, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("just testing"); @@ -504,119 +402,131 @@ public Message createMessage(Session session) throws JMSException { } } - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); - messageProducerControl.verify(); + if (useTransactedTemplate()) { + verify(session).commit(); + } + + if (disableIdAndTimestamp) { + verify(messageProducer).setDisableMessageID(true); + verify(messageProducer).setDisableMessageTimestamp(true); + } + + if (ignoreQOS) { + verify(messageProducer).send(textMessage); + } + else { + verify(messageProducer).send(textMessage, deliveryMode, priority, timeToLive); + } + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } + @Test public void testConverter() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); 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(); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - mockSession.createProducer(mockQueue); - sessionControl.setReturnValue(mockMessageProducer); - mockSession.createTextMessage("Hello world"); - sessionControl.setReturnValue(mockMessage); + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("Hello world")).willReturn(textMessage); - mockMessageProducer.send(mockMessage); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); + template.convertAndSend(queue, s); + verify(messageProducer).send(textMessage); + verify(messageProducer).close(); if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); + verify(session).commit(); } - - 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(); + verify(session).close(); + verify(connection).close(); } + @Test public void testReceiveDefaultDestination() throws Exception { doTestReceive(true, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDefaultDestinationName() throws Exception { doTestReceive(false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestination() throws Exception { doTestReceive(true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(true, false, false, true, false, false, 1000); } + @Test public void testReceiveDestinationName() throws Exception { doTestReceive(false, false, false, false, false, true, 1000); } + @Test public void testReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(true, true, false, false, true, true, 1000); } + @Test public void testReceiveDefaultDestinationNameWithSelector() throws Exception { doTestReceive(false, true, false, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveDestinationWithSelector() throws Exception { doTestReceive(true, false, false, false, true, false, 1000); } + @Test public void testReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestinationNameWithSelector() throws Exception { doTestReceive(false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(true, true, true, false, false, false, 1000); } + @Test public void testReceiveAndConvertDefaultDestinationName() throws Exception { doTestReceive(false, true, true, false, false, false, 1000); } + @Test public void testReceiveAndConvertDestinationName() throws Exception { doTestReceive(false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveAndConvertDestination() throws Exception { doTestReceive(true, false, true, false, false, true, 1000); } + @Test public void testReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(true, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveAndConvertDestinationNameWithSelector() throws Exception { doTestReceive(false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(true, false, true, false, true, false, 1000); } @@ -627,13 +537,13 @@ private void doTestReceive( throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); String destinationName = "testDestination"; if (useDefaultDestination) { if (explicitDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } else { template.setDefaultDestinationName(destinationName); @@ -644,67 +554,34 @@ private void doTestReceive( } template.setReceiveTimeout(timeout); - mockConnection.start(); - connectionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - MockControl messageConsumerControl = MockControl.createControl(MessageConsumer.class); - MessageConsumer mockMessageConsumer = (MessageConsumer) messageConsumerControl.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); String selectorString = "selector"; - mockSession.createConsumer(mockQueue, messageSelector ? selectorString : null); - sessionControl.setReturnValue(mockMessageConsumer); + given(session.createConsumer(queue, + messageSelector ? selectorString : null)).willReturn(messageConsumer); - 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); - } + if (!useTransactedTemplate() && !useTransactedSession()) { + given(session.getAcknowledgeMode()).willReturn( + clientAcknowledge ? Session.CLIENT_ACKNOWLEDGE + : Session.AUTO_ACKNOWLEDGE); } - mockSession.close(); - sessionControl.setVoidCallable(1); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + TextMessage textMessage = mock(TextMessage.class); if (testConverter) { - mockMessage.getText(); - messageControl.setReturnValue("Hello World!"); - } - if (!useTransactedSession() && clientAcknowledge) { - mockMessage.acknowledge(); - messageControl.setVoidCallable(1); + given(textMessage.getText()).willReturn("Hello World!"); } - sessionControl.replay(); - connectionControl.replay(); - messageControl.replay(); - if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) { - mockMessageConsumer.receiveNoWait(); + given(messageConsumer.receiveNoWait()).willReturn(textMessage); } else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { - mockMessageConsumer.receive(); + given(messageConsumer.receive()).willReturn(textMessage); } else { - mockMessageConsumer.receive(timeout); + given(messageConsumer.receive(timeout)).willReturn(textMessage); } - messageConsumerControl.setReturnValue(mockMessage); - mockMessageConsumer.close(); - messageConsumerControl.setVoidCallable(1); - - messageConsumerControl.replay(); - Message message = null; String textFromMessage = null; @@ -721,12 +598,12 @@ else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { else if (explicitDestination) { if (testConverter) { textFromMessage = (String) - (messageSelector ? template.receiveSelectedAndConvert(mockQueue, selectorString) : - template.receiveAndConvert(mockQueue)); + (messageSelector ? template.receiveSelectedAndConvert(queue, selectorString) : + template.receiveAndConvert(queue)); } else { - message = (messageSelector ? template.receiveSelected(mockQueue, selectorString) : - template.receive(mockQueue)); + message = (messageSelector ? template.receiveSelected(queue, selectorString) : + template.receive(queue)); } } else { @@ -741,105 +618,107 @@ else if (explicitDestination) { } } - 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); + assertEquals("Messages should refer to the same object", message, textMessage); + } + + verify(connection).start(); + verify(connection).close(); + if (useTransactedTemplate()) { + verify(session).commit(); } + verify(session).close(); + if (!useTransactedSession() && clientAcknowledge) { + verify(textMessage).acknowledge(); + } + verify(messageConsumer).close(); } + @Test public void testIllegalStateException() throws Exception { doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class); } + @Test public void testInvalidClientIDException() throws Exception { doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class); } + @Test public void testInvalidDestinationException() throws Exception { doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class); } + @Test public void testInvalidSelectorException() throws Exception { doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class); } + @Test public void testJmsSecurityException() throws Exception { doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class); } + @Test public void testMessageEOFException() throws Exception { doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class); } + @Test public void testMessageFormatException() throws Exception { doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class); } + @Test public void testMessageNotReadableException() throws Exception { doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class); } + @Test public void testMessageNotWriteableException() throws Exception { doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class); } + @Test public void testResourceAllocationException() throws Exception { doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class); } + @Test public void testTransactionInProgressException() throws Exception { doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class); } + @Test public void testTransactionRolledBackException() throws Exception { doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class); } + @Test 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.setConnectionFactory(connectionFactory); 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); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); + reset(session); + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("Hello world")).willReturn(textMessage); - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); + willThrow(original).given(messageProducer).send(textMessage); try { - template.convertAndSend(mockQueue, s); + template.convertAndSend(queue, s); fail("Should have thrown JmsException"); } catch (JmsException wrappedEx) { @@ -848,10 +727,9 @@ protected void doTestJmsException(JMSException original, Class thrownExceptionCl assertEquals(original, wrappedEx.getCause()); } - messageProducerControl.verify(); - sessionControl.verify(); - connectionControl.verify(); - connectionFactoryControl.verify(); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java index 30b71cf18235..15eefc873f75 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,26 +15,26 @@ */ package org.springframework.jms.core.support; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + import java.util.ArrayList; import java.util.List; import javax.jms.ConnectionFactory; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.jms.core.JmsTemplate; /** * @author Mark Pollack * @since 24.9.2004 */ -public class JmsGatewaySupportTests extends TestCase { +public class JmsGatewaySupportTests { + @Test public void testJmsGatewaySupportWithConnectionFactory() throws Exception { - MockControl connectionFactoryControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock(); - connectionFactoryControl.replay(); + ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); final List test = new ArrayList(); JmsGatewaySupport gateway = new JmsGatewaySupport() { @Override @@ -47,9 +47,9 @@ protected void initGateway() { assertEquals("Correct ConnectionFactory", mockConnectionFactory, gateway.getConnectionFactory()); assertEquals("Correct JmsTemplate", mockConnectionFactory, gateway.getJmsTemplate().getConnectionFactory()); assertEquals("initGatway called", test.size(), 1); - connectionFactoryControl.verify(); - } + + @Test public void testJmsGatewaySupportWithJmsTemplate() throws Exception { JmsTemplate template = new JmsTemplate(); final List test = new ArrayList(); diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java index 6bd5c5712364..8dad2a08e037 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,14 @@ package org.springframework.jms.listener; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.HashSet; @@ -29,12 +36,8 @@ import javax.jms.MessageListener; import javax.jms.Session; -import org.easymock.EasyMock; -import org.easymock.MockControl; -import org.easymock.internal.AlwaysMatcher; import org.junit.Before; import org.junit.Test; - import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.task.TaskExecutor; import org.springframework.jms.StubQueue; @@ -91,38 +94,20 @@ public void testSettingConcurrentConsumersToANegativeValueIsNotAllowed() throws @Test public void testContextRefreshedEventDoesNotStartTheConnectionIfAutoStartIsSetToFalse() 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(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(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(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); - mockConnection.replay(); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -134,49 +119,26 @@ public void testContextRefreshedEventDoesNotStartTheConnectionIfAutoStartIsSetTo context.getBeanFactory().registerSingleton("messageListenerContainer", this.container); context.refresh(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); } @Test public void testContextRefreshedEventStartsTheConnectionByDefault() 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(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(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(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(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(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -187,48 +149,31 @@ public void testContextRefreshedEventStartsTheConnectionByDefault() throws Excep context.getBeanFactory().registerSingleton("messageListenerContainer", this.container); context.refresh(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testCorrectSessionExposedForSessionAwareMessageListenerInvocation() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); + final Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // 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(); + given(session.getTransacted()).willReturn(false); + given(session.getAcknowledgeMode()).willReturn(Session.AUTO_ACKNOWLEDGE); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(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 ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final HashSet failure = new HashSet(); @@ -250,52 +195,33 @@ public void onMessage(Message message, Session sess) { this.container.afterPropertiesSet(); this.container.start(); - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); messageConsumer.sendMessage(message); if (!failure.isEmpty()) { fail(failure.iterator().next().toString()); } - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test 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 Session session = mock(Session.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + given(session.getTransacted()).willReturn(false); + given(session.getAcknowledgeMode()).willReturn(Session.AUTO_ACKNOWLEDGE); + + Connection connection = mock(Connection.class); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); + + final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final TestMessageListener listener = new TestMessageListener(); @@ -314,53 +240,36 @@ public void execute(Runnable task) { this.container.afterPropertiesSet(); this.container.start(); - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); messageConsumer.sendMessage(message); assertTrue(listener.executorInvoked); assertTrue(listener.listenerInvoked); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testRegisteredExceptionListenerIsInvokedOnException() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // 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(); + given(session.getTransacted()).willReturn(false); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(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(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final JMSException theException = new JMSException(EXCEPTION_MESSAGE); @@ -373,61 +282,44 @@ public void onMessage(Message message, Session session) throws JMSException { } }); - MockControl mockExceptionListener = MockControl.createControl(ExceptionListener.class); - ExceptionListener exceptionListener = (ExceptionListener) mockExceptionListener.getMock(); - exceptionListener.onException(theException); - mockExceptionListener.setVoidCallable(); - mockExceptionListener.replay(); + ExceptionListener exceptionListener = mock(ExceptionListener.class); this.container.setExceptionListener(exceptionListener); this.container.afterPropertiesSet(); this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockExceptionListener.verify(); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(exceptionListener).onException(theException); } @Test public void testRegisteredErrorHandlerIsInvokedOnException() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - Session session = EasyMock.createMock(Session.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - EasyMock.expectLastCall().andReturn(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - EasyMock.expectLastCall().andReturn(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - EasyMock.expectLastCall().andReturn(false); - EasyMock.replay(session); + given(session.getTransacted()).willReturn(false); - Connection connection = EasyMock.createMock(Connection.class); - connection.setExceptionListener(this.container); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - EasyMock.expectLastCall().andReturn(session); - // and the connection is start()ed after the listener is registered... - connection.start(); - EasyMock.replay(connection); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); - ConnectionFactory connectionFactory = EasyMock.createMock(ConnectionFactory.class); - connectionFactory.createConnection(); - EasyMock.expectLastCall().andReturn(connection); - EasyMock.replay(connectionFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final IllegalStateException theException = new IllegalStateException("intentional test failure"); @@ -440,58 +332,42 @@ public void onMessage(Message message, Session session) throws JMSException { } }); - ErrorHandler errorHandler = EasyMock.createMock(ErrorHandler.class); - errorHandler.handleError(theException); - EasyMock.expectLastCall(); - EasyMock.replay(errorHandler); + ErrorHandler errorHandler = mock(ErrorHandler.class); this.container.setErrorHandler(errorHandler); this.container.afterPropertiesSet(); this.container.start(); // manually trigger an Exception with the above bad MessageListener... - Message message = EasyMock.createMock(Message.class); - EasyMock.replay(message); + Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - EasyMock.verify(errorHandler, message, session, connection, connectionFactory); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(errorHandler).handleError(theException); } @Test public void testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_Propagate() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // 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(); + given(session.getTransacted()).willReturn(false); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(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(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -505,17 +381,13 @@ public void onMessage(Message message) { this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test @@ -524,39 +396,22 @@ public void testTransactedSessionsGetRollbackLogicAppliedAndThatExceptionsStillD final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // 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(); + given(session.getTransacted()).willReturn(true); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(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(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -570,65 +425,34 @@ public void onMessage(Message message) { this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + // Session is rolled back 'cos it is transacted... + verify(session).rollback(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test 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(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(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(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(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(); + + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -638,10 +462,11 @@ public void testDestroyClosesConsumersSessionsAndConnectionInThatOrder() throws this.container.start(); this.container.destroy(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(messageConsumer).close(); + verify(session).close(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(connection).close(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java index a41851b5ecfa..0781e2916d95 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,13 @@ package org.springframework.jms.listener.adapter; import static org.junit.Assert.*; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import javax.jms.BytesMessage; import javax.jms.InvalidDestinationException; @@ -30,8 +37,9 @@ import javax.jms.TopicPublisher; import javax.jms.TopicSession; -import org.easymock.MockControl; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.SimpleMessageConverter102; /** @@ -40,6 +48,7 @@ * @author Rick Evans * @author Chris Beams */ +@Deprecated public final class MessageListenerAdapter102Tests { private static final String TEXT = "The Runaways"; @@ -50,48 +59,36 @@ public final class MessageListenerAdapter102Tests { @Test public void testWithMessageContentsDelegateForBytesMessage() throws Exception { - MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class); - BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock(); + BytesMessage bytesMessage = mock(BytesMessage.class); // 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(); + given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + byte[] bytes = (byte[]) invocation.getArguments()[0]; + ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); + return inputStream.read(bytes); + } + }); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); adapter.onMessage(bytesMessage); - mockDelegate.verify(); - mockBytesMessage.verify(); + verify(delegate).handleMessage(TEXT.getBytes()); } @Test 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(); + TextMessage textMessage = mock(TextMessage.class); + MessageDelegate delegate = mock(MessageDelegate.class); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test @@ -104,69 +101,38 @@ public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter1 @Test public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); + TextMessage textMessage = mock(TextMessage.class); - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setReturnValue(TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(textMessage)).willReturn(TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForQueue() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); + Queue destination = mock(Queue.class); - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); + + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -177,58 +143,30 @@ protected Object extractMessage(Message message) { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test 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(); + Topic destination = mock(Topic.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); // we want to fall back to the default... + + TextMessage responseTextMessage = mock(TextMessage.class); + TopicPublisher topicPublisher = mock(TopicPublisher.class); + TopicSession session = mock(TopicSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createPublisher(destination)).willReturn(topicPublisher); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -239,58 +177,30 @@ protected Object extractMessage(Message message) { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockTopicPublisher.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(topicPublisher).publish(responseTextMessage); + verify(topicPublisher).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test 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(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -300,44 +210,29 @@ protected Object extractMessage(Message message) { }; adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); + + TextMessage responseTextMessage = mock(TextMessage.class); + + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -350,57 +245,31 @@ protected Object extractMessage(Message message) { fail("expected InvalidDestinationException"); } catch (InvalidDestinationException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(delegate).handleMessage(sentTextMessage); } @Test 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(); + Queue destination = mock(Queue.class); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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!")); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + willThrow(new JMSException("Doe!")).given(queueSender).send(responseTextMessage); // 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 QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -413,30 +282,20 @@ protected Object extractMessage(Message message) { fail("expected JMSException"); } catch (JMSException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); - mockSentTextMessage.replay(); + final TextMessage sentTextMessage = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); - 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(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + willThrow(new IllegalArgumentException("Doe!")).given(delegate).handleMessage(sentTextMessage); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -448,10 +307,6 @@ protected Object extractMessage(Message message) { adapter.onMessage(sentTextMessage, session); fail("expected ListenerExecutionFailedException"); } catch (ListenerExecutionFailedException ex) { /* expected */ } - - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java index 8fdf93910883..c673f51a4474 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,19 @@ package org.springframework.jms.listener.adapter; -import static org.junit.Assert.*; - +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.io.Serializable; import javax.jms.BytesMessage; @@ -33,9 +44,9 @@ import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.MockControl; import org.junit.Test; - +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; @@ -59,161 +70,110 @@ public class MessageListenerAdapterTests { @Test public void testWithMessageContentsDelegateForTextMessage() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(TEXT); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(TEXT); } @Test public void testWithMessageContentsDelegateForBytesMessage() throws Exception { - MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class); - BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock(); + BytesMessage bytesMessage = mock(BytesMessage.class); // 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(); + given(bytesMessage.getBodyLength()).willReturn(new Long(TEXT.getBytes().length)); + given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + byte[] bytes = (byte[]) invocation.getArguments()[0]; + ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); + return inputStream.read(bytes); + } + }); + + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(bytesMessage); - mockDelegate.verify(); - mockBytesMessage.verify(); + verify(delegate).handleMessage(TEXT.getBytes()); } @Test 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(); + ObjectMessage objectMessage = mock(ObjectMessage.class); + given(objectMessage.getObject()).willReturn(NUMBER); + + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(objectMessage); - mockDelegate.verify(); - mockObjectMessage.verify(); + verify(delegate).handleMessage(NUMBER); } @Test 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(); + ObjectMessage objectMessage = mock(ObjectMessage.class); + given(objectMessage.getObject()).willReturn(OBJECT); + + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(objectMessage); - mockDelegate.verify(); - mockObjectMessage.verify(); + verify(delegate).handleMessage(OBJECT); } @Test public void testWithMessageDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); + TextMessage textMessage = mock(TextMessage.class); - MockControl mockDelegate = MockControl.createControl(MessageDelegate.class); - MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageDelegate delegate = mock(MessageDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test public void testWhenTheAdapterItselfIsTheDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.onMessage(textMessage); assertTrue(adapter.wasCalled()); - - mockTextMessage.verify(); } @Test public void testRainyDayWithNoApplicableHandlingMethods() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.setDefaultListenerMethod("walnutsRock"); adapter.onMessage(textMessage); assertFalse(adapter.wasCalled()); - - mockTextMessage.verify(); } @Test 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(); + TextMessage textMessage = mock(TextMessage.class); + MessageDelegate delegate = mock(MessageDelegate.class); + willThrow(exception).given(delegate).handleMessage(textMessage); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -230,9 +190,6 @@ protected void handleListenerException(Throwable ex) { // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - - mockDelegate.verify(); - mockTextMessage.verify(); } @Test @@ -257,68 +214,35 @@ public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() th @Test 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(); + TextMessage textMessage = mock(TextMessage.class); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(textMessage)).willReturn(TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - - mockDelegate.verify(); - mockTextMessage.verify(); } @Test 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(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn( + 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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); // we want to fall back to the default... + + TextMessage responseTextMessage = mock(TextMessage.class); + + QueueSender queueSender = mock(QueueSender.class); + Session session = mock(Session.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -329,59 +253,30 @@ protected Object extractMessage(Message message) { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test 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(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(null); - sentTextMessage.getJMSMessageID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(null); + given(sentTextMessage.getJMSMessageID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + MessageProducer messageProducer = mock(MessageProducer.class); + Session session = mock(Session.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(messageProducer); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -391,43 +286,26 @@ protected Object extractMessage(Message message) { }; adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockMessageProducer.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(messageProducer).send(responseTextMessage); + verify(messageProducer).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); + + TextMessage responseTextMessage = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -440,56 +318,30 @@ protected Object extractMessage(Message message) { fail("expected InvalidDestinationException"); } catch(InvalidDestinationException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); + Queue destination = mock(Queue.class); - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + MessageProducer messageProducer = mock(MessageProducer.class); + willThrow(new JMSException("Doe!")).given(messageProducer).send(responseTextMessage); + + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(messageProducer); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -502,29 +354,18 @@ protected Object extractMessage(Message message) { fail("expected JMSException"); } catch(JMSException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockMessageProducer.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(messageProducer).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test 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(); + final TextMessage message = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(message); - mockDelegate.setThrowable(new IllegalArgumentException("Dow!")); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + willThrow(new IllegalArgumentException("Doe!")).given(delegate).handleMessage(message); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -536,20 +377,12 @@ protected Object extractMessage(Message message) { adapter.onMessage(message, session); fail("expected ListenerExecutionFailedException"); } catch(ListenerExecutionFailedException ex) { /* expected */ } - - mockDelegate.verify(); - mockMessage.verify(); - mockSession.verify(); } @Test 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 TextMessage message = mock(TextMessage.class); + given(message.getText()).willReturn(TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter() { @Override @@ -559,18 +392,12 @@ protected void handleListenerException(Throwable ex) { }; adapter.setDefaultListenerMethod(null); adapter.onMessage(message); - - mockMessage.verify(); } @Test 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 TextMessage message = mock(TextMessage.class); + given(message.getText()).willReturn(TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter() { @Override @@ -584,25 +411,14 @@ protected String getListenerMethodName(Message originalMessage, Object extracted }; adapter.setDefaultListenerMethod(null); adapter.onMessage(message); - - mockMessage.verify(); } @Test 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 TextMessage sentTextMessage = mock(TextMessage.class); + final Session session = mock(Session.class); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -615,53 +431,25 @@ protected Object extractMessage(Message message) { adapter.onMessage(sentTextMessage, session); fail("expected MessageConversionException"); } catch(MessageConversionException ex) { /* expected */ } - - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); } @Test 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(); + Queue destination = mock(Queue.class); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(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(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + + Session session = mock(Session.class); + given(session.createProducer(destination)).willReturn(queueSender); + + ResponsiveJmsTextMessageReturningMessageDelegate delegate = mock(ResponsiveJmsTextMessageReturningMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(responseMessage); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -672,12 +460,9 @@ protected Object extractMessage(Message message) { adapter.setMessageConverter(null); adapter.onMessage(sentTextMessage, session); - mockDestination.verify(); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); - mockQueueSender.verify(); - mockResponseMessage.verify(); + verify(responseMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseMessage); + verify(queueSender).close(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java index f91da0b40cf3..ea98f9020678 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java @@ -16,12 +16,14 @@ package org.springframework.jms.listener.endpoint; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + 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; @@ -60,12 +62,10 @@ public void testActiveMQResourceAdapterSetup() { public void testWebSphereResourceAdapterSetup() throws Exception { Destination destination = new StubQueue(); - MockControl control = MockControl.createControl(DestinationResolver.class); - DestinationResolver destinationResolver = (DestinationResolver) control.getMock(); + DestinationResolver destinationResolver = mock(DestinationResolver.class); - destinationResolver.resolveDestinationName(null, "destinationname", false); - control.setReturnValue(destination); - control.replay(); + given(destinationResolver.resolveDestinationName(null, "destinationname", + false)).willReturn(destination); DefaultJmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory(); activationSpecFactory.setDestinationResolver(destinationResolver); @@ -73,8 +73,6 @@ public void testWebSphereResourceAdapterSetup() throws Exception { StubWebSphereActivationSpecImpl spec = (StubWebSphereActivationSpecImpl) activationSpecFactory .createActivationSpec(new StubWebSphereResourceAdapterImpl(), activationSpecConfig); - control.verify(); - assertEquals(destination, spec.getDestination()); assertEquals(5, spec.getMaxConcurrency()); assertEquals(3, spec.getMaxBatchSize()); diff --git a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java index 55736c4d2a9b..9cdbf3413686 100644 --- a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java @@ -16,9 +16,16 @@ package org.springframework.jms.remoting; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import java.io.Serializable; import java.util.Arrays; import java.util.Enumeration; + import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; @@ -30,71 +37,47 @@ import javax.jms.QueueSession; import javax.jms.Session; -import junit.framework.TestCase; -import org.easymock.MockControl; - -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller */ -public class JmsInvokerTests extends TestCase { +public class JmsInvokerTests { - private MockControl connectionFactoryControl; private QueueConnectionFactory mockConnectionFactory; - private MockControl connectionControl; private QueueConnection mockConnection; - private MockControl sessionControl; private QueueSession mockSession; - private MockControl queueControl; private Queue mockQueue; - @Override - protected void setUp() throws Exception { - connectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class); - mockConnectionFactory = (QueueConnectionFactory) connectionFactoryControl.getMock(); - - connectionControl = MockControl.createControl(QueueConnection.class); - mockConnection = (QueueConnection) connectionControl.getMock(); + @Before + public void setUpMocks() throws Exception { + mockConnectionFactory = mock(QueueConnectionFactory.class); + mockConnection = mock(QueueConnection.class); + mockSession = mock(QueueSession.class); + mockQueue = mock(Queue.class); - sessionControl = MockControl.createControl(QueueSession.class); - mockSession = (QueueSession) sessionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - mockConnectionFactory.createConnection(); - connectionFactoryControl.setReturnValue(mockConnection, 8); - - mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connectionControl.setReturnValue(mockSession, 8); - - mockConnection.start(); - connectionControl.setVoidCallable(8); - - connectionFactoryControl.replay(); - connectionControl.replay(); + given(mockConnectionFactory.createConnection()).willReturn(mockConnection); + given(mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(mockSession); } + @Test public void testJmsInvokerProxyFactoryBeanAndServiceExporter() throws Throwable { - sessionControl.replay(); - doTestJmsInvokerProxyFactoryBeanAndServiceExporter(false); } + @Test public void testJmsInvokerProxyFactoryBeanAndServiceExporterWithDynamicQueue() throws Throwable { - mockSession.createQueue("myQueue"); - sessionControl.setReturnValue(mockQueue, 8); - sessionControl.replay(); - + given(mockSession.createQueue("myQueue")).willReturn(mockQueue); doTestJmsInvokerProxyFactoryBeanAndServiceExporter(true); } @@ -110,14 +93,10 @@ private void doTestJmsInvokerProxyFactoryBeanAndServiceExporter(boolean dynamicQ JmsInvokerProxyFactoryBean pfb = new JmsInvokerProxyFactoryBean() { @Override protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException { - MockControl exporterSessionControl = MockControl.createControl(Session.class); - Session mockExporterSession = (Session) exporterSessionControl.getMock(); + Session mockExporterSession = mock(Session.class); ResponseStoringProducer mockProducer = new ResponseStoringProducer(); - mockExporterSession.createProducer(requestMessage.getJMSReplyTo()); - exporterSessionControl.setReturnValue(mockProducer); - exporterSessionControl.replay(); + given(mockExporterSession.createProducer(requestMessage.getJMSReplyTo())).willReturn(mockProducer); exporter.onMessage(requestMessage, mockExporterSession); - exporterSessionControl.verify(); assertTrue(mockProducer.closed); return mockProducer.response; } @@ -156,10 +135,6 @@ protected Message doExecuteRequest(Session session, Queue queue, Message request catch (IllegalAccessException ex) { // expected } - - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java index 7d4663a2859c..8ca5ad2e1f1a 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,24 @@ 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 static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; + +import java.io.ByteArrayInputStream; +import java.util.Random; import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; -import java.util.Arrays; + +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.springframework.jms.support.converter.SimpleMessageConverter102; /** * Unit tests for the {@link SimpleMessageConverter102} class. @@ -33,46 +41,28 @@ * @author Juergen Hoeller * @author Rick Evans */ -public final class SimpleMessageConverter102Tests extends TestCase { +public final class SimpleMessageConverter102Tests { + @Test 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(); + Session session = mock(Session.class); + BytesMessage message = mock(BytesMessage.class); byte[] content = new byte[5000]; + new Random().nextBytes(content); - session.createBytesMessage(); - sessionControl.setReturnValue(message, 1); - message.writeBytes(content); - messageControl.setVoidCallable(1); - message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]); - messageControl.setMatcher(new ArgumentsMatcher() { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); + given(session.createBytesMessage()).willReturn(message); + given(message.readBytes(any(byte[].class))).willAnswer(new Answer() { @Override - public boolean matches(Object[] arg0, Object[] arg1) { - byte[] one = (byte[]) arg0[0]; - byte[] two = (byte[]) arg1[0]; - return Arrays.equals(one, two); - } - - @Override - public String toString(Object[] arg0) { - return "bla"; + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteArrayInputStream.read((byte[])invocation.getArguments()[0]); } }); - 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(); + assertThat((byte[])converter.fromMessage(msg), equalTo(content)); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java index 147987430b39..b903ff368686 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,15 @@ package org.springframework.jms.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -import java.util.Arrays; +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -31,9 +37,9 @@ import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.ArgumentsMatcher; -import org.easymock.MockControl; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; @@ -48,127 +54,79 @@ public final class SimpleMessageConverterTests { @Test 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(); + Session session = mock(Session.class); + TextMessage message = mock(TextMessage.class); String content = "test"; - session.createTextMessage(content); - sessionControl.setReturnValue(message, 1); - message.getText(); - messageControl.setReturnValue(content, 1); - sessionControl.replay(); - messageControl.replay(); + given(session.createTextMessage(content)).willReturn(message); + given(message.getText()).willReturn(content); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - - sessionControl.verify(); - messageControl.verify(); } @Test 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(); + Session session = mock(Session.class); + BytesMessage message = mock(BytesMessage.class); byte[] content = "test".getBytes(); + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); - 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() { - @Override - public boolean matches(Object[] arg0, Object[] arg1) { - byte[] one = (byte[]) arg0[0]; - byte[] two = (byte[]) arg1[0]; - return Arrays.equals(one, two); - } - + given(session.createBytesMessage()).willReturn(message); + given(message.getBodyLength()).willReturn((long) content.length); + given(message.readBytes(any(byte[].class))).willAnswer(new Answer() { @Override - public String toString(Object[] arg0) { - return "bla"; + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteArrayInputStream.read((byte[]) invocation.getArguments()[0]); } }); - 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(); + verify(message).writeBytes(content); } @Test 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(); + Session session = mock(Session.class); + MapMessage message = mock(MapMessage.class); 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(); + given(session.createMapMessage()).willReturn(message); + given(message.getMapNames()).willReturn(Collections.enumeration(content.keySet())); + given(message.getObject("key1")).willReturn("value1"); + given(message.getObject("key2")).willReturn("value2"); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - sessionControl.verify(); - messageControl.verify(); + verify(message).setObject("key1", "value1"); + verify(message).setObject("key2", "value2"); } @Test 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(); + Session session = mock(Session.class); + ObjectMessage message = mock(ObjectMessage.class); Integer content = new Integer(5); - session.createObjectMessage(content); - sessionControl.setReturnValue(message, 1); - message.getObject(); - messageControl.setReturnValue(content, 1); - sessionControl.replay(); - messageControl.replay(); + given(session.createObjectMessage(content)).willReturn(message); + given(message.getObject()).willReturn(content); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - - sessionControl.verify(); - messageControl.verify(); } @Test(expected=MessageConversionException.class) @@ -184,50 +142,30 @@ public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() thr @Test 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(); + Session session = mock(Session.class); + ObjectMessage message = mock(ObjectMessage.class); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(message, session); assertSame(message, msg); - - sessionControl.verify(); - messageControl.verify(); } @Test public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException { - MockControl messageControl = MockControl.createControl(Message.class); - Message message = (Message) messageControl.getMock(); - - messageControl.replay(); + Message message = mock(Message.class); SimpleMessageConverter converter = new SimpleMessageConverter(); Object msg = converter.fromMessage(message); assertSame(message, msg); - - messageControl.verify(); } @Test 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(); + MapMessage message = mock(MapMessage.class); + final Session session = mock(Session.class); + given(session.createMapMessage()).willReturn(message); final Map content = new HashMap(); content.put(new Integer(1), "value1"); @@ -237,22 +175,14 @@ public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSExcept converter.toMessage(content, session); fail("expected MessageConversionException"); } catch (MessageConversionException ex) { /* expected */ } - - sessionControl.verify(); } @Test 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(); + MapMessage message = mock(MapMessage.class); + final Session session = mock(Session.class); + given(session.createMapMessage()).willReturn(message); final Map content = new HashMap(); content.put(null, "value1"); @@ -262,8 +192,6 @@ public void testMapConversionWhereMapHasNNullForKey() throws JMSException { converter.toMessage(content, session); fail("expected MessageConversionException"); } catch (MessageConversionException ex) { /* expected */ } - - sessionControl.verify(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java index 025ba22fc790..d2054d5bf2ce 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,27 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.Capture; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; /** * @author Arjen Poutsma @@ -44,7 +50,7 @@ public class MappingJackson2MessageConverterTests { @Before public void setUp() throws Exception { - sessionMock = createMock(Session.class); + sessionMock = mock(Session.class); converter = new MappingJackson2MessageConverter(); converter.setEncodingPropertyName("__encoding__"); converter.setTypeIdPropertyName("__typeid__"); @@ -52,128 +58,94 @@ public void setUp() throws Exception { @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Date toBeMarshalled = new Date(); - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - bytesMessageMock.setStringProperty("__encoding__", "UTF-8"); - bytesMessageMock.setStringProperty("__typeid__", Date.class.getName()); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, bytesMessageMock); + verify(bytesMessageMock).setStringProperty("__encoding__", "UTF-8"); + verify(bytesMessageMock).setStringProperty("__typeid__", Date.class.getName()); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); - - final byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); - @SuppressWarnings("serial") - Capture captured = new Capture() { - @Override - public void setValue(byte[] value) { - super.setValue(value); - System.arraycopy(bytes, 0, value, 0, bytes.length); - } - }; - - expect( - bytesMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect( - bytesMessageMock.propertyExists("__encoding__")) - .andReturn(false); - expect(bytesMessageMock.getBodyLength()).andReturn( - new Long(bytes.length)); - expect(bytesMessageMock.readBytes(EasyMock.capture(captured))) - .andReturn(bytes.length); - - replay(sessionMock, bytesMessageMock); + BytesMessage bytesMessageMock = mock(BytesMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); + + byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); + final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); + + given(bytesMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); + given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length)); + given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( + new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteStream.read((byte[]) invocation.getArguments()[0]); + } + }); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, bytesMessageMock); } @Test public void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Date toBeMarshalled = new Date(); - textMessageMock.setStringProperty("__typeid__", Date.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( textMessageMock); - - replay(sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn( + textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", Date.class.getName()); } @Test public void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Map toBeMarshalled = new HashMap(); toBeMarshalled.put("foo", "bar"); - textMessageMock.setStringProperty("__typeid__", HashMap.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( + given(sessionMock.createTextMessage(isA(String.class))).willReturn( textMessageMock); - replay(sessionMock, textMessageMock); - converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", HashMap.class.getName()); } @Test public void fromTextMessageAsObject() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } @Test public void fromTextMessageAsMap() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(HashMap.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + HashMap.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java index 54ca352ea0d4..0bce702aaad8 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,26 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.Capture; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; /** * @author Arjen Poutsma @@ -43,7 +49,7 @@ public class MappingJacksonMessageConverterTests { @Before public void setUp() throws Exception { - sessionMock = createMock(Session.class); + sessionMock = mock(Session.class); converter = new MappingJacksonMessageConverter(); converter.setEncodingPropertyName("__encoding__"); converter.setTypeIdPropertyName("__typeid__"); @@ -51,128 +57,96 @@ public void setUp() throws Exception { @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object toBeMarshalled = new Object(); - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - bytesMessageMock.setStringProperty("__encoding__", "UTF-8"); - bytesMessageMock.setStringProperty("__typeid__", Object.class.getName()); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, bytesMessageMock); + verify(bytesMessageMock).setStringProperty("__encoding__", "UTF-8"); + verify(bytesMessageMock).setStringProperty("__typeid__", Object.class.getName()); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test @SuppressWarnings("serial") public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); - - final byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); - Capture captured = new Capture() { - @Override - public void setValue(byte[] value) { - super.setValue(value); - System.arraycopy(bytes, 0, value, 0, bytes.length); - } - }; - - expect( - bytesMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect( - bytesMessageMock.propertyExists("__encoding__")) - .andReturn(false); - expect(bytesMessageMock.getBodyLength()).andReturn( - new Long(bytes.length)); - expect(bytesMessageMock.readBytes(EasyMock.capture(captured))) - .andReturn(bytes.length); - - replay(sessionMock, bytesMessageMock); + BytesMessage bytesMessageMock = mock(BytesMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); + + byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); + final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); + + given(bytesMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); + given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length)); + given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( + new Answer() { + + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteStream.read((byte[]) invocation.getArguments()[0]); + } + }); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, bytesMessageMock); } @Test public void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object toBeMarshalled = new Object(); - textMessageMock.setStringProperty("__typeid__", Object.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( textMessageMock); - - replay(sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn( + textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", Object.class.getName()); } @Test public void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Map toBeMarshalled = new HashMap(); toBeMarshalled.put("foo", "bar"); - - textMessageMock.setStringProperty("__typeid__", HashMap.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( + given(sessionMock.createTextMessage(isA(String.class))).willReturn( textMessageMock); - replay(sessionMock, textMessageMock); - converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", HashMap.class.getName()); } @Test public void fromTextMessageAsObject() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } @Test public void fromTextMessageAsMap() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(HashMap.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + HashMap.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java index 861179583d7b..2f6a06199de1 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,21 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; import javax.xml.transform.Result; import javax.xml.transform.Source; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; - import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; @@ -45,76 +49,60 @@ public class MarshallingMessageConverterTests { @Before public void setUp() throws Exception { - marshallerMock = createMock(Marshaller.class); - unmarshallerMock = createMock(Unmarshaller.class); - sessionMock = createMock(Session.class); + marshallerMock = mock(Marshaller.class); + unmarshallerMock = mock(Unmarshaller.class); + sessionMock = mock(Session.class); converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock); } @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object toBeMarshalled = new Object(); - - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class)); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object unmarshalled = new Object(); - expect(bytesMessageMock.getBodyLength()).andReturn(10L); - expect(bytesMessageMock.readBytes(isA(byte[].class))).andReturn(0); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); - - replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + given(bytesMessageMock.getBodyLength()).willReturn(10L); + given(bytesMessageMock.readBytes(isA(byte[].class))).willReturn(0); + given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); } @Test public void toTextMessage() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object toBeMarshalled = new Object(); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn(textMessageMock); - marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class)); - - replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); } @Test public void fromTextMessage() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object unmarshalled = new Object(); String text = "foo"; - expect(textMessageMock.getText()).andReturn(text); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); - - replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + given(textMessageMock.getText()).willReturn(text); + given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java index e968d8cf28b9..504e247ee92d 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ package org.springframework.jms.support.destination; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Queue; @@ -25,7 +28,6 @@ import javax.jms.TopicSession; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.jms.StubQueue; import org.springframework.jms.StubTopic; @@ -39,63 +41,31 @@ public class DynamicDestinationResolverTests extends TestCase { 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(); - + TopicSession session = mock(TopicSession.class); + given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); 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(); - + Session session = mock(Session.class); + given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); 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(); - + Session session = mock(QueueSession.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); 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(); - + Session session = mock(Session.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, false); - - mockSession.verify(); } private static void testResolveDestination(Session session, Destination expectedDestination, boolean isPubSub) throws JMSException { diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java index 133602bcbd86..2afd8e6f9c99 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,9 @@ package org.springframework.jms.support.destination; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; import javax.jms.ConnectionFactory; @@ -31,8 +32,7 @@ public class JmsDestinationAccessorTests { @Test public void testChokesIfDestinationResolverIsetToNullExplcitly() throws Exception { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - replay(connectionFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); try { JmsDestinationAccessor accessor = new StubJmsDestinationAccessor(); @@ -40,9 +40,11 @@ public void testChokesIfDestinationResolverIsetToNullExplcitly() throws Exceptio accessor.setDestinationResolver(null); accessor.afterPropertiesSet(); fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException ex) { /* expected */ } + } + catch (IllegalArgumentException ex) { + // expected + } - verify(connectionFactory); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java index 9cdf36ef45dd..548e0334d19e 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,17 @@ package org.springframework.jms.support.destination; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; import javax.jms.Destination; import javax.jms.Session; import javax.naming.NamingException; -import org.easymock.MockControl; import org.junit.Test; import org.springframework.jms.StubTopic; @@ -40,24 +44,18 @@ public class JndiDestinationResolverTests { @Test public void testHitsCacheSecondTimeThrough() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); JndiDestinationResolver resolver = new OneTimeLookupJndiDestinationResolver(); Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true); assertNotNull(destination); assertSame(DESTINATION, destination); - - mockSession.verify(); } @Test public void testDoesNotUseCacheIfCachingIsTurnedOff() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); CountingCannedJndiDestinationResolver resolver = new CountingCannedJndiDestinationResolver(); @@ -71,21 +69,15 @@ public void testDoesNotUseCacheIfCachingIsTurnedOff() throws Exception { assertNotNull(destination); assertSame(DESTINATION, destination); assertEquals(2, resolver.getCallCount()); - - mockSession.verify(); } @Test public void testDelegatesToFallbackIfNotResolvedInJndi() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); - MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class); - DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock(); - dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, true); - mockDestinationResolver.setReturnValue(DESTINATION); - mockDestinationResolver.replay(); + DestinationResolver dynamicResolver = mock(DestinationResolver.class); + given(dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, + true)).willReturn(DESTINATION); JndiDestinationResolver resolver = new JndiDestinationResolver() { @Override @@ -99,20 +91,12 @@ protected Object lookup(String jndiName, Class requiredClass) throws NamingExcep assertNotNull(destination); assertSame(DESTINATION, destination); - - mockSession.verify(); - mockDestinationResolver.verify(); } @Test 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 Session session = mock(Session.class); + DestinationResolver dynamicResolver = mock(DestinationResolver.class); final JndiDestinationResolver resolver = new JndiDestinationResolver() { @Override @@ -125,10 +109,10 @@ protected Object lookup(String jndiName, Class requiredClass) throws NamingExcep try { resolver.resolveDestinationName(session, DESTINATION_NAME, true); fail("expected DestinationResolutionException"); - } catch (DestinationResolutionException ex) { /* expected */ } - - mockSession.verify(); - mockDestinationResolver.verify(); + } + catch (DestinationResolutionException ex) { + // expected + } }