@Before public void setup() throws JMSException { Mockito.reset(this.mockJmsTemplate); TextMessage message = mock(TextMessage.class); willReturn(new SimpleMessageConverter()) .given(this.mockJmsTemplate).getMessageConverter(); willReturn(message) .given(this.mockJmsTemplate).receiveSelected(isNull()); willAnswer((Answer<String>) invocation -> testMessageHolder.get()) .given(message).getText(); }
given(emf.createEntityManager()).willReturn(targetEm); given(targetEm.createStoredProcedureQuery("x")).willReturn(query); willReturn("y").given(query).getOutputParameterValue(0); willReturn("z").given(query).getOutputParameterValue(2); given(targetEm.isOpen()).willReturn(true);
given(emf.createEntityManager()).willReturn(targetEm); given(targetEm.createStoredProcedureQuery("x")).willReturn(query); willReturn("y").given(query).getOutputParameterValue("a"); willReturn("z").given(query).getOutputParameterValue("c"); given(targetEm.isOpen()).willReturn(true);
@Test public void scheduleAndCancelHeartbeat() throws Exception { ScheduledFuture<?> task = mock(ScheduledFuture.class); willReturn(task).given(this.taskScheduler).schedule(any(Runnable.class), any(Date.class)); this.session.setActive(true); this.session.scheduleHeartbeat(); verify(this.taskScheduler).schedule(any(Runnable.class), any(Date.class)); verifyNoMoreInteractions(this.taskScheduler); given(task.isCancelled()).willReturn(false); given(task.cancel(false)).willReturn(true); this.session.cancelHeartbeat(); verify(task).cancel(false); verifyNoMoreInteractions(task); }
@Test public void getAndPutFail() { UnsupportedOperationException exception = new UnsupportedOperationException("Test exception on get"); willThrow(exception).given(this.cache).get(0L); willThrow(exception).given(this.cache).put(0L, 0L); // Update of the cache will fail as well Object counter = this.simpleService.get(0L); willReturn(new SimpleValueWrapper(2L)).given(this.cache).get(0L); Object counter2 = this.simpleService.get(0L); Object counter3 = this.simpleService.get(0L); assertNotSame(counter, counter2); assertEquals(counter2, counter3); }
@SuppressWarnings("unchecked") @Test // should not fail with NPE (see INT-2666) public void shouldIgnoreNullValuesWhenInitializedWithCollectionContainingNulls() throws Exception { Message<?> m1 = mock(Message.class); willReturn(new MessageHeaders(mock(Map.class))).given(m1).getHeaders(); Message<?> m2 = mock(Message.class); willReturn(new MessageHeaders(mock(Map.class))).given(m2).getHeaders(); final List<Message<?>> messages = new ArrayList<Message<?>>(); messages.add(m1); messages.add(null); messages.add(m2); SimpleMessageGroup grp = new SimpleMessageGroup(messages, 1); assertEquals(2, grp.getMessages().size()); }
@Test public void testOperationWithinChainWithNonNullReturn() { Log logger = spy(TestUtils.getPropertyValue(this.operationWithinChainWithNonNullReturnHandler, "logger", Log.class)); willReturn(true) .given(logger) .isWarnEnabled(); new DirectFieldAccessor(this.operationWithinChainWithNonNullReturnHandler) .setPropertyValue("logger", logger); this.operationWithinChainWithNonNullReturn.send(new GenericMessage<>("test1")); verify(logger).warn("This component doesn't expect a reply. " + "The MBean operation 'testWithReturn' result '[test1]' for " + "'org.springframework.integration.jmx.config:type=TestBean,name=testBeanAdapter' is ignored."); }
@Test public void testOutboundAdapterWithNonNullReturn() { Log logger = spy(TestUtils.getPropertyValue(this.operationWithNonNullReturnHandler, "logger", Log.class)); willReturn(true) .given(logger) .isWarnEnabled(); new DirectFieldAccessor(this.operationWithNonNullReturnHandler) .setPropertyValue("logger", logger); this.operationWithNonNullReturn.send(new GenericMessage<>("test1")); verify(logger).warn("This component doesn't expect a reply. " + "The MBean operation 'testWithReturn' result '[test1]' for " + "'org.springframework.integration.jmx.config:type=TestBean,name=testBeanAdapter' is ignored."); }
@Test public void testConverterBean() throws Exception { @SuppressWarnings("unchecked") Converter<String, Foo> converterDelegate = mock(Converter.class); fooConverter.setDelegate(converterDelegate); Foo foo = new Foo("foo"); willReturn(foo).given(converterDelegate).convert("{'bar':'foo'}"); template.send("annotated32", 0, 1, "{'bar':'foo'}"); assertThat(this.listener.latch20.await(30, TimeUnit.SECONDS)).isTrue(); assertThat(this.listener.listen16foo).isEqualTo(foo); willThrow(new RuntimeException()).given(converterDelegate).convert("foobar"); template.send("annotated32", 0, 1, "foobar"); assertThat(this.config.listen16ErrorLatch.await(30, TimeUnit.SECONDS)).isTrue(); assertThat(this.config.listen16Exception).isNotNull(); assertThat(this.config.listen16Exception).isInstanceOf(ListenerExecutionFailedException.class); assertThat(((ListenerExecutionFailedException) this.config.listen16Exception).getGroupId()) .isEqualTo("converter.explicitGroupId"); assertThat(this.config.listen16Message).isEqualTo("foobar"); }
@SuppressWarnings("unchecked") @Override public Session<String> getSession() { if (this.session != null) { return this.session; } try { Session<String> session = mock(Session.class); willReturn(new String[] { "/foo/foo", "/foo/bar" }).given(session).list("/foo"); ByteArrayInputStream foo = new ByteArrayInputStream("foo\nbar".getBytes()); ByteArrayInputStream bar = new ByteArrayInputStream("baz\nqux".getBytes()); willReturn(foo).given(session).readRaw("/foo/foo"); willReturn(bar).given(session).readRaw("/foo/bar"); willReturn(new String[] { "/bar/foo", "/bar/bar" }).given(session).list("/bar"); ByteArrayInputStream foo2 = new ByteArrayInputStream("foo\r\nbar".getBytes()); ByteArrayInputStream bar2 = new ByteArrayInputStream("baz\r\nqux".getBytes()); willReturn(foo2).given(session).readRaw("/bar/foo"); willReturn(bar2).given(session).readRaw("/bar/bar"); willReturn(new String[] { "/bad/file" }).given(session).list("/bad"); willThrow(new IOException("No file")).given(session).readRaw("/bad/file"); given(session.finalizeRaw()).willReturn(true); this.session = session; return session; } catch (Exception e) { throw new RuntimeException("failed to mock session", e); } }
@Test public void testAdvice() throws Exception { BoundRabbitChannelAdvice advice = this.config.advice(this.config.template()); Log logger = spy(TestUtils.getPropertyValue(advice, "logger", Log.class)); new DirectFieldAccessor(advice).setPropertyValue("logger", logger); willReturn(true).given(logger).isDebugEnabled(); final CountDownLatch latch = new CountDownLatch(1); willAnswer(i -> { latch.countDown(); return i.callRealMethod(); }).given(logger).debug(anyString()); this.gate.send("a,b,c"); assertTrue(this.config.latch.await(10, TimeUnit.SECONDS)); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertThat(this.config.received).containsExactly("A", "B", "C"); }
private void testNackOrRequeue(boolean requeue) throws IOException, TimeoutException { Channel channel = mock(Channel.class); willReturn(true).given(channel).isOpen(); Envelope envelope = new Envelope(123L, false, "ex", "rk"); BasicProperties props = new BasicProperties.Builder().build(); GetResponse getResponse = new GetResponse(envelope, props, "bar".getBytes(), 0); willReturn(getResponse).given(channel).basicGet("foo", false); Connection connection = mock(Connection.class); willReturn(true).given(connection).isOpen(); willReturn(channel).given(connection).createChannel(); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString()); CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory); AmqpMessageSource source = new AmqpMessageSource(ccf, "foo"); Message<?> received = source.receive(); verify(connection).createChannel(); StaticMessageHeaderAccessor.getAcknowledgmentCallback(received) .acknowledge(requeue ? Status.REQUEUE : Status.REJECT); verify(channel).basicReject(123L, requeue); verify(connection).createChannel(); ccf.destroy(); verify(channel).close(); verify(connection).close(30000); }
@Test @SuppressWarnings("unchecked") public void testNotPropagateAddWhenNonExist() { AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { return new GenericMessage<>("world", Collections.singletonMap("bar", "RAB")); } }; handler.addNotPropagatedHeaders("boom"); assertThat(handler.getNotPropagatedHeaders(), containsInAnyOrder("boom")); handler.setOutputChannel(this.channel); ArgumentCaptor<Message<?>> captor = ArgumentCaptor.forClass(Message.class); willReturn(true).given(this.channel).send(captor.capture()); handler.handleMessage(MessageBuilder.withPayload("hello") .setHeader("boom", "FOO") .setHeader("bar", "BAR") .setHeader("baz", "BAZ") .build()); Message<?> out = captor.getValue(); assertThat(out, notNullValue()); assertThat(out.getHeaders().get("boom"), nullValue()); assertThat(out.getHeaders().get("bar"), equalTo("RAB")); assertThat(out.getHeaders().get("baz"), equalTo("BAZ")); }
@Test public void testAck() throws Exception { Channel channel = mock(Channel.class); willReturn(true).given(channel).isOpen(); Envelope envelope = new Envelope(123L, false, "ex", "rk"); BasicProperties props = new BasicProperties.Builder().build(); GetResponse getResponse = new GetResponse(envelope, props, "bar".getBytes(), 0); willReturn(getResponse).given(channel).basicGet("foo", false); Connection connection = mock(Connection.class); willReturn(true).given(connection).isOpen(); willReturn(channel).given(connection).createChannel(); ConnectionFactory connectionFactory = mock(ConnectionFactory.class); willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString());
@Test @SuppressWarnings("unchecked") public void testNotPropagate() { AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { return new GenericMessage<>("world", Collections.singletonMap("bar", "RAB")); } }; assertThat(handler.getNotPropagatedHeaders(), emptyCollectionOf(String.class)); handler.setNotPropagatedHeaders("f*", "*r"); handler.setOutputChannel(this.channel); assertThat(handler.getNotPropagatedHeaders(), containsInAnyOrder("f*", "*r")); ArgumentCaptor<Message<?>> captor = ArgumentCaptor.forClass(Message.class); willReturn(true).given(this.channel).send(captor.capture()); handler.handleMessage(MessageBuilder.withPayload("hello") .setHeader("foo", "FOO") .setHeader("bar", "BAR") .setHeader("baz", "BAZ") .build()); Message<?> out = captor.getValue(); assertThat(out, notNullValue()); assertThat(out.getHeaders().get("foo"), nullValue()); assertThat(out.getHeaders().get("bar"), equalTo("RAB")); assertThat(out.getHeaders().get("baz"), equalTo("BAZ")); }
@Test public void testFallbackType() { final class MyAdapter extends MessagingMessageListenerAdapter<String, String> implements AcknowledgingMessageListener<String, String> { private MyAdapter() { super(null, null); } @Override public void onMessage(ConsumerRecord<String, String> data, Acknowledgment acknowledgment) { toMessagingMessage(data, acknowledgment, null); } } MyAdapter adapter = new MyAdapter(); adapter.setFallbackType(String.class); RecordMessageConverter converter = mock(RecordMessageConverter.class); ConsumerRecord<String, String> cr = new ConsumerRecord<>("foo", 1, 1L, null, null); Acknowledgment ack = mock(Acknowledgment.class); willReturn(new GenericMessage<>("foo")).given(converter).toMessage(cr, ack, null, String.class); adapter.setMessageConverter(converter); adapter.onMessage(cr, ack); verify(converter).toMessage(cr, ack, null, String.class); }
willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class)); willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class)); willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any()); willReturn(token).given(aClient).subscribe(any(String[].class), any(int[].class), any(), any());
@Test @SuppressWarnings("unchecked") public void testNotPropagateAdd() { AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() { @Override protected Object handleRequestMessage(Message<?> requestMessage) { return new GenericMessage<>("world", Collections.singletonMap("bar", "RAB")); } }; assertThat(handler.getNotPropagatedHeaders(), emptyCollectionOf(String.class)); handler.setNotPropagatedHeaders("foo"); handler.addNotPropagatedHeaders("b*r"); handler.setOutputChannel(this.channel); assertThat(handler.getNotPropagatedHeaders(), containsInAnyOrder("foo", "b*r")); ArgumentCaptor<Message<?>> captor = ArgumentCaptor.forClass(Message.class); willReturn(true).given(this.channel).send(captor.capture()); handler.handleMessage( MessageBuilder.withPayload("hello") .setHeader("foo", "FOO") .setHeader("bar", "BAR") .setHeader("baz", "BAZ") .build()); Message<?> out = captor.getValue(); assertThat(out, notNullValue()); assertThat(out.getHeaders().get("foo"), nullValue()); assertThat(out.getHeaders().get("bar"), equalTo("RAB")); assertThat(out.getHeaders().get("baz"), equalTo("BAZ")); }
willReturn(consumer).given(cf).createConsumer("group", "", null); Producer producer = mock(Producer.class);
return token; }).given(client).connect(any(MqttConnectOptions.class)); willReturn(token).given(client).subscribe(any(String[].class), any(int[].class));