diff --git a/build.gradle b/build.gradle index 47161ac8ef..08b133da40 100644 --- a/build.gradle +++ b/build.gradle @@ -92,6 +92,7 @@ subprojects { subproject -> aspectjVersion = '1.9.2' assertjVersion = '3.12.0' assertkVersion = '0.13' + awaitilityVersion = '3.1.6' boonVersion = '0.34' commonsDbcp2Version = '2.5.0' commonsIoVersion = '2.6' @@ -102,7 +103,7 @@ subprojects { subproject -> googleJsr305Version = '3.0.2' groovyVersion = '2.5.6' guavaVersion = '26.0-jre' - hamcrestVersion = '1.3' + hamcrestVersion = '2.1' hazelcastVersion = '3.11.1' hibernateVersion = '5.4.1.Final' hsqldbVersion = '2.4.1' @@ -159,12 +160,18 @@ subprojects { subproject -> // dependencies that are common across all java projects dependencies { if (!(subproject.name ==~ /.*-test.*/)) { - testCompile project(":spring-integration-test-support") + testCompile (project(":spring-integration-test-support")) { + exclude group: 'org.hamcrest' + } } // JSR-305 only used for non-required meta-annotations - compileOnly("com.google.code.findbugs:jsr305:$googleJsr305Version") - testCompile("com.google.code.findbugs:jsr305:$googleJsr305Version") + compileOnly "com.google.code.findbugs:jsr305:$googleJsr305Version" + testCompile "com.google.code.findbugs:jsr305:$googleJsr305Version" + + testCompile ("org.awaitility:awaitility:$awaitilityVersion") { + exclude group: 'org.hamcrest' + } testCompile "org.junit.jupiter:junit-jupiter-api:$junitJupiterVersion" testRuntime "org.junit.jupiter:junit-jupiter-engine:$junitJupiterVersion" @@ -179,7 +186,7 @@ subprojects { subproject -> testRuntime "org.apache.logging.log4j:log4j-slf4j-impl:$log4jVersion" testRuntime "org.apache.logging.log4j:log4j-jcl:$log4jVersion" - testCompile("com.willowtreeapps.assertk:assertk-jvm:$assertkVersion") + testCompile "com.willowtreeapps.assertk:assertk-jvm:$assertkVersion" testCompile "org.jetbrains.kotlin:kotlin-reflect" testCompile "org.jetbrains.kotlin:kotlin-stdlib-jdk8" @@ -330,9 +337,10 @@ subprojects { subproject -> project('spring-integration-test-support') { description = 'Spring Integration Test Support - **No SI Dependencies Allowed**' dependencies { - compile "org.hamcrest:hamcrest-core:$hamcrestVersion" compile "org.hamcrest:hamcrest-library:$hamcrestVersion" - compile "junit:junit:$junit4Version" + compile ("junit:junit:$junit4Version") { + exclude group: 'org.hamcrest' + } compile ("org.junit.jupiter:junit-jupiter-api:$junitJupiterVersion", optional) compileOnly 'org.apiguardian:apiguardian-api:1.0.0' compile "org.mockito:mockito-core:$mockitoVersion" @@ -459,6 +467,7 @@ project('spring-integration-http') { compile ("com.rometools:rome:$romeToolsVersion", optional) testCompile project(":spring-integration-security") + testCompile "org.hamcrest:hamcrest-core:$hamcrestVersion" testCompile ("org.springframework.security:spring-security-config:$springSecurityVersion") { exclude group: 'org.springframework' } @@ -674,7 +683,8 @@ project('spring-integration-webflux') { } compile "org.springframework:spring-webflux:$springVersion" compile ("io.projectreactor.netty:reactor-netty:$reactorNettyVersion" , optional) - + + testCompile "org.hamcrest:hamcrest-core:$hamcrestVersion" testCompile "org.springframework:spring-webmvc:$springVersion" testCompile ("org.springframework.security:spring-security-config:$springSecurityVersion") { exclude group: 'org.springframework' diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/ChannelTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/ChannelTests.java index fc0a47e3e8..ee22e3e5f3 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/ChannelTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/ChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,8 @@ package org.springframework.integration.amqp.channel; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; @@ -34,9 +29,7 @@ import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.ClassRule; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.springframework.amqp.core.AmqpTemplate; @@ -80,9 +73,6 @@ public class ChannelTests { public static final BrokerRunning brokerIsRunning = BrokerRunning.isRunningWithEmptyQueues("pollableWithEP", "withEP", "testConvertFail"); - @Rule - public ExpectedException exception = ExpectedException.none(); - @Autowired private PublishSubscribeAmqpChannel channel; @@ -136,8 +126,8 @@ public class ChannelTests { this.pubSubWithEP.destroy(); this.withEP.destroy(); this.pollableWithEP.destroy(); - assertEquals(0, - TestUtils.getPropertyValue(connectionFactory, "connectionListener.delegates", Collection.class).size()); + assertThat(TestUtils.getPropertyValue(connectionFactory, "connectionListener.delegates", Collection.class) + .size()).isEqualTo(0); } @SuppressWarnings("unchecked") @@ -147,7 +137,8 @@ public class ChannelTests { final Object consumersMonitor = TestUtils.getPropertyValue(channel, "container.consumersMonitor"); int n = 0; while (n++ < 100) { - Set consumers = TestUtils.getPropertyValue(channel, "container.consumers", Set.class); + Set consumers = TestUtils + .getPropertyValue(channel, "container.consumers", Set.class); synchronized (consumersMonitor) { if (!consumers.isEmpty()) { BlockingQueueConsumer newConsumer = consumers.iterator().next(); @@ -158,7 +149,7 @@ public class ChannelTests { } Thread.sleep(100); } - assertTrue("Failed to restart consumer", n < 100); + assertThat(n < 100).as("Failed to restart consumer").isTrue(); } /* @@ -177,21 +168,21 @@ public class ChannelTests { channel.afterPropertiesSet(); channel.onCreate(null); - assertNotNull(admin.getQueueProperties("implicit")); + assertThat(admin.getQueueProperties("implicit")).isNotNull(); admin.deleteQueue("explicit"); channel.setQueueName("explicit"); channel.afterPropertiesSet(); channel.onCreate(null); - assertNotNull(admin.getQueueProperties("explicit")); + assertThat(admin.getQueueProperties("explicit")).isNotNull(); admin.deleteQueue("explicit"); admin.declareQueue(new Queue("explicit", false)); // verify no declaration if exists with non-standard props channel.afterPropertiesSet(); channel.onCreate(null); - assertNotNull(admin.getQueueProperties("explicit")); + assertThat(admin.getQueueProperties("explicit")).isNotNull(); admin.deleteQueue("explicit"); } @@ -203,7 +194,7 @@ public class ChannelTests { channelFactoryBean.setBeanName("testChannel"); channelFactoryBean.afterPropertiesSet(); AbstractAmqpChannel channel = channelFactoryBean.getObject(); - assertThat(channel, instanceOf(PointToPointSubscribableAmqpChannel.class)); + assertThat(channel).isInstanceOf(PointToPointSubscribableAmqpChannel.class); channelFactoryBean = new AmqpChannelFactoryBean(); channelFactoryBean.setBeanFactory(mock(BeanFactory.class)); @@ -212,7 +203,7 @@ public class ChannelTests { channelFactoryBean.setPubSub(true); channelFactoryBean.afterPropertiesSet(); channel = channelFactoryBean.getObject(); - assertThat(channel, instanceOf(PublishSubscribeAmqpChannel.class)); + assertThat(channel).isInstanceOf(PublishSubscribeAmqpChannel.class); RabbitAdmin rabbitAdmin = new RabbitAdmin(this.connectionFactory); rabbitAdmin.deleteQueue("testChannel"); @@ -225,24 +216,24 @@ public class ChannelTests { Message message = MessageBuilder.withPayload(foo).setHeader("baz", "qux").build(); this.pollableWithEP.send(message); Message received = this.pollableWithEP.receive(10000); - assertNotNull(received); - assertThat(received.getPayload(), equalTo(foo)); - assertThat(received.getHeaders().get("baz"), equalTo("qux")); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo(foo); + assertThat(received.getHeaders().get("baz")).isEqualTo("qux"); this.withEP.send(message); received = this.out.receive(10000); - assertNotNull(received); - assertThat(received.getPayload(), equalTo(foo)); - assertThat(received.getHeaders().get("baz"), equalTo("qux")); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo(foo); + assertThat(received.getHeaders().get("baz")).isEqualTo("qux"); this.pubSubWithEP.send(message); received = this.out.receive(10000); - assertNotNull(received); - assertThat(received.getPayload(), equalTo(foo)); - assertThat(received.getHeaders().get("baz"), equalTo("qux")); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo(foo); + assertThat(received.getHeaders().get("baz")).isEqualTo("qux"); - assertSame(this.mapperIn, TestUtils.getPropertyValue(this.pollableWithEP, "inboundHeaderMapper")); - assertSame(this.mapperOut, TestUtils.getPropertyValue(this.pollableWithEP, "outboundHeaderMapper")); + assertThat(TestUtils.getPropertyValue(this.pollableWithEP, "inboundHeaderMapper")).isSameAs(this.mapperIn); + assertThat(TestUtils.getPropertyValue(this.pollableWithEP, "outboundHeaderMapper")).isSameAs(this.mapperOut); } @Test @@ -257,9 +248,9 @@ public class ChannelTests { MessageListener.class); willThrow(new MessageConversionException("foo", new IllegalStateException("bar"))) .given(messageConverter).fromMessage(any(org.springframework.amqp.core.Message.class)); - this.exception.expect(MessageConversionException.class); - this.exception.expectCause(instanceOf(IllegalStateException.class)); - listener.onMessage(mock(org.springframework.amqp.core.Message.class)); + assertThatThrownBy(() -> listener.onMessage(mock(org.springframework.amqp.core.Message.class))) + .isInstanceOf(MessageConversionException.class) + .hasCauseInstanceOf(IllegalStateException.class); } public static class Foo { diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/DispatcherHasNoSubscribersTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/DispatcherHasNoSubscribersTests.java index ec769c067c..dc746c9db7 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/DispatcherHasNoSubscribersTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/channel/DispatcherHasNoSubscribersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.amqp.channel; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -87,8 +84,8 @@ public class DispatcherHasNoSubscribersTests { fail("Exception expected"); } catch (MessageDeliveryException e) { - assertThat(e.getMessage(), - containsString("Dispatcher has no subscribers for amqp-channel 'noSubscribersChannel'.")); + assertThat(e.getMessage()) + .contains("Dispatcher has no subscribers for amqp-channel 'noSubscribersChannel'."); } } @@ -135,19 +132,18 @@ public class DispatcherHasNoSubscribersTests { } private void verifyLogReceived(final List logList) { - assertTrue("Failed to get expected exception", logList.size() > 0); + assertThat(logList.size() > 0).as("Failed to get expected exception").isTrue(); boolean expectedExceptionFound = false; while (logList.size() > 0) { String message = logList.remove(0); - assertNotNull("Failed to get expected exception", message); + assertThat(message).as("Failed to get expected exception").isNotNull(); if (message.startsWith("Dispatcher has no subscribers")) { expectedExceptionFound = true; - assertThat(message, - containsString("Dispatcher has no subscribers for amqp-channel 'noSubscribersChannel'.")); + assertThat(message).contains("Dispatcher has no subscribers for amqp-channel 'noSubscribersChannel'."); break; } } - assertTrue("Failed to get expected exception", expectedExceptionFound); + assertThat(expectedExceptionFound).as("Failed to get expected exception").isTrue(); } } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpChannelParserTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpChannelParserTests.java index 78d7545d87..bf01811b28 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpChannelParserTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,14 +16,7 @@ package org.springframework.integration.amqp.config; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -73,30 +66,33 @@ public class AmqpChannelParserTests { public void interceptor() { MessageChannel channel = context.getBean("channelWithInterceptor", MessageChannel.class); List interceptorList = TestUtils.getPropertyValue(channel, "interceptors.interceptors", List.class); - assertEquals(1, interceptorList.size()); - assertEquals(TestInterceptor.class, interceptorList.get(0).getClass()); - assertEquals(Integer.MAX_VALUE, TestUtils.getPropertyValue( - TestUtils.getPropertyValue(channel, "dispatcher"), "maxSubscribers", Integer.class).intValue()); + assertThat(interceptorList.size()).isEqualTo(1); + assertThat(interceptorList.get(0).getClass()).isEqualTo(TestInterceptor.class); + assertThat(TestUtils.getPropertyValue( + TestUtils.getPropertyValue(channel, "dispatcher"), "maxSubscribers", Integer.class).intValue()) + .isEqualTo(Integer.MAX_VALUE); channel = context.getBean("pubSub", MessageChannel.class); Object mbf = context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME); - assertSame(mbf, TestUtils.getPropertyValue(channel, "container.messageListener.messageBuilderFactory")); - assertTrue(TestUtils.getPropertyValue(channel, "container.missingQueuesFatal", Boolean.class)); - assertFalse(TestUtils.getPropertyValue(channel, "container.transactional", Boolean.class)); - assertFalse(TestUtils.getPropertyValue(channel, "amqpTemplate.transactional", Boolean.class)); - assertThat(TestUtils.getPropertyValue(channel, "container"), instanceOf(SimpleMessageListenerContainer.class)); + assertThat(TestUtils.getPropertyValue(channel, "container.messageListener.messageBuilderFactory")) + .isSameAs(mbf); + assertThat(TestUtils.getPropertyValue(channel, "container.missingQueuesFatal", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(channel, "container.transactional", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(channel, "amqpTemplate.transactional", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(channel, "container")).isInstanceOf(SimpleMessageListenerContainer.class); } @Test public void subscriberLimit() { MessageChannel channel = context.getBean("channelWithSubscriberLimit", MessageChannel.class); - assertEquals(1, TestUtils.getPropertyValue( - TestUtils.getPropertyValue(channel, "dispatcher"), "maxSubscribers", Integer.class).intValue()); - assertFalse(TestUtils.getPropertyValue(channel, "container.missingQueuesFatal", Boolean.class)); - assertFalse(TestUtils.getPropertyValue(channel, "container.transactional", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(channel, "amqpTemplate.transactional", Boolean.class)); - assertFalse(TestUtils.getPropertyValue(channel, "extractPayload", Boolean.class)); - assertThat(TestUtils.getPropertyValue(channel, "container"), instanceOf(DirectMessageListenerContainer.class)); - assertEquals(2, TestUtils.getPropertyValue(channel, "container.consumersPerQueue")); + assertThat(TestUtils.getPropertyValue( + TestUtils.getPropertyValue(channel, "dispatcher"), "maxSubscribers", Integer.class).intValue()) + .isEqualTo(1); + assertThat(TestUtils.getPropertyValue(channel, "container.missingQueuesFatal", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(channel, "container.transactional", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(channel, "amqpTemplate.transactional", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(channel, "extractPayload", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(channel, "container")).isInstanceOf(DirectMessageListenerContainer.class); + assertThat(TestUtils.getPropertyValue(channel, "container.consumersPerQueue")).isEqualTo(2); } @Test @@ -104,19 +100,19 @@ public class AmqpChannelParserTests { checkExtract(this.pollableWithEP); checkExtract(this.withEP); checkExtract(this.pubSubWithEP); - assertEquals(MessageDeliveryMode.NON_PERSISTENT, - TestUtils.getPropertyValue(this.withEP, "defaultDeliveryMode")); - assertFalse(TestUtils.getPropertyValue(this.withEP, "headersMappedLast", Boolean.class)); - assertNull(TestUtils.getPropertyValue(this.pollableWithEP, "defaultDeliveryMode")); - assertTrue(TestUtils.getPropertyValue(this.pollableWithEP, "headersMappedLast", Boolean.class)); + assertThat(TestUtils.getPropertyValue(this.withEP, "defaultDeliveryMode")) + .isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(TestUtils.getPropertyValue(this.withEP, "headersMappedLast", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(this.pollableWithEP, "defaultDeliveryMode")).isNull(); + assertThat(TestUtils.getPropertyValue(this.pollableWithEP, "headersMappedLast", Boolean.class)).isTrue(); } private void checkExtract(AbstractAmqpChannel channel) { - assertThat(TestUtils.getPropertyValue(channel, "outboundHeaderMapper").toString(), - containsString("Mock for AmqpHeaderMapper")); - assertThat(TestUtils.getPropertyValue(channel, "inboundHeaderMapper").toString(), - containsString("Mock for AmqpHeaderMapper")); - assertTrue(TestUtils.getPropertyValue(channel, "extractPayload", Boolean.class)); + assertThat(TestUtils.getPropertyValue(channel, "outboundHeaderMapper").toString()) + .contains("Mock for AmqpHeaderMapper"); + assertThat(TestUtils.getPropertyValue(channel, "inboundHeaderMapper").toString()) + .contains("Mock for AmqpHeaderMapper"); + assertThat(TestUtils.getPropertyValue(channel, "extractPayload", Boolean.class)).isTrue(); } private static class TestInterceptor implements ChannelInterceptor { diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundChannelAdapterParserTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundChannelAdapterParserTests.java index 67a23f8b40..2432c333b5 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundChannelAdapterParserTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.amqp.config; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -66,33 +60,36 @@ public class AmqpInboundChannelAdapterParserTests { public void verifyIdAsChannel() { Object channel = context.getBean("rabbitInbound"); Object adapter = context.getBean("rabbitInbound.adapter"); - assertEquals(DirectChannel.class, channel.getClass()); - assertEquals(AmqpInboundChannelAdapter.class, adapter.getClass()); - assertEquals(Boolean.TRUE, TestUtils.getPropertyValue(adapter, "autoStartup")); - assertEquals(Integer.MAX_VALUE / 2, TestUtils.getPropertyValue(adapter, "phase")); - assertTrue(TestUtils.getPropertyValue(adapter, "messageListenerContainer.missingQueuesFatal", Boolean.class)); - assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer"), - instanceOf(SimpleMessageListenerContainer.class)); + assertThat(channel.getClass()).isEqualTo(DirectChannel.class); + assertThat(adapter.getClass()).isEqualTo(AmqpInboundChannelAdapter.class); + assertThat(TestUtils.getPropertyValue(adapter, "autoStartup")).isEqualTo(Boolean.TRUE); + assertThat(TestUtils.getPropertyValue(adapter, "phase")).isEqualTo(Integer.MAX_VALUE / 2); + assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer.missingQueuesFatal", Boolean.class)) + .isTrue(); + assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer")) + .isInstanceOf(SimpleMessageListenerContainer.class); } @Test public void verifyDMCC() { Object adapter = context.getBean("dmlc.adapter"); - assertEquals(AmqpInboundChannelAdapter.class, adapter.getClass()); - assertFalse(TestUtils.getPropertyValue(adapter, "messageListenerContainer.missingQueuesFatal", Boolean.class)); - assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer"), - instanceOf(DirectMessageListenerContainer.class)); - assertEquals(2, TestUtils.getPropertyValue(adapter, "messageListenerContainer.consumersPerQueue")); + assertThat(adapter.getClass()).isEqualTo(AmqpInboundChannelAdapter.class); + assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer.missingQueuesFatal", Boolean.class)) + .isFalse(); + assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer")) + .isInstanceOf(DirectMessageListenerContainer.class); + assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer.consumersPerQueue")).isEqualTo(2); } @Test public void verifyLifeCycle() { Object adapter = context.getBean("autoStartFalse.adapter"); - assertEquals(Boolean.FALSE, TestUtils.getPropertyValue(adapter, "autoStartup")); - assertEquals(123, TestUtils.getPropertyValue(adapter, "phase")); - assertEquals(AcknowledgeMode.NONE, - TestUtils.getPropertyValue(adapter, "messageListenerContainer.acknowledgeMode")); - assertFalse(TestUtils.getPropertyValue(adapter, "messageListenerContainer.missingQueuesFatal", Boolean.class)); + assertThat(TestUtils.getPropertyValue(adapter, "autoStartup")).isEqualTo(Boolean.FALSE); + assertThat(TestUtils.getPropertyValue(adapter, "phase")).isEqualTo(123); + assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer.acknowledgeMode")) + .isEqualTo(AcknowledgeMode.NONE); + assertThat(TestUtils.getPropertyValue(adapter, "messageListenerContainer.missingQueuesFatal", Boolean.class)) + .isFalse(); } @Test @@ -116,12 +113,12 @@ public class AmqpInboundChannelAdapterParserTests { listener.onMessage(amqpMessage, null); QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class); org.springframework.messaging.Message siMessage = requestChannel.receive(0); - assertEquals("foo", siMessage.getHeaders().get("foo")); - assertNull(siMessage.getHeaders().get("bar")); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID)); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); + assertThat(siMessage.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(siMessage.getHeaders().get("bar")).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)).isNotNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)).isNotNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNotNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNotNull(); } @Test @@ -145,12 +142,12 @@ public class AmqpInboundChannelAdapterParserTests { listener.onMessage(amqpMessage, null); QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class); org.springframework.messaging.Message siMessage = requestChannel.receive(0); - assertEquals("foo", siMessage.getHeaders().get("foo")); - assertNull(siMessage.getHeaders().get("bar")); - assertNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)); - assertNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)); - assertNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID)); - assertNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); + assertThat(siMessage.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(siMessage.getHeaders().get("bar")).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNull(); } @Test @@ -175,12 +172,12 @@ public class AmqpInboundChannelAdapterParserTests { QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class); org.springframework.messaging.Message siMessage = requestChannel.receive(0); - assertNull(siMessage.getHeaders().get("foo")); - assertNull(siMessage.getHeaders().get("bar")); - assertNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)); - assertNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)); - assertNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID)); - assertNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); + assertThat(siMessage.getHeaders().get("foo")).isNull(); + assertThat(siMessage.getHeaders().get("bar")).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNull(); } @Test @@ -204,12 +201,12 @@ public class AmqpInboundChannelAdapterParserTests { listener.onMessage(amqpMessage, null); QueueChannel requestChannel = context.getBean("requestChannel", QueueChannel.class); org.springframework.messaging.Message siMessage = requestChannel.receive(0); - assertNotNull(siMessage.getHeaders().get("bar")); - assertNotNull(siMessage.getHeaders().get("foo")); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.APP_ID)); - assertNotNull(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); + assertThat(siMessage.getHeaders().get("bar")).isNotNull(); + assertThat(siMessage.getHeaders().get("foo")).isNotNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_ENCODING)).isNotNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CLUSTER_ID)).isNotNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNotNull(); + assertThat(siMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNotNull(); } @Test @@ -219,8 +216,8 @@ public class AmqpInboundChannelAdapterParserTests { this.getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + - "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")); + assertThat(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + + "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")).isTrue(); } } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundGatewayParserTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundGatewayParserTests.java index 74c68d91cf..ba84ec7827 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundGatewayParserTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpInboundGatewayParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.amqp.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isNull; import java.lang.reflect.Field; @@ -72,28 +69,31 @@ public class AmqpInboundGatewayParserTests { MessageConverter gatewayConverter = TestUtils.getPropertyValue(gateway, "amqpMessageConverter", MessageConverter.class); MessageConverter templateConverter = TestUtils.getPropertyValue(gateway, "amqpTemplate.messageConverter", MessageConverter.class); TestConverter testConverter = context.getBean("testConverter", TestConverter.class); - assertSame(testConverter, gatewayConverter); - assertSame(testConverter, templateConverter); - assertEquals(Boolean.TRUE, TestUtils.getPropertyValue(gateway, "autoStartup")); - assertEquals(0, TestUtils.getPropertyValue(gateway, "phase")); - assertEquals(Long.valueOf(1234L), TestUtils.getPropertyValue(gateway, "replyTimeout", Long.class)); - assertEquals(Long.valueOf(1234L), TestUtils.getPropertyValue(gateway, "messagingTemplate.receiveTimeout", Long.class)); - assertTrue(TestUtils.getPropertyValue(gateway, "messageListenerContainer.missingQueuesFatal", Boolean.class)); + assertThat(gatewayConverter).isSameAs(testConverter); + assertThat(templateConverter).isSameAs(testConverter); + assertThat(TestUtils.getPropertyValue(gateway, "autoStartup")).isEqualTo(Boolean.TRUE); + assertThat(TestUtils.getPropertyValue(gateway, "phase")).isEqualTo(0); + assertThat(TestUtils.getPropertyValue(gateway, "replyTimeout", Long.class)).isEqualTo(Long.valueOf(1234L)); + assertThat(TestUtils.getPropertyValue(gateway, "messagingTemplate.receiveTimeout", Long.class)) + .isEqualTo(Long.valueOf(1234L)); + assertThat(TestUtils.getPropertyValue(gateway, "messageListenerContainer.missingQueuesFatal", Boolean.class)) + .isTrue(); } @Test public void verifyLifeCycle() { Object gateway = context.getBean("autoStartFalseGateway"); - assertEquals(Boolean.FALSE, TestUtils.getPropertyValue(gateway, "autoStartup")); - assertEquals(123, TestUtils.getPropertyValue(gateway, "phase")); - assertFalse(TestUtils.getPropertyValue(gateway, "messageListenerContainer.missingQueuesFatal", Boolean.class)); + assertThat(TestUtils.getPropertyValue(gateway, "autoStartup")).isEqualTo(Boolean.FALSE); + assertThat(TestUtils.getPropertyValue(gateway, "phase")).isEqualTo(123); + assertThat(TestUtils.getPropertyValue(gateway, "messageListenerContainer.missingQueuesFatal", Boolean.class)) + .isFalse(); Object amqpTemplate = context.getBean("amqpTemplate"); - assertSame(amqpTemplate, TestUtils.getPropertyValue(gateway, "amqpTemplate")); + assertThat(TestUtils.getPropertyValue(gateway, "amqpTemplate")).isSameAs(amqpTemplate); Address defaultReplyTo = TestUtils.getPropertyValue(gateway, "defaultReplyTo", Address.class); Address expected = new Address("fooExchange/barRoutingKey"); - assertEquals(expected.getExchangeName(), defaultReplyTo.getExchangeName()); - assertEquals(expected.getRoutingKey(), defaultReplyTo.getRoutingKey()); - assertEquals(expected, defaultReplyTo); + assertThat(defaultReplyTo.getExchangeName()).isEqualTo(expected.getExchangeName()); + assertThat(defaultReplyTo.getRoutingKey()).isEqualTo(expected.getRoutingKey()); + assertThat(defaultReplyTo).isEqualTo(expected); } @Test @@ -117,7 +117,7 @@ public class AmqpInboundGatewayParserTests { Object[] args = invocation.getArguments(); Message amqpReplyMessage = (Message) args[2]; MessageProperties properties = amqpReplyMessage.getMessageProperties(); - assertEquals("bar", properties.getHeaders().get("bar")); + assertThat(properties.getHeaders().get("bar")).isEqualTo("bar"); return null; }).when(amqpTemplate).send(Mockito.any(String.class), Mockito.any(String.class), Mockito.any(Message.class), isNull()); @@ -150,8 +150,8 @@ public class AmqpInboundGatewayParserTests { this.getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + - "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")); + assertThat(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + + "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")).isTrue(); } } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundChannelAdapterParserTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundChannelAdapterParserTests.java index 5d49148f69..7e83c6958a 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundChannelAdapterParserTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.amqp.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; @@ -107,14 +102,14 @@ public class AmqpOutboundChannelAdapterParserTests { public void verifyIdAsChannel() { Object channel = context.getBean("rabbitOutbound"); Object adapter = context.getBean("rabbitOutbound.adapter"); - assertEquals(DirectChannel.class, channel.getClass()); - assertEquals(EventDrivenConsumer.class, adapter.getClass()); + assertThat(channel.getClass()).isEqualTo(DirectChannel.class); + assertThat(adapter.getClass()).isEqualTo(EventDrivenConsumer.class); MessageHandler handler = TestUtils.getPropertyValue(adapter, "handler", MessageHandler.class); - assertTrue(handler instanceof NamedComponent); - assertEquals("amqp:outbound-channel-adapter", ((NamedComponent) handler).getComponentType()); + assertThat(handler instanceof NamedComponent).isTrue(); + assertThat(((NamedComponent) handler).getComponentType()).isEqualTo("amqp:outbound-channel-adapter"); handler.handleMessage(new GenericMessage("foo")); - assertEquals(1, adviceCalled); - assertTrue(TestUtils.getPropertyValue(handler, "lazyConnect", Boolean.class)); + assertThat(adviceCalled).isEqualTo(1); + assertThat(TestUtils.getPropertyValue(handler, "lazyConnect", Boolean.class)).isTrue(); } @Test @@ -123,12 +118,12 @@ public class AmqpOutboundChannelAdapterParserTests { AmqpOutboundEndpoint endpoint = TestUtils.getPropertyValue(eventDrivenConsumer, "handler", AmqpOutboundEndpoint.class); - assertNotNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); - assertFalse(TestUtils.getPropertyValue(endpoint, "lazyConnect", Boolean.class)); - assertEquals("42", - TestUtils.getPropertyValue(endpoint, "delayExpression", org.springframework.expression.Expression.class) - .getExpressionString()); - assertFalse(TestUtils.getPropertyValue(endpoint, "headersMappedLast", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")).isNotNull(); + assertThat(TestUtils.getPropertyValue(endpoint, "lazyConnect", Boolean.class)).isFalse(); + assertThat(TestUtils + .getPropertyValue(endpoint, "delayExpression", org.springframework.expression.Expression.class) + .getExpressionString()).isEqualTo("42"); + assertThat(TestUtils.getPropertyValue(endpoint, "headersMappedLast", Boolean.class)).isFalse(); Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); @@ -140,11 +135,12 @@ public class AmqpOutboundChannelAdapterParserTests { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpMessage.getMessageProperties(); - assertEquals("foo", properties.getHeaders().get("foo")); - assertEquals("foobar", properties.getHeaders().get("foobar")); - assertNull(properties.getHeaders().get("bar")); - assertEquals(shouldBePersistent.get() ? MessageDeliveryMode.PERSISTENT - : MessageDeliveryMode.NON_PERSISTENT, properties.getDeliveryMode()); + assertThat(properties.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(properties.getHeaders().get("foobar")).isEqualTo("foobar"); + assertThat(properties.getHeaders().get("bar")).isNull(); + assertThat(properties.getDeliveryMode()).isEqualTo(shouldBePersistent.get() ? + MessageDeliveryMode.PERSISTENT + : MessageDeliveryMode.NON_PERSISTENT); return null; }) .when(amqpTemplate).send(Mockito.any(String.class), Mockito.any(String.class), @@ -178,9 +174,9 @@ public class AmqpOutboundChannelAdapterParserTests { AmqpOutboundEndpoint.class); NullChannel nullChannel = context.getBean(NullChannel.class); MessageChannel ackChannel = context.getBean("ackChannel", MessageChannel.class); - assertSame(ackChannel, TestUtils.getPropertyValue(endpoint, "confirmAckChannel")); - assertSame(nullChannel, TestUtils.getPropertyValue(endpoint, "confirmNackChannel")); - assertSame(context.getBean("ems"), TestUtils.getPropertyValue(endpoint, "errorMessageStrategy")); + assertThat(TestUtils.getPropertyValue(endpoint, "confirmAckChannel")).isSameAs(ackChannel); + assertThat(TestUtils.getPropertyValue(endpoint, "confirmNackChannel")).isSameAs(nullChannel); + assertThat(TestUtils.getPropertyValue(endpoint, "errorMessageStrategy")).isSameAs(context.getBean("ems")); } @SuppressWarnings("rawtypes") @@ -191,7 +187,7 @@ public class AmqpOutboundChannelAdapterParserTests { List chainHandlers = TestUtils.getPropertyValue(eventDrivenConsumer, "handler.handlers", List.class); AmqpOutboundEndpoint endpoint = (AmqpOutboundEndpoint) chainHandlers.get(0); - assertNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); + assertThat(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")).isNull(); Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); @@ -202,8 +198,8 @@ public class AmqpOutboundChannelAdapterParserTests { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpMessage.getMessageProperties(); - assertEquals("hello", new String(amqpMessage.getBody())); - assertEquals(MessageDeliveryMode.PERSISTENT, properties.getDeliveryMode()); + assertThat(new String(amqpMessage.getBody())).isEqualTo("hello"); + assertThat(properties.getDeliveryMode()).isEqualTo(MessageDeliveryMode.PERSISTENT); return null; }) .when(amqpTemplate).send(Mockito.any(String.class), Mockito.any(String.class), @@ -226,9 +222,9 @@ public class AmqpOutboundChannelAdapterParserTests { fail("Expected BeanDefinitionParsingException"); } catch (BeansException e) { - assertTrue(e instanceof BeanDefinitionParsingException); - assertTrue(e.getMessage().contains("The 'channel' attribute isn't allowed for " + - "'amqp:outbound-channel-adapter' when it is used as a nested element")); + assertThat(e instanceof BeanDefinitionParsingException).isTrue(); + assertThat(e.getMessage().contains("The 'channel' attribute isn't allowed for " + + "'amqp:outbound-channel-adapter' when it is used as a nested element")).isTrue(); } } @@ -292,8 +288,8 @@ public class AmqpOutboundChannelAdapterParserTests { this.getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + - "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")); + assertThat(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + + "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")).isTrue(); } } @@ -301,9 +297,9 @@ public class AmqpOutboundChannelAdapterParserTests { public void testInt2971AmqpOutboundChannelAdapterWithCustomHeaderMapper() { AmqpHeaderMapper headerMapper = TestUtils.getPropertyValue(this.amqpMessageHandlerWithCustomHeaderMapper, "headerMapper", AmqpHeaderMapper.class); - assertSame(this.context.getBean("customHeaderMapper"), headerMapper); - assertTrue(TestUtils.getPropertyValue(this.amqpMessageHandlerWithCustomHeaderMapper, - "headersMappedLast", Boolean.class)); + assertThat(headerMapper).isSameAs(this.context.getBean("customHeaderMapper")); + assertThat(TestUtils.getPropertyValue(this.amqpMessageHandlerWithCustomHeaderMapper, + "headersMappedLast", Boolean.class)).isTrue(); } @Test diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundGatewayParserTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundGatewayParserTests.java index f3883ca7c8..2eeda50036 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundGatewayParserTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/AmqpOutboundGatewayParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.amqp.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isNull; import java.lang.reflect.Field; @@ -74,32 +69,32 @@ public class AmqpOutboundGatewayParserTests { @Test public void testGatewayConfig() { Object edc = this.context.getBean("rabbitGateway"); - assertFalse(TestUtils.getPropertyValue(edc, "autoStartup", Boolean.class)); + assertThat(TestUtils.getPropertyValue(edc, "autoStartup", Boolean.class)).isFalse(); AmqpOutboundEndpoint gateway = TestUtils.getPropertyValue(edc, "handler", AmqpOutboundEndpoint.class); - assertEquals("amqp:outbound-gateway", gateway.getComponentType()); - assertTrue(TestUtils.getPropertyValue(gateway, "requiresReply", Boolean.class)); + assertThat(gateway.getComponentType()).isEqualTo("amqp:outbound-gateway"); + assertThat(TestUtils.getPropertyValue(gateway, "requiresReply", Boolean.class)).isTrue(); checkGWProps(this.context, gateway); AsyncAmqpOutboundGateway async = this.context.getBean("asyncGateway.handler", AsyncAmqpOutboundGateway.class); - assertEquals("amqp:outbound-async-gateway", async.getComponentType()); + assertThat(async.getComponentType()).isEqualTo("amqp:outbound-async-gateway"); checkGWProps(this.context, async); - assertSame(this.context.getBean("asyncTemplate"), TestUtils.getPropertyValue(async, "template")); - assertSame(this.context.getBean("ems"), TestUtils.getPropertyValue(gateway, "errorMessageStrategy")); + assertThat(TestUtils.getPropertyValue(async, "template")).isSameAs(this.context.getBean("asyncTemplate")); + assertThat(TestUtils.getPropertyValue(gateway, "errorMessageStrategy")).isSameAs(this.context.getBean("ems")); } protected void checkGWProps(ApplicationContext context, Orderable gateway) { - assertEquals(5, gateway.getOrder()); - assertEquals(context.getBean("fromRabbit"), TestUtils.getPropertyValue(gateway, "outputChannel")); + assertThat(gateway.getOrder()).isEqualTo(5); + assertThat(TestUtils.getPropertyValue(gateway, "outputChannel")).isEqualTo(context.getBean("fromRabbit")); MessageChannel returnChannel = context.getBean("returnChannel", MessageChannel.class); - assertSame(returnChannel, TestUtils.getPropertyValue(gateway, "returnChannel")); + assertThat(TestUtils.getPropertyValue(gateway, "returnChannel")).isSameAs(returnChannel); Long sendTimeout = TestUtils.getPropertyValue(gateway, "messagingTemplate.sendTimeout", Long.class); - assertEquals(Long.valueOf(777), sendTimeout); - assertTrue(TestUtils.getPropertyValue(gateway, "lazyConnect", Boolean.class)); - assertEquals("42", - TestUtils.getPropertyValue(gateway, "delayExpression", org.springframework.expression.Expression.class) - .getExpressionString()); + assertThat(sendTimeout).isEqualTo(Long.valueOf(777)); + assertThat(TestUtils.getPropertyValue(gateway, "lazyConnect", Boolean.class)).isTrue(); + assertThat(TestUtils + .getPropertyValue(gateway, "delayExpression", org.springframework.expression.Expression.class) + .getExpressionString()).isEqualTo("42"); } @Test @@ -108,11 +103,11 @@ public class AmqpOutboundGatewayParserTests { AmqpOutboundEndpoint endpoint = TestUtils.getPropertyValue(eventDrivenConsumer, "handler", AmqpOutboundEndpoint.class); - assertNotNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); - assertFalse(TestUtils.getPropertyValue(endpoint, "lazyConnect", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")).isNotNull(); + assertThat(TestUtils.getPropertyValue(endpoint, "lazyConnect", Boolean.class)).isFalse(); - assertFalse(TestUtils.getPropertyValue(endpoint, "requiresReply", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(endpoint, "headersMappedLast", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "requiresReply", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(endpoint, "headersMappedLast", Boolean.class)).isTrue(); Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); @@ -124,9 +119,10 @@ public class AmqpOutboundGatewayParserTests { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpRequestMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpRequestMessage.getMessageProperties(); - assertEquals("foo", properties.getHeaders().get("foo")); - assertEquals(shouldBePersistent.get() ? MessageDeliveryMode.PERSISTENT - : MessageDeliveryMode.NON_PERSISTENT, properties.getDeliveryMode()); + assertThat(properties.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(properties.getDeliveryMode()).isEqualTo(shouldBePersistent.get() ? + MessageDeliveryMode.PERSISTENT + : MessageDeliveryMode.NON_PERSISTENT); // mock reply AMQP message MessageProperties amqpProperties = new MessageProperties(); amqpProperties.setAppId("test.appId"); @@ -149,13 +145,13 @@ public class AmqpOutboundGatewayParserTests { // verify reply QueueChannel queueChannel = this.context.getBean("fromRabbit", QueueChannel.class); Message replyMessage = queueChannel.receive(0); - assertNotNull(replyMessage); - assertEquals("bar", replyMessage.getHeaders().get("bar")); - assertEquals("foo", replyMessage.getHeaders().get("foo")); // copied from request Message - assertNull(replyMessage.getHeaders().get("foobar")); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.DELIVERY_MODE)); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)); + assertThat(replyMessage).isNotNull(); + assertThat(replyMessage.getHeaders().get("bar")).isEqualTo("bar"); + assertThat(replyMessage.getHeaders().get("foo")).isEqualTo("foo"); // copied from request Message + assertThat(replyMessage.getHeaders().get("foobar")).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNull(); shouldBePersistent.set(true); message = MessageBuilder.withPayload("hello") @@ -164,7 +160,7 @@ public class AmqpOutboundGatewayParserTests { .build(); requestChannel.send(message); replyMessage = queueChannel.receive(0); - assertNotNull(replyMessage); + assertThat(replyMessage).isNotNull(); } @Test @@ -173,8 +169,8 @@ public class AmqpOutboundGatewayParserTests { AmqpOutboundEndpoint endpoint = TestUtils.getPropertyValue(eventDrivenConsumer, "handler", AmqpOutboundEndpoint.class); - assertNull(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")); - assertFalse(TestUtils.getPropertyValue(endpoint, "headersMappedLast", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "defaultDeliveryMode")).isNull(); + assertThat(TestUtils.getPropertyValue(endpoint, "headersMappedLast", Boolean.class)).isFalse(); Field amqpTemplateField = ReflectionUtils.findField(AmqpOutboundEndpoint.class, "amqpTemplate"); amqpTemplateField.setAccessible(true); @@ -185,13 +181,13 @@ public class AmqpOutboundGatewayParserTests { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpRequestMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpRequestMessage.getMessageProperties(); - assertEquals("foo", properties.getHeaders().get("foo")); + assertThat(properties.getHeaders().get("foo")).isEqualTo("foo"); // mock reply AMQP message MessageProperties amqpProperties = new MessageProperties(); amqpProperties.setAppId("test.appId"); amqpProperties.setHeader("foobar", "foobar"); amqpProperties.setHeader("bar", "bar"); - assertEquals(MessageDeliveryMode.PERSISTENT, properties.getDeliveryMode()); + assertThat(properties.getDeliveryMode()).isEqualTo(MessageDeliveryMode.PERSISTENT); amqpProperties.setReceivedDeliveryMode(properties.getDeliveryMode()); return new org.springframework.amqp.core.Message("hello".getBytes(), amqpProperties); }) @@ -210,12 +206,12 @@ public class AmqpOutboundGatewayParserTests { // verify reply QueueChannel queueChannel = this.context.getBean("fromRabbit", QueueChannel.class); Message replyMessage = queueChannel.receive(0); - assertEquals("bar", replyMessage.getHeaders().get("bar")); - assertEquals("foo", replyMessage.getHeaders().get("foo")); // copied from request Message - assertNull(replyMessage.getHeaders().get("foobar")); - assertNotNull(replyMessage.getHeaders().get(AmqpHeaders.RECEIVED_DELIVERY_MODE)); - assertNotNull(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); - assertNotNull(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)); + assertThat(replyMessage.getHeaders().get("bar")).isEqualTo("bar"); + assertThat(replyMessage.getHeaders().get("foo")).isEqualTo("foo"); // copied from request Message + assertThat(replyMessage.getHeaders().get("foobar")).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.RECEIVED_DELIVERY_MODE)).isNotNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNotNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNotNull(); } @Test @@ -234,7 +230,7 @@ public class AmqpOutboundGatewayParserTests { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpRequestMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpRequestMessage.getMessageProperties(); - assertNull(properties.getHeaders().get("foo")); + assertThat(properties.getHeaders().get("foo")).isNull(); // mock reply AMQP message MessageProperties amqpProperties = new MessageProperties(); amqpProperties.setAppId("test.appId"); @@ -257,13 +253,13 @@ public class AmqpOutboundGatewayParserTests { // verify reply QueueChannel queueChannel = context.getBean("fromRabbit", QueueChannel.class); Message replyMessage = queueChannel.receive(0); - assertNull(replyMessage.getHeaders().get("bar")); - assertEquals("foo", replyMessage.getHeaders().get("foo")); // copied from request Message - assertNull(replyMessage.getHeaders().get("foobar")); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.DELIVERY_MODE)); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)); - assertEquals(1, adviceCalled); + assertThat(replyMessage.getHeaders().get("bar")).isNull(); + assertThat(replyMessage.getHeaders().get("foo")).isEqualTo("foo"); // copied from request Message + assertThat(replyMessage.getHeaders().get("foobar")).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNull(); + assertThat(adviceCalled).isEqualTo(1); } @Test //INT-1029 @@ -283,7 +279,7 @@ public class AmqpOutboundGatewayParserTests { Object[] args = invocation.getArguments(); org.springframework.amqp.core.Message amqpRequestMessage = (org.springframework.amqp.core.Message) args[2]; MessageProperties properties = amqpRequestMessage.getMessageProperties(); - assertNull(properties.getHeaders().get("foo")); + assertThat(properties.getHeaders().get("foo")).isNull(); // mock reply AMQP message MessageProperties amqpProperties = new MessageProperties(); amqpProperties.setAppId("test.appId"); @@ -307,13 +303,13 @@ public class AmqpOutboundGatewayParserTests { // verify reply QueueChannel queueChannel = this.context.getBean("fromRabbit", QueueChannel.class); Message replyMessage = queueChannel.receive(0); - assertEquals("hello", new String((byte[]) replyMessage.getPayload())); - assertNull(replyMessage.getHeaders().get("bar")); - assertEquals("foo", replyMessage.getHeaders().get("foo")); // copied from request Message - assertNull(replyMessage.getHeaders().get("foobar")); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.DELIVERY_MODE)); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)); - assertNull(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)); + assertThat(new String((byte[]) replyMessage.getPayload())).isEqualTo("hello"); + assertThat(replyMessage.getHeaders().get("bar")).isNull(); + assertThat(replyMessage.getHeaders().get("foo")).isEqualTo("foo"); // copied from request Message + assertThat(replyMessage.getHeaders().get("foobar")).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.DELIVERY_MODE)).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.CONTENT_TYPE)).isNull(); + assertThat(replyMessage.getHeaders().get(AmqpHeaders.APP_ID)).isNull(); } @@ -324,8 +320,8 @@ public class AmqpOutboundGatewayParserTests { this.getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + - "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")); + assertThat(e.getMessage().startsWith("Configuration problem: The 'header-mapper' attribute " + + "is mutually exclusive with 'mapped-request-headers' or 'mapped-reply-headers'")).isTrue(); } } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayIntegrationTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayIntegrationTests.java index 424bc7e5fd..f0b0ca494a 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayIntegrationTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.amqp.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.ClassRule; import org.junit.Test; @@ -58,8 +57,8 @@ public class OutboundGatewayIntegrationTests { String payload = "foo"; this.toRabbit.send(new GenericMessage(payload)); Message receive = this.fromRabbit.receive(10000); - assertNotNull(receive); - assertEquals(payload.toUpperCase(), receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(payload.toUpperCase()); } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayTests.java index 50e3df2c7b..8f14d645a0 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/config/OutboundGatewayTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.amqp.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -67,16 +65,16 @@ public class OutboundGatewayTests { @Test public void testVanillaConfiguration() throws Exception { - assertTrue(context.getBeanFactory().containsBeanDefinition("vanilla")); + assertThat(context.getBeanFactory().containsBeanDefinition("vanilla")).isTrue(); context.getBean("vanilla"); } @Test public void testExpressionBasedConfiguration() throws Exception { - assertTrue(context.getBeanFactory().containsBeanDefinition("expression")); + assertThat(context.getBeanFactory().containsBeanDefinition("expression")).isTrue(); Object target = context.getBean("expression"); - assertNotNull(ReflectionTestUtils.getField(ReflectionTestUtils.getField(target, "handler"), - "routingKeyGenerator")); + assertThat(ReflectionTestUtils.getField(ReflectionTestUtils.getField(target, "handler"), + "routingKeyGenerator")).isNotNull(); } @Test @@ -103,12 +101,12 @@ public class OutboundGatewayTests { endpoint.setBeanFactory(context); endpoint.afterPropertiesSet(); Message message = new GenericMessage("Hello, world!"); - assertEquals("foobar", TestUtils.getPropertyValue(endpoint, "routingKeyGenerator", MessageProcessor.class) - .processMessage(message)); - assertEquals("barbar", TestUtils.getPropertyValue(endpoint, "exchangeNameGenerator", MessageProcessor.class) - .processMessage(message)); - assertEquals("bazbar", TestUtils.getPropertyValue(endpoint, "correlationDataGenerator", MessageProcessor.class) - .processMessage(message)); + assertThat(TestUtils.getPropertyValue(endpoint, "routingKeyGenerator", MessageProcessor.class) + .processMessage(message)).isEqualTo("foobar"); + assertThat(TestUtils.getPropertyValue(endpoint, "exchangeNameGenerator", MessageProcessor.class) + .processMessage(message)).isEqualTo("barbar"); + assertThat(TestUtils.getPropertyValue(endpoint, "correlationDataGenerator", MessageProcessor.class) + .processMessage(message)).isEqualTo("bazbar"); } } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/dsl/AmqpTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/dsl/AmqpTests.java index ca3dcbfd08..defc09a7ba 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/dsl/AmqpTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/dsl/AmqpTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,7 @@ package org.springframework.integration.amqp.dsl; -import static org.hamcrest.Matchers.instanceOf; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.atomic.AtomicReference; @@ -112,11 +106,11 @@ public class AmqpTests { @Test public void testAmqpInboundGatewayFlow() { - assertNotNull(this.amqpInboundGatewayContainer); - assertSame(this.amqpTemplate, TestUtils.getPropertyValue(this.amqpInboundGateway, "amqpTemplate")); + assertThat(this.amqpInboundGatewayContainer).isNotNull(); + assertThat(TestUtils.getPropertyValue(this.amqpInboundGateway, "amqpTemplate")).isSameAs(this.amqpTemplate); Object result = this.amqpTemplate.convertSendAndReceive(this.amqpQueue.getName(), "world"); - assertEquals("HELLO WORLD", result); + assertThat(result).isEqualTo("HELLO WORLD"); this.amqpInboundGateway.stop(); //INTEXT-209 @@ -125,7 +119,7 @@ public class AmqpTests { this.amqpTemplate.convertAndSend(this.amqpQueue.getName(), "world"); ((RabbitTemplate) this.amqpTemplate).setReceiveTimeout(10000); result = this.amqpTemplate.receiveAndConvert("defaultReplyTo"); - assertEquals("HELLO WORLD", result); + assertThat(result).isEqualTo("HELLO WORLD"); } @Autowired @@ -153,8 +147,8 @@ public class AmqpTests { } while (i < 10); - assertNotNull(receive); - assertEquals("HELLO THROUGH THE AMQP", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("HELLO THROUGH THE AMQP"); ((Lifecycle) this.amqpOutboundInput).stop(); } @@ -165,8 +159,8 @@ public class AmqpTests { this.rabbitConnectionFactory) .autoStartup(false) .templateChannelTransacted(true)); - assertTrue(TestUtils.getPropertyValue(flow, "currentMessageChannel.amqpTemplate.transactional", - Boolean.class)); + assertThat(TestUtils.getPropertyValue(flow, "currentMessageChannel.amqpTemplate.transactional", + Boolean.class)).isTrue(); } @Autowired @@ -181,8 +175,8 @@ public class AmqpTests { .build()); Message receive = replyChannel.receive(10000); - assertNotNull(receive); - assertEquals("HELLO ASYNC GATEWAY", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("HELLO ASYNC GATEWAY"); this.asyncOutboundGateway.stop(); } @@ -197,19 +191,19 @@ public class AmqpTests { @Test public void testInboundMessagingExceptionFlow() { this.amqpTemplate.convertAndSend("si.dsl.exception.test", "foo"); - assertNotNull(this.amqpTemplate.receive("si.dsl.exception.test.dlq", 30_000)); - assertNull(this.lefe.get()); - assertNotNull(this.raw.get()); + assertThat(this.amqpTemplate.receive("si.dsl.exception.test.dlq", 30_000)).isNotNull(); + assertThat(this.lefe.get()).isNull(); + assertThat(this.raw.get()).isNotNull(); this.raw.set(null); } @Test public void testInboundConversionExceptionFlow() { this.amqpTemplate.convertAndSend("si.dsl.conv.exception.test", "foo"); - assertNotNull(this.amqpTemplate.receive("si.dsl.conv.exception.test.dlq", 30_000)); - assertNotNull(this.lefe.get()); - assertThat(this.lefe.get().getCause(), instanceOf(MessageConversionException.class)); - assertNotNull(this.raw.get()); + assertThat(this.amqpTemplate.receive("si.dsl.conv.exception.test.dlq", 30_000)).isNotNull(); + assertThat(this.lefe.get()).isNotNull(); + assertThat(this.lefe.get().getCause()).isInstanceOf(MessageConversionException.class); + assertThat(this.raw.get()).isNotNull(); this.raw.set(null); this.lefe.set(null); } @@ -225,11 +219,11 @@ public class AmqpTests { @Test public void unitTestChannel() { - assertEquals(MessageDeliveryMode.NON_PERSISTENT, - TestUtils.getPropertyValue(this.unitChannel, "defaultDeliveryMode")); - assertSame(this.mapperIn, TestUtils.getPropertyValue(this.unitChannel, "inboundHeaderMapper")); - assertSame(this.mapperOut, TestUtils.getPropertyValue(this.unitChannel, "outboundHeaderMapper")); - assertTrue(TestUtils.getPropertyValue(this.unitChannel, "extractPayload", Boolean.class)); + assertThat(TestUtils.getPropertyValue(this.unitChannel, "defaultDeliveryMode")) + .isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(TestUtils.getPropertyValue(this.unitChannel, "inboundHeaderMapper")).isSameAs(this.mapperIn); + assertThat(TestUtils.getPropertyValue(this.unitChannel, "outboundHeaderMapper")).isSameAs(this.mapperOut); + assertThat(TestUtils.getPropertyValue(this.unitChannel, "extractPayload", Boolean.class)).isTrue(); } @Configuration diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceIntegrationTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceIntegrationTests.java index 662bea4d7c..d497bcd63b 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceIntegrationTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 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,11 +16,7 @@ package org.springframework.integration.amqp.inbound; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -126,16 +122,16 @@ public class AmqpMessageSourceIntegrationTests { template.convertAndSend(DSL_QUEUE, "bar"); template.convertAndSend(INTERCEPT_QUEUE, "baz"); template.convertAndSend(NOAUTOACK_QUEUE, "qux"); - assertTrue(this.config.latch.await(10, TimeUnit.SECONDS)); - assertThat(this.config.received, equalTo("foo")); + assertThat(this.config.latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(this.config.received).isEqualTo("foo"); Message dead = template.receive(DLQ, 10_000); - assertNotNull(dead); - assertThat(this.config.fromDsl, equalTo("bar")); - assertThat(this.config.fromInterceptedSource, equalTo("BAZ")); - assertNull(template.receive(NOAUTOACK_QUEUE)); - assertThat(this.config.requeueLatch.getCount(), equalTo(1L)); + assertThat(dead).isNotNull(); + assertThat(this.config.fromDsl).isEqualTo("bar"); + assertThat(this.config.fromInterceptedSource).isEqualTo("BAZ"); + assertThat(template.receive(NOAUTOACK_QUEUE)).isNull(); + assertThat(this.config.requeueLatch.getCount()).isEqualTo(1L); this.config.callback.acknowledge(Status.REQUEUE); - assertTrue(this.config.requeueLatch.await(10, TimeUnit.SECONDS)); + assertThat(this.config.requeueLatch.await(10, TimeUnit.SECONDS)).isTrue(); } @Configuration diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceTests.java index 4334328326..4cdf9c9db0 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/AmqpMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 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,7 @@ package org.springframework.integration.amqp.inbound; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.BDDMockito.willReturn; @@ -70,9 +68,9 @@ public class AmqpMessageSourceTests { AmqpMessageSource source = new AmqpMessageSource(ccf, "foo"); source.setRawMessageHeader(true); Message received = source.receive(); - assertThat(received.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE), - instanceOf(org.springframework.amqp.core.Message.class)); - assertThat(received.getHeaders().get(AmqpHeaders.CONSUMER_QUEUE), equalTo("foo")); + assertThat(received.getHeaders().get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE)) + .isInstanceOf(org.springframework.amqp.core.Message.class); + assertThat(received.getHeaders().get(AmqpHeaders.CONSUMER_QUEUE)).isEqualTo("foo"); // make sure channel is not cached org.springframework.amqp.rabbit.connection.Connection conn = ccf.createConnection(); Channel notCached = conn.createChannel(false); // should not have been "closed" diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java index 1affb5c2e0..777c0c38b1 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/InboundEndpointTests.java @@ -17,18 +17,6 @@ package org.springframework.integration.amqp.inbound; import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -125,10 +113,10 @@ public class InboundEndpointTests { listener.onMessage(amqpMessage, rabbitChannel); Message result = channel.receive(1000); - assertEquals(payload, result.getPayload()); + assertThat(result.getPayload()).isEqualTo(payload); - assertSame(rabbitChannel, result.getHeaders().get(AmqpHeaders.CHANNEL)); - assertEquals(123L, result.getHeaders().get(AmqpHeaders.DELIVERY_TAG)); + assertThat(result.getHeaders().get(AmqpHeaders.CHANNEL)).isSameAs(rabbitChannel); + assertThat(result.getHeaders().get(AmqpHeaders.DELIVERY_TAG)).isEqualTo(123L); } @Test @@ -161,7 +149,7 @@ public class InboundEndpointTests { Message result = new JsonToObjectTransformer().transform(receive); - assertEquals(payload, result.getPayload()); + assertThat(result.getPayload()).isEqualTo(payload); } @Test @@ -179,8 +167,8 @@ public class InboundEndpointTests { final Channel rabbitChannel = mock(Channel.class); channel.subscribe(new MessageTransformingHandler(message -> { - assertSame(rabbitChannel, message.getHeaders().get(AmqpHeaders.CHANNEL)); - assertEquals(123L, message.getHeaders().get(AmqpHeaders.DELIVERY_TAG)); + assertThat(message.getHeaders().get(AmqpHeaders.CHANNEL)).isSameAs(rabbitChannel); + assertThat(message.getHeaders().get(AmqpHeaders.DELIVERY_TAG)).isEqualTo(123L); return MessageBuilder.fromMessage(message) .setHeader(JsonHeaders.TYPE_ID, "foo") .setHeader(JsonHeaders.CONTENT_TYPE_ID, "bar") @@ -197,13 +185,13 @@ public class InboundEndpointTests { org.springframework.amqp.core.Message message = invocation.getArgument(2); Map headers = message.getMessageProperties().getHeaders(); - assertTrue(headers.containsKey(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))); - assertNotEquals("foo", headers.get(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))); - assertFalse(headers.containsKey(JsonHeaders.CONTENT_TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))); - assertFalse(headers.containsKey(JsonHeaders.KEY_TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))); - assertFalse(headers.containsKey(JsonHeaders.TYPE_ID)); - assertFalse(headers.containsKey(JsonHeaders.KEY_TYPE_ID)); - assertFalse(headers.containsKey(JsonHeaders.CONTENT_TYPE_ID)); + assertThat(headers.containsKey(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))).isTrue(); + assertThat(headers.get(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))).isNotEqualTo("foo"); + assertThat(headers.containsKey(JsonHeaders.CONTENT_TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))).isFalse(); + assertThat(headers.containsKey(JsonHeaders.KEY_TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))).isFalse(); + assertThat(headers.containsKey(JsonHeaders.TYPE_ID)).isFalse(); + assertThat(headers.containsKey(JsonHeaders.KEY_TYPE_ID)).isFalse(); + assertThat(headers.containsKey(JsonHeaders.CONTENT_TYPE_ID)).isFalse(); sendLatch.countDown(); return null; }).when(rabbitTemplate) @@ -227,7 +215,7 @@ public class InboundEndpointTests { ChannelAwareMessageListener listener = (ChannelAwareMessageListener) container.getMessageListener(); listener.onMessage(amqpMessage, rabbitChannel); - assertTrue(sendLatch.await(10, TimeUnit.SECONDS)); + assertThat(sendLatch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test @@ -349,15 +337,15 @@ public class InboundEndpointTests { listener.onMessage(org.springframework.amqp.core.MessageBuilder.withBody("foo".getBytes()) .andProperties(new MessageProperties()).build(), null); Message errorMessage = errors.receive(0); - assertNotNull(errorMessage); - assertThat(errorMessage.getPayload(), instanceOf(MessagingException.class)); + assertThat(errorMessage).isNotNull(); + assertThat(errorMessage.getPayload()).isInstanceOf(MessagingException.class); MessagingException payload = (MessagingException) errorMessage.getPayload(); - assertThat(payload.getMessage(), containsString("Dispatcher has no")); - assertThat(StaticMessageHeaderAccessor.getDeliveryAttempt(payload.getFailedMessage()).get(), equalTo(3)); + assertThat(payload.getMessage()).contains("Dispatcher has no"); + assertThat(StaticMessageHeaderAccessor.getDeliveryAttempt(payload.getFailedMessage()).get()).isEqualTo(3); org.springframework.amqp.core.Message amqpMessage = errorMessage.getHeaders() .get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, org.springframework.amqp.core.Message.class); - assertThat(amqpMessage, notNullValue()); - assertNull(errors.receive(0)); + assertThat(amqpMessage).isNotNull(); + assertThat(errors.receive(0)).isNull(); } @Test @@ -376,15 +364,15 @@ public class InboundEndpointTests { listener.onMessage(org.springframework.amqp.core.MessageBuilder.withBody("foo".getBytes()) .andProperties(new MessageProperties()).build(), null); Message errorMessage = errors.receive(0); - assertNotNull(errorMessage); - assertThat(errorMessage.getPayload(), instanceOf(MessagingException.class)); + assertThat(errorMessage).isNotNull(); + assertThat(errorMessage.getPayload()).isInstanceOf(MessagingException.class); MessagingException payload = (MessagingException) errorMessage.getPayload(); - assertThat(payload.getMessage(), containsString("Dispatcher has no")); - assertThat(StaticMessageHeaderAccessor.getDeliveryAttempt(payload.getFailedMessage()).get(), equalTo(3)); + assertThat(payload.getMessage()).contains("Dispatcher has no"); + assertThat(StaticMessageHeaderAccessor.getDeliveryAttempt(payload.getFailedMessage()).get()).isEqualTo(3); org.springframework.amqp.core.Message amqpMessage = errorMessage.getHeaders() .get(AmqpMessageHeaderErrorMessageStrategy.AMQP_RAW_MESSAGE, org.springframework.amqp.core.Message.class); - assertThat(amqpMessage, notNullValue()); - assertNull(errors.receive(0)); + assertThat(amqpMessage).isNotNull(); + assertThat(errors.receive(0)).isNull(); } public static class Foo { diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/ManualAckTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/ManualAckTests.java index e160b00119..5a1e2767ef 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/ManualAckTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/inbound/ManualAckTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,7 @@ package org.springframework.integration.amqp.inbound; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Rule; @@ -89,16 +87,16 @@ public class ManualAckTests { adapter.start(); this.template.convertAndSend("Hello, world"); Message out = bar.receive(5000); - assertNotNull(out); - assertEquals(1, out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo(1); out = bar.receive(5000); - assertNotNull(out); - assertEquals(2, out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo(2); out = bar.receive(5000); - assertNotNull(out); - assertEquals(3, out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo(3); out = bar.receive(1000); - assertNull(out); + assertThat(out).isNull(); adapter.stop(); } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AmqpOutboundEndpointTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AmqpOutboundEndpointTests.java index 889c2cf2a1..f2fc836ee4 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AmqpOutboundEndpointTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AmqpOutboundEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.amqp.outbound; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Rule; import org.junit.Test; @@ -108,24 +104,24 @@ public class AmqpOutboundEndpointTests { .build(); this.pcRequestChannel.send(message); Message ack = this.ackChannel.receive(10000); - assertNotNull(ack); - assertEquals("foo", ack.getPayload()); - assertEquals(Boolean.TRUE, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); + assertThat(ack).isNotNull(); + assertThat(ack.getPayload()).isEqualTo("foo"); + assertThat(ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)).isEqualTo(Boolean.TRUE); org.springframework.amqp.core.Message received = this.amqpTemplateConfirms.receive(this.queue.getName()); - assertEquals("\"hello\"", new String(received.getBody(), "UTF-8")); - assertEquals("application/json", received.getMessageProperties().getContentType()); - assertEquals("java.lang.String", received.getMessageProperties().getHeaders() - .get(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))); + assertThat(new String(received.getBody(), "UTF-8")).isEqualTo("\"hello\""); + assertThat(received.getMessageProperties().getContentType()).isEqualTo("application/json"); + assertThat(received.getMessageProperties().getHeaders() + .get(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))).isEqualTo("java.lang.String"); // test whole message is correlation message = MessageBuilder.withPayload("hello") .build(); this.pcMessageCorrelationRequestChannel.send(message); ack = ackChannel.receive(10000); - assertNotNull(ack); - assertSame(message.getPayload(), ack.getPayload()); - assertEquals(Boolean.TRUE, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); + assertThat(ack).isNotNull(); + assertThat(ack.getPayload()).isSameAs(message.getPayload()); + assertThat(ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)).isEqualTo(Boolean.TRUE); while (this.amqpTemplateConfirms.receive(this.queue.getName()) != null) { // drain @@ -139,9 +135,9 @@ public class AmqpOutboundEndpointTests { .build(); this.pcRequestChannelForAdapter.send(message); Message ack = this.ackChannel.receive(10000); - assertNotNull(ack); - assertEquals("foo", ack.getPayload()); - assertEquals(Boolean.TRUE, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); + assertThat(ack).isNotNull(); + assertThat(ack.getPayload()).isEqualTo("foo"); + assertThat(ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)).isEqualTo(Boolean.TRUE); } @Test @@ -150,8 +146,8 @@ public class AmqpOutboundEndpointTests { Message message = MessageBuilder.withPayload("hello").build(); this.returnRequestChannel.send(message); Message returned = returnChannel.receive(10000); - assertNotNull(returned); - assertEquals(message.getPayload(), returned.getPayload()); + assertThat(returned).isNotNull(); + assertThat(returned.getPayload()).isEqualTo(message.getPayload()); } @Test @@ -159,11 +155,11 @@ public class AmqpOutboundEndpointTests { Message message = MessageBuilder.withPayload("hello").build(); this.returnRequestChannel.send(message); Message returned = returnChannel.receive(10000); - assertNotNull(returned); - assertThat(returned, instanceOf(ErrorMessage.class)); - assertThat(returned.getPayload(), instanceOf(ReturnedAmqpMessageException.class)); + assertThat(returned).isNotNull(); + assertThat(returned).isInstanceOf(ErrorMessage.class); + assertThat(returned.getPayload()).isInstanceOf(ReturnedAmqpMessageException.class); ReturnedAmqpMessageException payload = (ReturnedAmqpMessageException) returned.getPayload(); - assertEquals(message.getPayload(), payload.getFailedMessage().getPayload()); + assertThat(payload.getFailedMessage().getPayload()).isEqualTo(message.getPayload()); } @Test @@ -178,18 +174,18 @@ public class AmqpOutboundEndpointTests { .build(); this.ctRequestChannel.send(message); org.springframework.amqp.core.Message m = receive(template); - assertNotNull(m); - assertEquals("\"hello\"", new String(m.getBody(), "UTF-8")); - assertEquals("application/json", m.getMessageProperties().getContentType()); - assertEquals("java.lang.String", - m.getMessageProperties().getHeaders().get(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))); + assertThat(m).isNotNull(); + assertThat(new String(m.getBody(), "UTF-8")).isEqualTo("\"hello\""); + assertThat(m.getMessageProperties().getContentType()).isEqualTo("application/json"); + assertThat(m.getMessageProperties().getHeaders().get(JsonHeaders.TYPE_ID.replaceFirst(JsonHeaders.PREFIX, ""))) + .isEqualTo("java.lang.String"); message = MessageBuilder.withPayload("hello") .build(); this.ctRequestChannel.send(message); m = receive(template); - assertNotNull(m); - assertEquals("hello", new String(m.getBody(), "UTF-8")); - assertEquals("text/plain", m.getMessageProperties().getContentType()); + assertThat(m).isNotNull(); + assertThat(new String(m.getBody(), "UTF-8")).isEqualTo("hello"); + assertThat(m.getMessageProperties().getContentType()).isEqualTo("text/plain"); while (template.receive() != null) { // drain } @@ -202,7 +198,7 @@ public class AmqpOutboundEndpointTests { Thread.sleep(100); message = template.receive(); } - assertNotNull(message); + assertThat(message).isNotNull(); return message; } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AsyncAmqpGatewayTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AsyncAmqpGatewayTests.java index eec67ab87e..6b51267a9d 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AsyncAmqpGatewayTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/AsyncAmqpGatewayTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,11 +16,7 @@ package org.springframework.integration.amqp.outbound; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.startsWith; @@ -153,14 +149,14 @@ public class AsyncAmqpGatewayTests { gateway.handleMessage(message); Message ack = ackChannel.receive(10000); - assertNotNull(ack); - assertEquals("foo", ack.getPayload()); - assertEquals(true, ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)); + assertThat(ack).isNotNull(); + assertThat(ack.getPayload()).isEqualTo("foo"); + assertThat(ack.getHeaders().get(AmqpHeaders.PUBLISH_CONFIRM)).isEqualTo(true); waitForAckBeforeReplying.countDown(); Message received = outputChannel.receive(10000); - assertNotNull(received); - assertEquals("FOO", received.getPayload()); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo("FOO"); // timeout tests asyncTemplate.setReceiveTimeout(10); @@ -169,7 +165,7 @@ public class AsyncAmqpGatewayTests { // reply timeout with no requiresReply message = MessageBuilder.withPayload("bar").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); - assertTrue(replyTimeoutLatch.await(10, TimeUnit.SECONDS)); + assertThat(replyTimeoutLatch.await(10, TimeUnit.SECONDS)).isTrue(); // reply timeout with requiresReply gateway.setRequiresReply(true); @@ -177,10 +173,10 @@ public class AsyncAmqpGatewayTests { gateway.handleMessage(message); received = errorChannel.receive(10000); - assertThat(received, instanceOf(ErrorMessage.class)); + assertThat(received).isInstanceOf(ErrorMessage.class); ErrorMessage error = (ErrorMessage) received; - assertThat(error.getPayload(), instanceOf(MessagingException.class)); - assertThat(error.getPayload().getCause(), instanceOf(AmqpReplyTimeoutException.class)); + assertThat(error.getPayload()).isInstanceOf(MessagingException.class); + assertThat(error.getPayload().getCause()).isInstanceOf(AmqpReplyTimeoutException.class); asyncTemplate.setReceiveTimeout(30000); receiver.setMessageListener(messageListener); @@ -194,20 +190,20 @@ public class AsyncAmqpGatewayTests { message = MessageBuilder.withPayload("qux").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); received = errorChannel.receive(10000); - assertThat(received, instanceOf(ErrorMessage.class)); + assertThat(received).isInstanceOf(ErrorMessage.class); error = (ErrorMessage) received; - assertThat(error.getPayload(), instanceOf(MessagingException.class)); - assertEquals("QUX", ((MessagingException) error.getPayload()).getFailedMessage().getPayload()); + assertThat(error.getPayload()).isInstanceOf(MessagingException.class); + assertThat(((MessagingException) error.getPayload()).getFailedMessage().getPayload()).isEqualTo("QUX"); gateway.setRoutingKey(UUID.randomUUID().toString()); message = MessageBuilder.withPayload("fiz").setErrorChannel(errorChannel).build(); gateway.handleMessage(message); Message returned = returnChannel.receive(10000); - assertNotNull(returned); - assertThat(returned, instanceOf(ErrorMessage.class)); - assertThat(returned.getPayload(), instanceOf(ReturnedAmqpMessageException.class)); + assertThat(returned).isNotNull(); + assertThat(returned).isInstanceOf(ErrorMessage.class); + assertThat(returned.getPayload()).isInstanceOf(ReturnedAmqpMessageException.class); ReturnedAmqpMessageException payload = (ReturnedAmqpMessageException) returned.getPayload(); - assertEquals("fiz", payload.getFailedMessage().getPayload()); + assertThat(payload.getFailedMessage().getPayload()).isEqualTo("fiz"); ackChannel.receive(10000); ackChannel.purge(null); @@ -226,12 +222,12 @@ public class AsyncAmqpGatewayTests { gateway.handleMessage(message); ack = ackChannel.receive(10000); - assertNotNull(ack); - assertThat(returned, instanceOf(ErrorMessage.class)); - assertThat(returned.getPayload(), instanceOf(ReturnedAmqpMessageException.class)); + assertThat(ack).isNotNull(); + assertThat(returned).isInstanceOf(ErrorMessage.class); + assertThat(returned.getPayload()).isInstanceOf(ReturnedAmqpMessageException.class); NackedAmqpMessageException nack = (NackedAmqpMessageException) ack.getPayload(); - assertEquals("buz", nack.getFailedMessage().getPayload()); - assertEquals("nacknack", nack.getNackReason()); + assertThat(nack.getFailedMessage().getPayload()).isEqualTo("buz"); + assertThat(nack.getNackReason()).isEqualTo("nacknack"); asyncTemplate.stop(); receiver.stop(); diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java index 9d5158caf8..0f8284498d 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/outbound/OutboundEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.amqp.outbound; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -76,19 +72,19 @@ public class OutboundEndpointTests { endpoint.handleMessage(new GenericMessage<>("foo")); ArgumentCaptor captor = ArgumentCaptor.forClass(Message.class); verify(amqpTemplate).send(eq("foo"), eq("bar"), captor.capture(), isNull()); - assertThat(captor.getValue().getMessageProperties().getDelay(), equalTo(42)); + assertThat(captor.getValue().getMessageProperties().getDelay()).isEqualTo(42); endpoint.setExpectReply(true); endpoint.setOutputChannel(new NullChannel()); endpoint.handleMessage(new GenericMessage<>("foo")); verify(amqpTemplate).sendAndReceive(eq("foo"), eq("bar"), captor.capture(), isNull()); - assertThat(captor.getValue().getMessageProperties().getDelay(), equalTo(42)); + assertThat(captor.getValue().getMessageProperties().getDelay()).isEqualTo(42); endpoint.setDelay(23); endpoint.setRoutingKey("baz"); endpoint.afterPropertiesSet(); endpoint.handleMessage(new GenericMessage<>("foo")); verify(amqpTemplate).sendAndReceive(eq("foo"), eq("baz"), captor.capture(), isNull()); - assertThat(captor.getValue().getMessageProperties().getDelay(), equalTo(23)); + assertThat(captor.getValue().getMessageProperties().getDelay()).isEqualTo(23); } @Test @@ -111,7 +107,7 @@ public class OutboundEndpointTests { ArgumentCaptor captor = ArgumentCaptor.forClass(Message.class); gateway.handleMessage(new GenericMessage<>("foo")); verify(amqpTemplate).sendAndReceive(eq("foo"), eq("bar"), captor.capture()); - assertThat(captor.getValue().getMessageProperties().getDelay(), equalTo(42)); + assertThat(captor.getValue().getMessageProperties().getDelay()).isEqualTo(42); } @Test @@ -130,8 +126,8 @@ public class OutboundEndpointTests { .setHeader(MessageHeaders.CONTENT_TYPE, "bar") .build(); endpoint.handleMessage(message); - assertNotNull(amqpMessage.get()); - assertEquals("bar", amqpMessage.get().getMessageProperties().getContentType()); + assertThat(amqpMessage.get()).isNotNull(); + assertThat(amqpMessage.get().getMessageProperties().getContentType()).isEqualTo("bar"); } @Test @@ -156,9 +152,9 @@ public class OutboundEndpointTests { .setReplyChannel(new QueueChannel()) .build(); endpoint.handleMessage(message); - assertNotNull(amqpMessage.get()); - assertEquals("bar", amqpMessage.get().getMessageProperties().getContentType()); - assertNull(amqpMessage.get().getMessageProperties().getHeaders().get(MessageHeaders.REPLY_CHANNEL)); + assertThat(amqpMessage.get()).isNotNull(); + assertThat(amqpMessage.get().getMessageProperties().getContentType()).isEqualTo("bar"); + assertThat(amqpMessage.get().getMessageProperties().getHeaders().get(MessageHeaders.REPLY_CHANNEL)).isNull(); } /** diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/BoundRabbitChannelAdviceIntegrationTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/BoundRabbitChannelAdviceIntegrationTests.java index 99312ae3df..c322383fa2 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/BoundRabbitChannelAdviceIntegrationTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/BoundRabbitChannelAdviceIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 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,7 +17,6 @@ package org.springframework.integration.amqp.support; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.BDDMockito.willReturn; @@ -75,8 +74,8 @@ public class BoundRabbitChannelAdviceIntegrationTests { 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.latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(this.config.received).containsExactly("A", "B", "C"); } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java index 2656790dc8..100375ebfb 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,9 +17,7 @@ package org.springframework.integration.amqp.support; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.util.Date; @@ -103,27 +101,27 @@ public class DefaultAmqpHeaderMapperTests { fail("Unexpected header in properties.headers: " + headerKey); } } - assertEquals("test.appId", amqpProperties.getAppId()); - assertEquals("test.clusterId", amqpProperties.getClusterId()); - assertEquals("test.contentEncoding", amqpProperties.getContentEncoding()); - assertEquals(99L, amqpProperties.getContentLength()); - assertEquals("test.contentType", amqpProperties.getContentType()); - assertEquals(testCorrelationId, amqpProperties.getCorrelationId()); - assertEquals(Integer.valueOf(1234), amqpProperties.getDelay()); - assertEquals(MessageDeliveryMode.NON_PERSISTENT, amqpProperties.getDeliveryMode()); - assertEquals(1234L, amqpProperties.getDeliveryTag()); - assertEquals("test.expiration", amqpProperties.getExpiration()); - assertEquals(new Integer(42), amqpProperties.getMessageCount()); - assertEquals("test.messageId", amqpProperties.getMessageId()); - assertEquals("test.receivedExchange", amqpProperties.getReceivedExchange()); - assertEquals("test.receivedRoutingKey", amqpProperties.getReceivedRoutingKey()); - assertEquals("test.replyTo", amqpProperties.getReplyTo()); - assertEquals(testTimestamp, amqpProperties.getTimestamp()); - assertEquals("test.type", amqpProperties.getType()); - assertEquals("test.userId", amqpProperties.getUserId()); + assertThat(amqpProperties.getAppId()).isEqualTo("test.appId"); + assertThat(amqpProperties.getClusterId()).isEqualTo("test.clusterId"); + assertThat(amqpProperties.getContentEncoding()).isEqualTo("test.contentEncoding"); + assertThat(amqpProperties.getContentLength()).isEqualTo(99L); + assertThat(amqpProperties.getContentType()).isEqualTo("test.contentType"); + assertThat(amqpProperties.getCorrelationId()).isEqualTo(testCorrelationId); + assertThat(amqpProperties.getDelay()).isEqualTo(Integer.valueOf(1234)); + assertThat(amqpProperties.getDeliveryMode()).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(amqpProperties.getDeliveryTag()).isEqualTo(1234L); + assertThat(amqpProperties.getExpiration()).isEqualTo("test.expiration"); + assertThat(amqpProperties.getMessageCount()).isEqualTo(new Integer(42)); + assertThat(amqpProperties.getMessageId()).isEqualTo("test.messageId"); + assertThat(amqpProperties.getReceivedExchange()).isEqualTo("test.receivedExchange"); + assertThat(amqpProperties.getReceivedRoutingKey()).isEqualTo("test.receivedRoutingKey"); + assertThat(amqpProperties.getReplyTo()).isEqualTo("test.replyTo"); + assertThat(amqpProperties.getTimestamp()).isEqualTo(testTimestamp); + assertThat(amqpProperties.getType()).isEqualTo("test.type"); + assertThat(amqpProperties.getUserId()).isEqualTo("test.userId"); - assertNull(amqpProperties.getHeaders().get(MessageHeaders.ERROR_CHANNEL)); - assertNull(amqpProperties.getHeaders().get(MessageHeaders.REPLY_CHANNEL)); + assertThat(amqpProperties.getHeaders().get(MessageHeaders.ERROR_CHANNEL)).isNull(); + assertThat(amqpProperties.getHeaders().get(MessageHeaders.REPLY_CHANNEL)).isNull(); } @Test @@ -138,14 +136,14 @@ public class DefaultAmqpHeaderMapperTests { MessageProperties amqpProperties = new MessageProperties(); headerMapper.fromHeadersToRequest(integrationHeaders, amqpProperties); - assertEquals("text/html", amqpProperties.getContentType()); + assertThat(amqpProperties.getContentType()).isEqualTo("text/html"); headerMap.put(AmqpHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON); integrationHeaders = new MessageHeaders(headerMap); amqpProperties = new MessageProperties(); headerMapper.fromHeadersToRequest(integrationHeaders, amqpProperties); - assertEquals(MimeTypeUtils.APPLICATION_JSON_VALUE, amqpProperties.getContentType()); + assertThat(amqpProperties.getContentType()).isEqualTo(MimeTypeUtils.APPLICATION_JSON_VALUE); } @Test @@ -160,7 +158,7 @@ public class DefaultAmqpHeaderMapperTests { MessageProperties amqpProperties = new MessageProperties(); headerMapper.fromHeadersToRequest(integrationHeaders, amqpProperties); - assertEquals("text/html", amqpProperties.getContentType()); + assertThat(amqpProperties.getContentType()).isEqualTo("text/html"); } @@ -193,26 +191,26 @@ public class DefaultAmqpHeaderMapperTests { amqpProperties.setHeader(AmqpHeaders.SPRING_REPLY_CORRELATION, "test.correlation"); amqpProperties.setHeader(AmqpHeaders.SPRING_REPLY_TO_STACK, "test.replyTo2"); Map headerMap = headerMapper.toHeadersFromReply(amqpProperties); - assertEquals("test.appId", headerMap.get(AmqpHeaders.APP_ID)); - assertEquals("test.clusterId", headerMap.get(AmqpHeaders.CLUSTER_ID)); - assertEquals("test.contentEncoding", headerMap.get(AmqpHeaders.CONTENT_ENCODING)); - assertEquals(99L, headerMap.get(AmqpHeaders.CONTENT_LENGTH)); - assertEquals("test.contentType", headerMap.get(AmqpHeaders.CONTENT_TYPE)); - assertEquals(testCorrelationId, headerMap.get(AmqpHeaders.CORRELATION_ID)); - assertEquals(MessageDeliveryMode.NON_PERSISTENT, headerMap.get(AmqpHeaders.RECEIVED_DELIVERY_MODE)); - assertEquals(1234L, headerMap.get(AmqpHeaders.DELIVERY_TAG)); - assertEquals("test.expiration", headerMap.get(AmqpHeaders.EXPIRATION)); - assertEquals(42, headerMap.get(AmqpHeaders.MESSAGE_COUNT)); - assertEquals("test.messageId", headerMap.get(AmqpHeaders.MESSAGE_ID)); - assertEquals(4567, headerMap.get(AmqpHeaders.RECEIVED_DELAY)); - assertEquals("test.receivedExchange", headerMap.get(AmqpHeaders.RECEIVED_EXCHANGE)); - assertEquals("test.receivedRoutingKey", headerMap.get(AmqpHeaders.RECEIVED_ROUTING_KEY)); - assertEquals("test.replyTo", headerMap.get(AmqpHeaders.REPLY_TO)); - assertEquals(testTimestamp, headerMap.get(AmqpHeaders.TIMESTAMP)); - assertEquals("test.type", headerMap.get(AmqpHeaders.TYPE)); - assertEquals("test.userId", headerMap.get(AmqpHeaders.RECEIVED_USER_ID)); - assertEquals("test.correlation", headerMap.get(AmqpHeaders.SPRING_REPLY_CORRELATION)); - assertEquals("test.replyTo2", headerMap.get(AmqpHeaders.SPRING_REPLY_TO_STACK)); + assertThat(headerMap.get(AmqpHeaders.APP_ID)).isEqualTo("test.appId"); + assertThat(headerMap.get(AmqpHeaders.CLUSTER_ID)).isEqualTo("test.clusterId"); + assertThat(headerMap.get(AmqpHeaders.CONTENT_ENCODING)).isEqualTo("test.contentEncoding"); + assertThat(headerMap.get(AmqpHeaders.CONTENT_LENGTH)).isEqualTo(99L); + assertThat(headerMap.get(AmqpHeaders.CONTENT_TYPE)).isEqualTo("test.contentType"); + assertThat(headerMap.get(AmqpHeaders.CORRELATION_ID)).isEqualTo(testCorrelationId); + assertThat(headerMap.get(AmqpHeaders.RECEIVED_DELIVERY_MODE)).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(headerMap.get(AmqpHeaders.DELIVERY_TAG)).isEqualTo(1234L); + assertThat(headerMap.get(AmqpHeaders.EXPIRATION)).isEqualTo("test.expiration"); + assertThat(headerMap.get(AmqpHeaders.MESSAGE_COUNT)).isEqualTo(42); + assertThat(headerMap.get(AmqpHeaders.MESSAGE_ID)).isEqualTo("test.messageId"); + assertThat(headerMap.get(AmqpHeaders.RECEIVED_DELAY)).isEqualTo(4567); + assertThat(headerMap.get(AmqpHeaders.RECEIVED_EXCHANGE)).isEqualTo("test.receivedExchange"); + assertThat(headerMap.get(AmqpHeaders.RECEIVED_ROUTING_KEY)).isEqualTo("test.receivedRoutingKey"); + assertThat(headerMap.get(AmqpHeaders.REPLY_TO)).isEqualTo("test.replyTo"); + assertThat(headerMap.get(AmqpHeaders.TIMESTAMP)).isEqualTo(testTimestamp); + assertThat(headerMap.get(AmqpHeaders.TYPE)).isEqualTo("test.type"); + assertThat(headerMap.get(AmqpHeaders.RECEIVED_USER_ID)).isEqualTo("test.userId"); + assertThat(headerMap.get(AmqpHeaders.SPRING_REPLY_CORRELATION)).isEqualTo("test.correlation"); + assertThat(headerMap.get(AmqpHeaders.SPRING_REPLY_TO_STACK)).isEqualTo("test.replyTo2"); } @Test @@ -225,7 +223,7 @@ public class DefaultAmqpHeaderMapperTests { String testCorrelationId = "foo"; amqpProperties.setCorrelationId(testCorrelationId); Map headerMap = headerMapper.toHeadersFromReply(amqpProperties); - assertEquals(testCorrelationId, headerMap.get(AmqpHeaders.CORRELATION_ID)); + assertThat(headerMap.get(AmqpHeaders.CORRELATION_ID)).isEqualTo(testCorrelationId); } @@ -236,8 +234,8 @@ public class DefaultAmqpHeaderMapperTests { amqpProperties.setConsumerTag("consumerTag"); amqpProperties.setConsumerQueue("consumerQueue"); Map headerMap = headerMapper.toHeadersFromRequest(amqpProperties); - assertEquals("consumerTag", headerMap.get(AmqpHeaders.CONSUMER_TAG)); - assertEquals("consumerQueue", headerMap.get(AmqpHeaders.CONSUMER_QUEUE)); + assertThat(headerMap.get(AmqpHeaders.CONSUMER_TAG)).isEqualTo("consumerTag"); + assertThat(headerMap.get(AmqpHeaders.CONSUMER_QUEUE)).isEqualTo("consumerQueue"); } @Test @@ -248,7 +246,7 @@ public class DefaultAmqpHeaderMapperTests { MessageHeaders integrationHeaders = new MessageHeaders(headerMap); MessageProperties amqpProperties = new MessageProperties(); headerMapper.fromHeadersToRequest(integrationHeaders, amqpProperties); - assertNull(amqpProperties.getHeaders().get(MessageHeaders.ID)); + assertThat(amqpProperties.getHeaders().get(MessageHeaders.ID)).isNull(); } @Test @@ -259,7 +257,7 @@ public class DefaultAmqpHeaderMapperTests { MessageHeaders integrationHeaders = new MessageHeaders(headerMap); MessageProperties amqpProperties = new MessageProperties(); headerMapper.fromHeadersToRequest(integrationHeaders, amqpProperties); - assertNull(amqpProperties.getHeaders().get(MessageHeaders.TIMESTAMP)); + assertThat(amqpProperties.getHeaders().get(MessageHeaders.TIMESTAMP)).isNull(); } @Test // INT-2090 @@ -272,9 +270,9 @@ public class DefaultAmqpHeaderMapperTests { headerMap.put("__TypeId__", "java.lang.Integer"); MessageHeaders integrationHeaders = new MessageHeaders(headerMap); headerMapper.fromHeadersToRequest(integrationHeaders, amqpProperties); - assertEquals("java.lang.String", amqpProperties.getHeaders().get("__TypeId__")); + assertThat(amqpProperties.getHeaders().get("__TypeId__")).isEqualTo("java.lang.String"); Object result = converter.fromMessage(new Message("123".getBytes(), amqpProperties)); - assertEquals(String.class, result.getClass()); + assertThat(result.getClass()).isEqualTo(String.class); } @Test @@ -285,31 +283,31 @@ public class DefaultAmqpHeaderMapperTests { amqpProperties.getHeaders().put("foo", "bar"); amqpProperties.getHeaders().put("x-foo", "bar"); Map headers = mapper.toHeadersFromRequest(amqpProperties); - assertNull(headers.get(AmqpHeaders.DELIVERY_MODE)); - assertEquals(MessageDeliveryMode.NON_PERSISTENT, headers.get(AmqpHeaders.RECEIVED_DELIVERY_MODE)); - assertEquals("bar", headers.get("foo")); - assertEquals("bar", headers.get("x-foo")); + assertThat(headers.get(AmqpHeaders.DELIVERY_MODE)).isNull(); + assertThat(headers.get(AmqpHeaders.RECEIVED_DELIVERY_MODE)).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(headers.get("foo")).isEqualTo("bar"); + assertThat(headers.get("x-foo")).isEqualTo("bar"); amqpProperties = new MessageProperties(); headers.put(AmqpHeaders.DELIVERY_MODE, MessageDeliveryMode.NON_PERSISTENT); mapper.fromHeadersToReply(new MessageHeaders(headers), amqpProperties); - assertEquals(MessageDeliveryMode.NON_PERSISTENT, amqpProperties.getDeliveryMode()); - assertEquals("bar", amqpProperties.getHeaders().get("foo")); - assertNull(amqpProperties.getHeaders().get("x-foo")); + assertThat(amqpProperties.getDeliveryMode()).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(amqpProperties.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(amqpProperties.getHeaders().get("x-foo")).isNull(); mapper = DefaultAmqpHeaderMapper.outboundMapper(); mapper.fromHeadersToRequest(new MessageHeaders(headers), amqpProperties); - assertEquals(MessageDeliveryMode.NON_PERSISTENT, amqpProperties.getDeliveryMode()); - assertEquals("bar", amqpProperties.getHeaders().get("foo")); - assertNull(amqpProperties.getHeaders().get("x-foo")); + assertThat(amqpProperties.getDeliveryMode()).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(amqpProperties.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(amqpProperties.getHeaders().get("x-foo")).isNull(); amqpProperties.setReceivedDeliveryMode(MessageDeliveryMode.NON_PERSISTENT); amqpProperties.setHeader("x-death", "foo"); headers = mapper.toHeadersFromReply(amqpProperties); - assertEquals(MessageDeliveryMode.NON_PERSISTENT, headers.get(AmqpHeaders.RECEIVED_DELIVERY_MODE)); - assertNull(headers.get(AmqpHeaders.DELIVERY_MODE)); - assertEquals("bar", headers.get("foo")); - assertEquals("foo", headers.get("x-death")); + assertThat(headers.get(AmqpHeaders.RECEIVED_DELIVERY_MODE)).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); + assertThat(headers.get(AmqpHeaders.DELIVERY_MODE)).isNull(); + assertThat(headers.get("foo")).isEqualTo("bar"); + assertThat(headers.get("x-death")).isEqualTo("foo"); } } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/JsonConverterCompatibilityTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/JsonConverterCompatibilityTests.java index a891ad7dcd..d173a28eaa 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/JsonConverterCompatibilityTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/JsonConverterCompatibilityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 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,7 @@ package org.springframework.integration.amqp.support; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; @@ -77,7 +76,7 @@ public class JsonConverterCompatibilityTests { }); Object received = this.rabbitTemplate.receiveAndConvert(JSON_TESTQ); - assertThat(received, instanceOf(Foo.class)); + assertThat(received).isInstanceOf(Foo.class); } public static class Foo { diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/MappingUtilsTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/MappingUtilsTests.java index 2e9eee39e2..d17d205620 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/MappingUtilsTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/MappingUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,8 @@ package org.springframework.integration.amqp.support; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.Test; @@ -48,23 +47,23 @@ public class MappingUtilsTests { boolean headersMappedLast = false; org.springframework.amqp.core.Message mapped = MappingUtils.mapMessage(requestMessage, converter, headerMapper, defaultDeliveryMode, headersMappedLast); - assertThat(mapped.getMessageProperties().getContentType(), equalTo("text/plain")); + assertThat(mapped.getMessageProperties().getContentType()).isEqualTo("text/plain"); headersMappedLast = true; mapped = MappingUtils.mapMessage(requestMessage, converter, headerMapper, defaultDeliveryMode, headersMappedLast); - assertThat(mapped.getMessageProperties().getContentType(), equalTo("my/ct")); + assertThat(mapped.getMessageProperties().getContentType()).isEqualTo("my/ct"); ContentTypeDelegatingMessageConverter ctdConverter = new ContentTypeDelegatingMessageConverter(); ctdConverter.addDelegate("my/ct", converter); mapped = MappingUtils.mapMessage(requestMessage, ctdConverter, headerMapper, defaultDeliveryMode, headersMappedLast); - assertThat(mapped.getMessageProperties().getContentType(), equalTo("my/ct")); + assertThat(mapped.getMessageProperties().getContentType()).isEqualTo("my/ct"); headersMappedLast = false; mapped = MappingUtils.mapMessage(requestMessage, ctdConverter, headerMapper, defaultDeliveryMode, headersMappedLast); - assertThat(mapped.getMessageProperties().getContentType(), equalTo("text/plain")); + assertThat(mapped.getMessageProperties().getContentType()).isEqualTo("text/plain"); headersMappedLast = true; requestMessage = MessageBuilder.withPayload("foo") @@ -76,8 +75,8 @@ public class MappingUtilsTests { fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), - equalTo("contentType header must be a MimeType or String, found: java.lang.Integer")); + assertThat(e.getMessage()) + .isEqualTo("contentType header must be a MimeType or String, found: java.lang.Integer"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java index 48ccab2acd..8abd8c59f2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -139,15 +135,15 @@ public class AbstractCorrelatingMessageHandlerTests { .build(); handler.handleMessage(message); - assertTrue(waitReapCompleteLatch.await(20, TimeUnit.SECONDS)); + assertThat(waitReapCompleteLatch.await(20, TimeUnit.SECONDS)).isTrue(); // Before INT-2751 we got bar + bar + qux - assertEquals(2, outputMessages.size()); // bar + qux + assertThat(outputMessages.size()).isEqualTo(2); // bar + qux // normal release - assertEquals(2, ((MessageGroup) outputMessages.get(0).getPayload()).size()); // 'bar' + assertThat(((MessageGroup) outputMessages.get(0).getPayload()).size()).isEqualTo(2); // 'bar' // reaper release - assertEquals(1, ((MessageGroup) outputMessages.get(1).getPayload()).size()); // 'qux' + assertThat(((MessageGroup) outputMessages.get(1).getPayload()).size()).isEqualTo(1); // 'qux' - assertNull(discards.receive(0)); + assertThat(discards.receive(0)).isNull(); exec.shutdownNow(); } @@ -171,11 +167,13 @@ public class AbstractCorrelatingMessageHandlerTests { .build(); handler.handleMessage(message); - assertEquals(1, outputMessages.size()); + assertThat(outputMessages.size()).isEqualTo(1); - assertEquals(1, TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()); + assertThat(TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()) + .isEqualTo(1); groupStore.expireMessageGroups(0); - assertEquals(0, TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()); + assertThat(TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()) + .isEqualTo(0); } @Test // INT-2833 @@ -200,11 +198,13 @@ public class AbstractCorrelatingMessageHandlerTests { handler.setMinimumTimeoutForEmptyGroups(10_000); - assertEquals(1, outputMessages.size()); + assertThat(outputMessages.size()).isEqualTo(1); - assertEquals(1, TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()); + assertThat(TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()) + .isEqualTo(1); groupStore.expireMessageGroups(0); - assertEquals(1, TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()); + assertThat(TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()) + .isEqualTo(1); handler.setMinimumTimeoutForEmptyGroups(10); @@ -220,8 +220,9 @@ public class AbstractCorrelatingMessageHandlerTests { } } - assertTrue(n < 200); - assertEquals(0, TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()); + assertThat(n < 200).isTrue(); + assertThat(TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()) + .isEqualTo(0); } @Test @@ -245,9 +246,9 @@ public class AbstractCorrelatingMessageHandlerTests { new DirectFieldAccessor(group).setPropertyValue("lastModified", groupNow.getLastModified()); forceComplete.invoke(handler, group); Message message = outputChannel.receive(0); - assertNotNull(message); + assertThat(message).isNotNull(); Collection payload = (Collection) message.getPayload(); - assertEquals(1, payload.size()); + assertThat(payload.size()).isEqualTo(1); } @Test /* INT-3216 */ @@ -267,10 +268,10 @@ public class AbstractCorrelatingMessageHandlerTests { forceComplete.setAccessible(true); MessageGroup group = (MessageGroup) TestUtils.getPropertyValue(mgs, "groupIdToMessageGroup", Map.class) .get("foo"); - assertTrue(group.isComplete()); + assertThat(group.isComplete()).isTrue(); forceComplete.invoke(handler, group); verify(mgs, never()).getMessageGroup("foo"); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); } /* @@ -294,12 +295,12 @@ public class AbstractCorrelatingMessageHandlerTests { forceComplete.setAccessible(true); MessageGroup groupInStore = (MessageGroup) TestUtils.getPropertyValue(mgs, "groupIdToMessageGroup", Map.class) .get("foo"); - assertTrue(groupInStore.isComplete()); - assertFalse(group.isComplete()); + assertThat(groupInStore.isComplete()).isTrue(); + assertThat(group.isComplete()).isFalse(); new DirectFieldAccessor(group).setPropertyValue("lastModified", groupInStore.getLastModified()); forceComplete.invoke(handler, group); verify(mgs).getMessageGroup("foo"); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); } /* @@ -322,14 +323,14 @@ public class AbstractCorrelatingMessageHandlerTests { forceComplete.setAccessible(true); MessageGroup groupInStore = (MessageGroup) TestUtils.getPropertyValue(mgs, "groupIdToMessageGroup", Map.class) .get("foo"); - assertFalse(groupInStore.isComplete()); - assertFalse(group.isComplete()); + assertThat(groupInStore.isComplete()).isFalse(); + assertThat(group.isComplete()).isFalse(); DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(group); directFieldAccessor.setPropertyValue("lastModified", groupInStore.getLastModified()); directFieldAccessor.setPropertyValue("timestamp", groupInStore.getTimestamp() - 1); forceComplete.invoke(handler, group); verify(mgs).getMessageGroup("foo"); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); } @Test @@ -373,13 +374,13 @@ public class AbstractCorrelatingMessageHandlerTests { /* Previously lock for the groupId hasn't been unlocked from the 'forceComplete', because it wasn't reachable in case of exception from the BasicMessageGroupStore.removeMessageGroup */ - assertTrue(executorService.awaitTermination(10, TimeUnit.SECONDS)); + assertThat(executorService.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); /* Since MessageGroup had been marked as 'complete', but hasn't been removed because of exception, the second message is discarded */ Message receive = discardChannel.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); } @Test @@ -409,9 +410,10 @@ public class AbstractCorrelatingMessageHandlerTests { .build(); handler.handleMessage(message); - assertEquals(1, outputMessages.size()); + assertThat(outputMessages.size()).isEqualTo(1); - assertEquals(1, TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()); + assertThat(TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()) + .isEqualTo(1); Thread.sleep(100); @@ -422,8 +424,9 @@ public class AbstractCorrelatingMessageHandlerTests { Thread.sleep(50); } - assertTrue(n < 200); - assertEquals(0, TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()); + assertThat(n < 200).isTrue(); + assertThat(TestUtils.getPropertyValue(handler, "messageStore.groupIdToMessageGroup", Map.class).size()) + .isEqualTo(0); } @Test @@ -449,8 +452,8 @@ public class AbstractCorrelatingMessageHandlerTests { groupStore.expireMessageGroups(0); - assertEquals(2, handler1DiscardChannel.getQueueSize()); - assertEquals(1, handler2DiscardChannel.getQueueSize()); + assertThat(handler1DiscardChannel.getQueueSize()).isEqualTo(2); + assertThat(handler2DiscardChannel.getQueueSize()).isEqualTo(1); } @Test @@ -473,12 +476,12 @@ public class AbstractCorrelatingMessageHandlerTests { Message receive = outputChannel.receive(10_000); - assertNotNull(receive); + assertThat(receive).isNotNull(); - assertEquals(2, receive.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID)); - assertEquals(2, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)); - assertEquals(2, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertTrue(receive.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID)).isEqualTo(2); + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)).isEqualTo(2); + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(2); + assertThat(receive.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java index 0460340ee7..33f2a12757 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.Arrays; @@ -133,11 +130,11 @@ public class AggregatingMessageGroupProcessorHeaderTests { List> messages = Arrays.asList(message1, message2); MessageGroup group = new SimpleMessageGroup(messages, 1); Object result = processor.processMessageGroup(group); - assertNotNull(result); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result).isNotNull(); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertNull(resultMessage.getHeaders().get("k1")); - assertNull(resultMessage.getHeaders().get("k2")); + assertThat(resultMessage.getHeaders().get("k1")).isNull(); + assertThat(resultMessage.getHeaders().get("k2")).isNull(); headers1 = new HashMap<>(); headers1.put("k1", "foo"); @@ -156,8 +153,8 @@ public class AggregatingMessageGroupProcessorHeaderTests { group = new SimpleMessageGroup(messages, 1); result = processor.processMessageGroup(group); resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertNull(resultMessage.getHeaders().get("k1")); - assertNull(resultMessage.getHeaders().get("k2")); + assertThat(resultMessage.getHeaders().get("k1")).isNull(); + assertThat(resultMessage.getHeaders().get("k2")).isNull(); } @@ -169,11 +166,11 @@ public class AggregatingMessageGroupProcessorHeaderTests { List> messages = Collections.singletonList(message); MessageGroup group = new SimpleMessageGroup(messages, 1); Object result = processor.processMessageGroup(group); - assertNotNull(result); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result).isNotNull(); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertEquals("value1", resultMessage.getHeaders().get("k1")); - assertEquals(2, resultMessage.getHeaders().get("k2")); + assertThat(resultMessage.getHeaders().get("k1")).isEqualTo("value1"); + assertThat(resultMessage.getHeaders().get("k2")).isEqualTo(2); } private void twoMessagesWithoutConflicts(MessageGroupProcessor processor) { @@ -185,11 +182,11 @@ public class AggregatingMessageGroupProcessorHeaderTests { List> messages = Arrays.asList(message1, message2); MessageGroup group = new SimpleMessageGroup(messages, 1); Object result = processor.processMessageGroup(group); - assertNotNull(result); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result).isNotNull(); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertEquals("value1", resultMessage.getHeaders().get("k1")); - assertEquals(2, resultMessage.getHeaders().get("k2")); + assertThat(resultMessage.getHeaders().get("k1")).isEqualTo("value1"); + assertThat(resultMessage.getHeaders().get("k2")).isEqualTo(2); } private void twoMessagesWithConflicts(MessageGroupProcessor processor) { @@ -204,11 +201,11 @@ public class AggregatingMessageGroupProcessorHeaderTests { List> messages = Arrays.asList(message1, message2); MessageGroup group = new SimpleMessageGroup(messages, 1); Object result = processor.processMessageGroup(group); - assertNotNull(result); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result).isNotNull(); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertNull(resultMessage.getHeaders().get("k1")); - assertEquals(123, resultMessage.getHeaders().get("k2")); + assertThat(resultMessage.getHeaders().get("k1")).isNull(); + assertThat(resultMessage.getHeaders().get("k2")).isEqualTo(123); } private void missingValuesDoNotConflict(MessageGroupProcessor processor) { @@ -235,17 +232,17 @@ public class AggregatingMessageGroupProcessorHeaderTests { List> messages = Arrays.asList(message1, message2, message3); MessageGroup group = new SimpleMessageGroup(messages, 1); Object result = processor.processMessageGroup(group); - assertNotNull(result); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result).isNotNull(); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertEquals("value1", resultMessage.getHeaders().get("only1")); - assertEquals("value2", resultMessage.getHeaders().get("only2")); - assertEquals("value3", resultMessage.getHeaders().get("only3")); - assertEquals("foo", resultMessage.getHeaders().get("commonTo1And2")); - assertEquals("bar", resultMessage.getHeaders().get("commonTo2And3")); - assertEquals(123, resultMessage.getHeaders().get("commonToAll")); - assertNull(resultMessage.getHeaders().get("conflictBetween1And2")); - assertNull(resultMessage.getHeaders().get("conflictBetween2And3")); + assertThat(resultMessage.getHeaders().get("only1")).isEqualTo("value1"); + assertThat(resultMessage.getHeaders().get("only2")).isEqualTo("value2"); + assertThat(resultMessage.getHeaders().get("only3")).isEqualTo("value3"); + assertThat(resultMessage.getHeaders().get("commonTo1And2")).isEqualTo("foo"); + assertThat(resultMessage.getHeaders().get("commonTo2And3")).isEqualTo("bar"); + assertThat(resultMessage.getHeaders().get("commonToAll")).isEqualTo(123); + assertThat(resultMessage.getHeaders().get("conflictBetween1And2")).isNull(); + assertThat(resultMessage.getHeaders().get("conflictBetween2And3")).isNull(); } private void multipleValuesConflict(MessageGroupProcessor processor) { @@ -264,11 +261,11 @@ public class AggregatingMessageGroupProcessorHeaderTests { List> messages = Arrays.asList(message1, message2, message3); MessageGroup group = new SimpleMessageGroup(messages, 1); Object result = processor.processMessageGroup(group); - assertNotNull(result); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result).isNotNull(); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertEquals("valueForAll", resultMessage.getHeaders().get("common")); - assertNull(resultMessage.getHeaders().get("conflict")); + assertThat(resultMessage.getHeaders().get("common")).isEqualTo("valueForAll"); + assertThat(resultMessage.getHeaders().get("conflict")).isNull(); } private static Message correlatedMessage(Object correlationId, Integer sequenceSize, diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java index 5014cffa51..18fd2f614a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,15 +16,7 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -132,8 +124,8 @@ public class AggregatorTests { " (10k in " + stopwatch.getLastTaskTimeMillis() + "ms)"); Collection result = resultFuture.get(10, TimeUnit.SECONDS); - assertNotNull(result); - assertEquals(60000, result.size()); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(60000); } @Test @@ -181,9 +173,9 @@ public class AggregatorTests { " (10k in " + stopwatch.getLastTaskTimeMillis() + "ms)"); Collection result = resultFuture.get(10, TimeUnit.SECONDS); - assertNotNull(result); - assertEquals(120000, result.size()); - assertThat(stopwatch.getTotalTimeSeconds(), lessThan(60.0)); // actually < 2.0, was many minutes + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(120000); + assertThat(stopwatch.getTotalTimeSeconds()).isLessThan(60.0); // actually < 2.0, was many minutes } @Test @@ -251,8 +243,8 @@ public class AggregatorTests { " (10k in " + stopwatch.getLastTaskTimeMillis() + "ms)"); Collection result = resultFuture.get(10, TimeUnit.SECONDS); - assertNotNull(result); - assertEquals(60000, result.size()); + assertThat(result).isNotNull(); + assertThat(result.size()).isEqualTo(60000); } @Test @@ -272,8 +264,8 @@ public class AggregatorTests { this.aggregator.handleMessage(message3); Message reply = replyChannel.receive(10000); - assertNotNull(reply); - assertEquals(reply.getPayload(), 105); + assertThat(reply).isNotNull(); + assertThat(105).isEqualTo(reply.getPayload()); } @Test @@ -294,8 +286,8 @@ public class AggregatorTests { this.aggregator.handleMessage(message3); Message reply = replyChannel.receive(10000); - assertNotNull(reply); - assertEquals(reply.getPayload(), 105); + assertThat(reply).isNotNull(); + assertThat(105).isEqualTo(reply.getPayload()); } @Test @@ -311,15 +303,15 @@ public class AggregatorTests { this.aggregator.handleMessage(message); this.store.expireMessageGroups(-10000); Message reply = replyChannel.receive(0); - assertNull("No message should have been sent normally", reply); + assertThat(reply).as("No message should have been sent normally").isNull(); Message discardedMessage = discardChannel.receive(1000); - assertNotNull("A message should have been discarded", discardedMessage); - assertEquals(message, discardedMessage); - assertEquals(1, expiryEvents.size()); - assertSame(this.aggregator, expiryEvents.get(0).getSource()); - assertEquals("ABC", this.expiryEvents.get(0).getGroupId()); - assertEquals(1, this.expiryEvents.get(0).getMessageCount()); - assertTrue(this.expiryEvents.get(0).isDiscarded()); + assertThat(discardedMessage).as("A message should have been discarded").isNotNull(); + assertThat(discardedMessage).isEqualTo(message); + assertThat(expiryEvents.size()).isEqualTo(1); + assertThat(expiryEvents.get(0).getSource()).isSameAs(this.aggregator); + assertThat(this.expiryEvents.get(0).getGroupId()).isEqualTo("ABC"); + assertThat(this.expiryEvents.get(0).getMessageCount()).isEqualTo(1); + assertThat(this.expiryEvents.get(0).isDiscarded()).isTrue(); } @Test @@ -336,15 +328,15 @@ public class AggregatorTests { this.aggregator.handleMessage(message); this.store.expireMessageGroups(-10000); Message reply = replyChannel.receive(0); - assertNull("No message should have been sent normally", reply); + assertThat(reply).as("No message should have been sent normally").isNull(); Message discardedMessage = discardChannel.receive(1000); - assertNotNull("A message should have been discarded", discardedMessage); - assertEquals(message, discardedMessage); - assertEquals(1, expiryEvents.size()); - assertSame(this.aggregator, expiryEvents.get(0).getSource()); - assertEquals("ABC", this.expiryEvents.get(0).getGroupId()); - assertEquals(1, this.expiryEvents.get(0).getMessageCount()); - assertTrue(this.expiryEvents.get(0).isDiscarded()); + assertThat(discardedMessage).as("A message should have been discarded").isNotNull(); + assertThat(discardedMessage).isEqualTo(message); + assertThat(expiryEvents.size()).isEqualTo(1); + assertThat(expiryEvents.get(0).getSource()).isSameAs(this.aggregator); + assertThat(this.expiryEvents.get(0).getGroupId()).isEqualTo("ABC"); + assertThat(this.expiryEvents.get(0).getMessageCount()).isEqualTo(1); + assertThat(this.expiryEvents.get(0).isDiscarded()).isTrue(); } @Test @@ -357,16 +349,16 @@ public class AggregatorTests { this.aggregator.handleMessage(message2); this.store.expireMessageGroups(-10000); Message reply = replyChannel.receive(1000); - assertNotNull("A reply message should have been received", reply); - assertEquals(15, reply.getPayload()); - assertEquals(1, expiryEvents.size()); - assertSame(this.aggregator, expiryEvents.get(0).getSource()); - assertEquals("ABC", this.expiryEvents.get(0).getGroupId()); - assertEquals(2, this.expiryEvents.get(0).getMessageCount()); - assertFalse(this.expiryEvents.get(0).isDiscarded()); + assertThat(reply).as("A reply message should have been received").isNotNull(); + assertThat(reply.getPayload()).isEqualTo(15); + assertThat(expiryEvents.size()).isEqualTo(1); + assertThat(expiryEvents.get(0).getSource()).isSameAs(this.aggregator); + assertThat(this.expiryEvents.get(0).getGroupId()).isEqualTo("ABC"); + assertThat(this.expiryEvents.get(0).getMessageCount()).isEqualTo(2); + assertThat(this.expiryEvents.get(0).isDiscarded()).isFalse(); Message message3 = createMessage(5, "ABC", 3, 3, replyChannel, null); this.aggregator.handleMessage(message3); - assertEquals(1, this.store.getMessageGroup("ABC").size()); + assertThat(this.store.getMessageGroup("ABC").size()).isEqualTo(1); } @Test @@ -391,20 +383,20 @@ public class AggregatorTests { this.aggregator.handleMessage(message2); this.store.expireMessageGroups(-10000); Message reply = replyChannel.receive(1000); - assertNotNull("A reply message should have been received", reply); - assertEquals(15, reply.getPayload()); - assertEquals(1, expiryEvents.size()); - assertSame(this.aggregator, expiryEvents.get(0).getSource()); - assertEquals("ABC", this.expiryEvents.get(0).getGroupId()); - assertEquals(2, this.expiryEvents.get(0).getMessageCount()); - assertFalse(this.expiryEvents.get(0).isDiscarded()); - assertEquals(0, this.store.getMessageGroup("ABC").size()); + assertThat(reply).as("A reply message should have been received").isNotNull(); + assertThat(reply.getPayload()).isEqualTo(15); + assertThat(expiryEvents.size()).isEqualTo(1); + assertThat(expiryEvents.get(0).getSource()).isSameAs(this.aggregator); + assertThat(this.expiryEvents.get(0).getGroupId()).isEqualTo("ABC"); + assertThat(this.expiryEvents.get(0).getMessageCount()).isEqualTo(2); + assertThat(this.expiryEvents.get(0).isDiscarded()).isFalse(); + assertThat(this.store.getMessageGroup("ABC").size()).isEqualTo(0); Message message3 = createMessage(5, "ABC", 3, 3, lockCheckingChannel, null); this.aggregator.handleMessage(message3); - assertEquals(0, this.store.getMessageGroup("ABC").size()); + assertThat(this.store.getMessageGroup("ABC").size()).isEqualTo(0); Message discardedMessage = discardChannel.receive(1000); - assertNotNull("A message should have been discarded", discardedMessage); - assertSame(message3, discardedMessage); + assertThat(discardedMessage).as("A message should have been discarded").isNotNull(); + assertThat(discardedMessage).isSameAs(message3); } @Test @@ -430,20 +422,20 @@ public class AggregatorTests { this.aggregator.handleMessage(message2); this.store.expireMessageGroups(-10000); Message reply = replyChannel.receive(1000); - assertNotNull("A reply message should have been received", reply); - assertEquals(15, reply.getPayload()); - assertEquals(1, expiryEvents.size()); - assertSame(this.aggregator, expiryEvents.get(0).getSource()); - assertEquals("ABC", this.expiryEvents.get(0).getGroupId()); - assertEquals(2, this.expiryEvents.get(0).getMessageCount()); - assertFalse(this.expiryEvents.get(0).isDiscarded()); - assertEquals(0, this.store.getMessageGroup("ABC").size()); + assertThat(reply).as("A reply message should have been received").isNotNull(); + assertThat(reply.getPayload()).isEqualTo(15); + assertThat(expiryEvents.size()).isEqualTo(1); + assertThat(expiryEvents.get(0).getSource()).isSameAs(this.aggregator); + assertThat(this.expiryEvents.get(0).getGroupId()).isEqualTo("ABC"); + assertThat(this.expiryEvents.get(0).getMessageCount()).isEqualTo(2); + assertThat(this.expiryEvents.get(0).isDiscarded()).isFalse(); + assertThat(this.store.getMessageGroup("ABC").size()).isEqualTo(0); Message message3 = createMessage(5, "ABC", 3, 3, lockCheckingChannel, null); this.aggregator.handleMessage(message3); - assertEquals(0, this.store.getMessageGroup("ABC").size()); + assertThat(this.store.getMessageGroup("ABC").size()).isEqualTo(0); Message discardedMessage = discardChannel.receive(1000); - assertNotNull("A message should have been discarded", discardedMessage); - assertSame(message3, discardedMessage); + assertThat(discardedMessage).as("A message should have been discarded").isNotNull(); + assertThat(discardedMessage).isSameAs(message3); } @Test @@ -464,12 +456,12 @@ public class AggregatorTests { aggregator.handleMessage(message2); @SuppressWarnings("unchecked") Message reply1 = (Message) replyChannel1.receive(1000); - assertNotNull(reply1); - assertThat(reply1.getPayload(), is(105)); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo(105); @SuppressWarnings("unchecked") Message reply2 = (Message) replyChannel2.receive(1000); - assertNotNull(reply2); - assertThat(reply2.getPayload(), is(2431)); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo(2431); } @Test @@ -481,14 +473,14 @@ public class AggregatorTests { this.aggregator.setDiscardChannel(discardChannel); this.aggregator.handleMessage(createMessage(1, 1, 1, 1, replyChannel, null)); - assertEquals(1, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(1); this.aggregator.handleMessage(createMessage(3, 2, 1, 1, replyChannel, null)); - assertEquals(3, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(3); this.aggregator.handleMessage(createMessage(4, 3, 1, 1, replyChannel, null)); - assertEquals(4, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(4); // next message with same correllation ID is discarded this.aggregator.handleMessage(createMessage(2, 1, 1, 1, replyChannel, null)); - assertEquals(2, discardChannel.receive(1000).getPayload()); + assertThat(discardChannel.receive(1000).getPayload()).isEqualTo(2); } @Test @@ -500,16 +492,16 @@ public class AggregatorTests { this.aggregator.setDiscardChannel(discardChannel); this.aggregator.handleMessage(createMessage(1, 1, 1, 1, replyChannel, null)); - assertEquals(1, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(1); this.aggregator.handleMessage(createMessage(2, 2, 1, 1, replyChannel, null)); - assertEquals(2, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(2); this.aggregator.handleMessage(createMessage(3, 3, 1, 1, replyChannel, null)); - assertEquals(3, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(3); this.aggregator.handleMessage(createMessage(4, 4, 1, 1, replyChannel, null)); - assertEquals(4, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(4); this.aggregator.handleMessage(createMessage(5, 1, 1, 1, replyChannel, null)); - assertEquals(5, replyChannel.receive(1000).getPayload()); - assertNull(discardChannel.receive(0)); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(5); + assertThat(discardChannel.receive(0)).isNull(); } @Test(expected = MessageHandlingException.class) @@ -532,8 +524,8 @@ public class AggregatorTests { this.aggregator.handleMessage(message4); Message reply = replyChannel.receive(10000); - assertNotNull("A message should be aggregated", reply); - assertThat((reply.getPayload()), is(105)); + assertThat(reply).as("A message should be aggregated").isNotNull(); + assertThat((reply.getPayload())).isEqualTo(105); } @Test @@ -552,8 +544,8 @@ public class AggregatorTests { this.aggregator.handleMessage(message2); Message reply = replyChannel.receive(10000); - assertNotNull("A message should be aggregated", reply); - assertThat((reply.getPayload()), is(105)); + assertThat(reply).as("A message should be aggregated").isNotNull(); + assertThat((reply.getPayload())).isEqualTo(105); } @@ -570,7 +562,7 @@ public class AggregatorTests { private void checkLock(AbstractCorrelatingMessageHandler handler, String group, boolean expectedHeld) { ReentrantLock lock = (ReentrantLock) TestUtils.getPropertyValue(handler, "lockRegistry", LockRegistry.class) .obtain(UUIDConverter.getUUID(group).toString()); - assertEquals(expectedHeld, lock.isHeldByCurrentThread()); + assertThat(lock.isHeldByCurrentThread()).isEqualTo(expectedHeld); } private class MultiplyingProcessor implements MessageGroupProcessor { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java index 6e20fc7436..53fc23900f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 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,15 +16,8 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -39,7 +32,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @@ -121,19 +113,19 @@ public class BarrierMessageHandlerTests { Thread.sleep(100); } Map inProcess = TestUtils.getPropertyValue(handler, "inProcess", Map.class); - assertEquals(1, inProcess.size()); - assertTrue("suspension did not appear in time", n < 100); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertNotNull(dupCorrelation.get()); - assertThat(dupCorrelation.get().getMessage(), startsWith("Correlation key (foo) is already in use by")); + assertThat(inProcess.size()).isEqualTo(1); + assertThat(n < 100).as("suspension did not appear in time").isTrue(); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(dupCorrelation.get()).isNotNull(); + assertThat(dupCorrelation.get().getMessage()).startsWith("Correlation key (foo) is already in use by"); handler.trigger(MessageBuilder.withPayload("bar").setCorrelationId("foo").build()); Message received = outputChannel.receive(10000); - assertNotNull(received); + assertThat(received).isNotNull(); List result = (List) received.getPayload(); - assertEquals("foo", result.get(0)); - assertEquals("bar", result.get(1)); - assertEquals(0, suspensions.size()); - assertEquals(0, inProcess.size()); + assertThat(result.get(0)).isEqualTo("foo"); + assertThat(result.get(1)).isEqualTo("bar"); + assertThat(suspensions.size()).isEqualTo(0); + assertThat(inProcess.size()).isEqualTo(0); exec.shutdownNow(); } @@ -151,14 +143,14 @@ public class BarrierMessageHandlerTests { while (n++ < 100 && suspensions.size() == 0) { Thread.sleep(100); } - assertTrue("suspension did not appear in time", n < 100); + assertThat(n < 100).as("suspension did not appear in time").isTrue(); handler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("foo").build()); Message received = outputChannel.receive(10000); - assertNotNull(received); + assertThat(received).isNotNull(); List result = (ArrayList) received.getPayload(); - assertEquals("foo", result.get(0)); - assertEquals("bar", result.get(1)); - assertEquals(0, suspensions.size()); + assertThat(result.get(0)).isEqualTo("foo"); + assertThat(result.get(1)).isEqualTo("bar"); + assertThat(suspensions.size()).isEqualTo(0); exec.shutdownNow(); } @@ -179,22 +171,21 @@ public class BarrierMessageHandlerTests { latch.countDown(); }); Map suspensions = TestUtils.getPropertyValue(handler, "suspensions", Map.class); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertEquals("suspension not removed", 0, suspensions.size()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(suspensions.size()).as("suspension not removed").isEqualTo(0); Log logger = spy(TestUtils.getPropertyValue(handler, "logger", Log.class)); new DirectFieldAccessor(handler).setPropertyValue("logger", logger); final Message triggerMessage = MessageBuilder.withPayload("bar").setCorrelationId("foo").build(); handler.trigger(triggerMessage); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(logger).error(captor.capture()); - assertThat(captor.getValue(), - allOf(containsString("Suspending thread timed out or did not arrive within timeout for:"), - containsString("payload=bar"))); - assertEquals(0, suspensions.size()); + assertThat(captor.getValue()).contains("Suspending thread timed out or did not arrive within timeout for:") + .contains("payload=bar"); + assertThat(suspensions.size()).isEqualTo(0); Message discard = discardChannel.receive(0); - assertSame(discard, triggerMessage); + assertThat(triggerMessage).isSameAs(discard); handler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("foo").build()); - assertEquals(0, suspensions.size()); + assertThat(suspensions.size()).isEqualTo(0); exec.shutdownNow(); } @@ -211,7 +202,7 @@ public class BarrierMessageHandlerTests { fail("exception expected"); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(ReplyRequiredException.class)); + assertThat(e).isInstanceOf(ReplyRequiredException.class); } } @@ -239,12 +230,12 @@ public class BarrierMessageHandlerTests { while (n++ < 100 && suspensions.size() == 0) { Thread.sleep(100); } - assertTrue("suspension did not appear in time", n < 100); + assertThat(n < 100).as("suspension did not appear in time").isTrue(); Exception exc = new RuntimeException(); handler.trigger(MessageBuilder.withPayload(exc).setCorrelationId("foo").build()); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertSame(exc, exception.get().getCause()); - assertEquals(0, suspensions.size()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(exception.get().getCause()).isSameAs(exc); + assertThat(suspensions.size()).isEqualTo(0); exec.shutdownNow(); } @@ -255,12 +246,12 @@ public class BarrierMessageHandlerTests { Message suspending = MessageBuilder.withPayload("foo").setCorrelationId("foo").build(); this.in.send(suspending); Message out = this.out.receive(10000); - assertNotNull(out); - assertEquals("[foo, bar]", out.getPayload().toString()); + assertThat(out).isNotNull(); + assertThat(out.getPayload().toString()).isEqualTo("[foo, bar]"); Message publisherMessage = this.publisherChannel.receive(10000); - assertNotNull(publisherMessage); - assertEquals("BAR", publisherMessage.getPayload()); + assertThat(publisherMessage).isNotNull(); + assertThat(publisherMessage.getPayload()).isEqualTo("BAR"); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java index ea9b54887a..4b419f6f3f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -80,12 +75,12 @@ public class ConcurrentAggregatorTests { this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message3, latch)); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); - assertThat(latch.getCount(), is(0L)); + assertThat(latch.getCount()).isEqualTo(0L); Message reply = replyChannel.receive(2000); - assertNotNull(reply); - assertEquals(reply.getPayload(), 105); + assertThat(reply).isNotNull(); + assertThat(105).isEqualTo(reply.getPayload()); } @Test @@ -106,8 +101,8 @@ public class ConcurrentAggregatorTests { new AggregatorTestTask(this.aggregator, message2, latch).run(); new AggregatorTestTask(this.aggregator, message3, latch).run(); Message reply = replyChannel.receive(1000); - assertNotNull(reply); - assertEquals("123456789", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("123456789"); } @Test @@ -122,16 +117,16 @@ public class ConcurrentAggregatorTests { message, latch); this.taskExecutor.execute(task); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); - assertEquals("Task should have completed within timeout", 0, latch - .getCount()); + assertThat(latch + .getCount()).as("Task should have completed within timeout").isEqualTo(0); Message reply = replyChannel.receive(10); - assertNull("No message should have been sent normally", reply); + assertThat(reply).as("No message should have been sent normally").isNull(); this.store.expireMessageGroups(-10000); Message discardedMessage = discardChannel.receive(10000); - assertNotNull("A message should have been discarded", discardedMessage); - assertEquals(message, discardedMessage); + assertThat(discardedMessage).as("A message should have been discarded").isNotNull(); + assertThat(discardedMessage).isEqualTo(message); } @Test @@ -148,16 +143,15 @@ public class ConcurrentAggregatorTests { this.taskExecutor.execute(task1); this.taskExecutor.execute(task2); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); - assertEquals("handlers should have been invoked within time limit", 0, - latch.getCount()); + assertThat(latch.getCount()).as("handlers should have been invoked within time limit").isEqualTo(0); this.store.expireMessageGroups(-10000); Message reply = replyChannel.receive(1000); - assertNotNull("A reply message should have been received", reply); - assertEquals(15, reply.getPayload()); - assertNull(task1.getException()); - assertNull(task2.getException()); + assertThat(reply).as("A reply message should have been received").isNotNull(); + assertThat(reply.getPayload()).isEqualTo(15); + assertThat(task1.getException()).isNull(); + assertThat(task2.getException()).isNull(); } @Test @@ -187,16 +181,16 @@ public class ConcurrentAggregatorTests { this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message4, latch)); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); @SuppressWarnings("unchecked") Message reply1 = (Message) replyChannel1.receive(1000); - assertNotNull(reply1); - assertThat(reply1.getPayload(), is(105)); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo(105); @SuppressWarnings("unchecked") Message reply2 = (Message) replyChannel2.receive(1000); - assertNotNull(reply2); - assertThat(reply2.getPayload(), is(2431)); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo(2431); } @Test @@ -210,17 +204,17 @@ public class ConcurrentAggregatorTests { this.aggregator.setDiscardChannel(discardChannel); this.aggregator.handleMessage(createMessage(1, 1, 1, 1, replyChannel, null)); - assertEquals(1, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(1); this.aggregator.handleMessage(createMessage(3, 2, 1, 1, replyChannel, null)); - assertEquals(3, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(3); this.aggregator.handleMessage(createMessage(4, 3, 1, 1, replyChannel, null)); - assertEquals(4, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(4); // next message with same correlation ID is discarded this.aggregator.handleMessage(createMessage(2, 1, 1, 1, replyChannel, null)); - assertEquals(2, discardChannel.receive(1000).getPayload()); + assertThat(discardChannel.receive(1000).getPayload()).isEqualTo(2); } @Test @@ -234,20 +228,20 @@ public class ConcurrentAggregatorTests { this.aggregator.setDiscardChannel(discardChannel); this.aggregator.handleMessage(createMessage(1, 1, 1, 1, replyChannel, null)); - assertEquals(1, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(1); this.aggregator.handleMessage(createMessage(2, 2, 1, 1, replyChannel, null)); - assertEquals(2, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(2); this.aggregator.handleMessage(createMessage(3, 3, 1, 1, replyChannel, null)); - assertEquals(3, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(3); this.aggregator.handleMessage(createMessage(4, 4, 1, 1, replyChannel, null)); - assertEquals(4, replyChannel.receive(1000).getPayload()); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(4); this.aggregator.handleMessage(createMessage(5, 1, 1, 1, replyChannel, null)); - assertEquals(5, replyChannel.receive(1000).getPayload()); - assertNull(discardChannel.receive(0)); + assertThat(replyChannel.receive(1000).getPayload()).isEqualTo(5); + assertThat(discardChannel.receive(0)).isNull(); } @Test(expected = MessageHandlingException.class) @@ -277,11 +271,11 @@ public class ConcurrentAggregatorTests { this.taskExecutor.execute(new AggregatorTestTask(this.aggregator, message4, latch)); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); Message reply = replyChannel.receive(10000); - assertNotNull("A message should be aggregated", reply); - assertThat(reply.getPayload(), is(105)); + assertThat(reply).as("A message should be aggregated").isNotNull(); + assertThat(reply.getPayload()).isEqualTo(105); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java index f28e85df17..8cf146ea67 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -69,7 +66,7 @@ public class CorrelatingMessageBarrierTests { public void shouldPassMessage() { Message message = testMessage(); barrier.handleMessage(message); - assertThat(barrier.receive(), is(message)); + assertThat(barrier.receive()).isEqualTo(message); } @Test @@ -78,10 +75,10 @@ public class CorrelatingMessageBarrierTests { Message message2 = testMessage(); barrier.handleMessage(message); verify(correlationStrategy).getCorrelationKey(message); - assertThat(barrier.receive(), is(notNullValue())); + assertThat(barrier.receive()).isNotNull(); barrier.handleMessage(message2); - assertThat(barrier.receive(), is(notNullValue())); - assertThat(barrier.receive(), is(nullValue())); + assertThat(barrier.receive()).isNotNull(); + assertThat(barrier.receive()).isNull(); } @Test(timeout = 10000) @@ -103,10 +100,10 @@ public class CorrelatingMessageBarrierTests { Thread.currentThread().interrupt(); } - assertThat((barrier.receive()), is(notNullValue())); + assertThat((barrier.receive())).isNotNull(); for (int i = 0; i < 199; i++) { trackingReleaseStrategy.release("foo"); - assertThat((barrier.receive()), is(notNullValue())); + assertThat((barrier.receive())).isNotNull(); } exec.shutdownNow(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java index 168e64143a..acd30d294e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doAnswer; @@ -118,7 +117,7 @@ public class CorrelatingMessageHandlerTests { fail("Expected MessageHandlingException"); } catch (MessageHandlingException e) { - assertEquals(0, store.getMessageGroup(correlationKey).size()); + assertThat(store.getMessageGroup(correlationKey).size()).isEqualTo(0); } verify(correlationStrategy).getCorrelationKey(message1); @@ -154,9 +153,9 @@ public class CorrelatingMessageHandlerTests { bothMessagesHandled.countDown(); }); - assertTrue(bothMessagesHandled.await(10, TimeUnit.SECONDS)); + assertThat(bothMessagesHandled.await(10, TimeUnit.SECONDS)).isTrue(); - assertEquals(0, store.expireMessageGroups(10000)); + assertThat(store.expireMessageGroups(10000)).isEqualTo(0); exec.shutdownNow(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java index 08bd86bc1f..8df4f82260 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java @@ -16,7 +16,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Before; @@ -47,7 +47,7 @@ public class CorrelationStrategyAdapterTests { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleMessageCorrelator(), "getKey"); adapter.setBeanFactory(mock(BeanFactory.class)); - assertEquals("b", adapter.getCorrelationKey(message)); + assertThat(adapter.getCorrelationKey(message)).isEqualTo("b"); } @Test @@ -56,7 +56,7 @@ public class CorrelationStrategyAdapterTests { new MethodInvokingCorrelationStrategy(new SimpleMessageCorrelator(), ReflectionUtils.findMethod(SimpleMessageCorrelator.class, "getKey", Message.class)); adapter.setBeanFactory(mock(BeanFactory.class)); - assertEquals("b", adapter.getCorrelationKey(message)); + assertThat(adapter.getCorrelationKey(message)).isEqualTo("b"); } @Test @@ -64,7 +64,7 @@ public class CorrelationStrategyAdapterTests { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimplePojoCorrelator(), "getKey"); adapter.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", adapter.getCorrelationKey(message)); + assertThat(adapter.getCorrelationKey(message)).isEqualTo("foo"); } @Test @@ -72,7 +72,7 @@ public class CorrelationStrategyAdapterTests { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleHeaderCorrelator(), "getKey"); adapter.setBeanFactory(mock(BeanFactory.class)); - assertEquals("b", adapter.getCorrelationKey(message)); + assertThat(adapter.getCorrelationKey(message)).isEqualTo("b"); } @Test @@ -80,7 +80,7 @@ public class CorrelationStrategyAdapterTests { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new MultiHeaderCorrelator(), ReflectionUtils.findMethod(MultiHeaderCorrelator.class, "getKey", String.class, String.class)); adapter.setBeanFactory(mock(BeanFactory.class)); - assertEquals("bd", adapter.getCorrelationKey(message)); + assertThat(adapter.getCorrelationKey(message)).isEqualTo("bd"); } private static class MultiHeaderCorrelator { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java index eb182511e1..335b82b57d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingCorrelationStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; @@ -65,8 +62,8 @@ public class ExpressionEvaluatingCorrelationStrategyTests { strategy = new ExpressionEvaluatingCorrelationStrategy(expression); strategy.setBeanFactory(mock(BeanFactory.class)); Object correlationKey = strategy.getCorrelationKey(new GenericMessage("bla")); - assertThat(correlationKey, is(instanceOf(String.class))); - assertThat((String) correlationKey, is("b")); + assertThat(correlationKey).isInstanceOf(String.class); + assertThat((String) correlationKey).isEqualTo("b"); } @Test @@ -78,7 +75,7 @@ public class ExpressionEvaluatingCorrelationStrategyTests { Message message = MessageBuilder.withPayload("foo").setSequenceNumber(1).setSequenceSize(1).build(); inputChannel.send(message); Message reply = outputChannel.receive(0); - assertNotNull(reply); + assertThat(reply).isNotNull(); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java index 2443118ee5..328e8817b1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingMessageGroupProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -69,9 +68,9 @@ public class ExpressionEvaluatingMessageGroupProcessorTests { processor = new ExpressionEvaluatingMessageGroupProcessor("#root.size()"); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessageGroup(group); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertEquals(5, resultMessage.getPayload()); + assertThat(resultMessage.getPayload()).isEqualTo(5); } @Test @@ -81,9 +80,9 @@ public class ExpressionEvaluatingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessageGroup(group); processor.setBeanFactory(mock(BeanFactory.class)); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertEquals("bar", resultMessage.getHeaders().get("foo")); + assertThat(resultMessage.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -92,16 +91,16 @@ public class ExpressionEvaluatingMessageGroupProcessorTests { processor = new ExpressionEvaluatingMessageGroupProcessor("![payload]"); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessageGroup(group); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertTrue(resultMessage.getPayload() instanceof Collection); + assertThat(resultMessage.getPayload() instanceof Collection).isTrue(); Collection list = (Collection) resultMessage.getPayload(); - assertEquals(5, list.size()); - assertTrue(list.contains(1)); - assertTrue(list.contains(2)); - assertTrue(list.contains(3)); - assertTrue(list.contains(4)); - assertTrue(list.contains(5)); + assertThat(list.size()).isEqualTo(5); + assertThat(list.contains(1)).isTrue(); + assertThat(list.contains(2)).isTrue(); + assertThat(list.contains(3)).isTrue(); + assertThat(list.contains(4)).isTrue(); + assertThat(list.contains(5)).isTrue(); } @Test @@ -110,14 +109,14 @@ public class ExpressionEvaluatingMessageGroupProcessorTests { processor = new ExpressionEvaluatingMessageGroupProcessor("?[payload>2].![payload]"); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessageGroup(group); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertTrue(resultMessage.getPayload() instanceof Collection); + assertThat(resultMessage.getPayload() instanceof Collection).isTrue(); Collection list = (Collection) resultMessage.getPayload(); - assertEquals(3, list.size()); - assertTrue(list.contains(3)); - assertTrue(list.contains(4)); - assertTrue(list.contains(5)); + assertThat(list.size()).isEqualTo(3); + assertThat(list.contains(3)).isTrue(); + assertThat(list.contains(4)).isTrue(); + assertThat(list.contains(5)).isTrue(); } @Test @@ -127,9 +126,9 @@ public class ExpressionEvaluatingMessageGroupProcessorTests { getClass().getName())); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessageGroup(group); - assertTrue(result instanceof AbstractIntegrationMessageBuilder); + assertThat(result instanceof AbstractIntegrationMessageBuilder).isTrue(); Message resultMessage = ((AbstractIntegrationMessageBuilder) result).build(); - assertEquals(3 + 4 + 5, resultMessage.getPayload()); + assertThat(resultMessage.getPayload()).isEqualTo(3 + 4 + 5); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java index 4c6ee875a5..d0b75cc74a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ExpressionEvaluatingReleaseStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Before; @@ -52,21 +51,21 @@ public class ExpressionEvaluatingReleaseStrategyTests { public void testCompletedWithSizeSpelEvaluated() { strategy = new ExpressionEvaluatingReleaseStrategy("#root.size()==5"); strategy.setBeanFactory(mock(BeanFactory.class)); - assertThat(strategy.canRelease(messages), is(true)); + assertThat(strategy.canRelease(messages)).isTrue(); } @Test public void testCompletedWithFilterSpelEvaluated() { strategy = new ExpressionEvaluatingReleaseStrategy("!messages.?[payload==5].empty"); strategy.setBeanFactory(mock(BeanFactory.class)); - assertThat(strategy.canRelease(messages), is(true)); + assertThat(strategy.canRelease(messages)).isTrue(); } @Test public void testCompletedWithFilterSpelReturnsNotCompleted() { strategy = new ExpressionEvaluatingReleaseStrategy("!messages.?[payload==6].empty"); strategy.setBeanFactory(mock(BeanFactory.class)); - assertThat(strategy.canRelease(messages), is(false)); + assertThat(strategy.canRelease(messages)).isFalse(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java index e1e9b2f70c..c02533392d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -34,7 +34,7 @@ public class HeaderAttributeCorrelationStrategyTests { String testHeaderName = "header.for.test"; Message message = MessageBuilder.withPayload("irrelevantData").setHeader(testHeaderName, testedHeaderValue).build(); HeaderAttributeCorrelationStrategy correlationStrategy = new HeaderAttributeCorrelationStrategy(testHeaderName); - assertEquals(testedHeaderValue, correlationStrategy.getCorrelationKey(message)); + assertThat(correlationStrategy.getCorrelationKey(message)).isEqualTo(testedHeaderValue); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MessageSequenceComparatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MessageSequenceComparatorTests.java index 044adbe1e8..e17a05d0a7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MessageSequenceComparatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MessageSequenceComparatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Comparator; @@ -38,7 +38,7 @@ public class MessageSequenceComparatorTests { .setSequenceNumber(1).build(); Message message2 = MessageBuilder.withPayload("test2") .setSequenceNumber(2).build(); - assertEquals(-1, comparator.compare(message1, message2)); + assertThat(comparator.compare(message1, message2)).isEqualTo(-1); } @Test @@ -48,7 +48,7 @@ public class MessageSequenceComparatorTests { .setSequenceNumber(3).build(); Message message2 = MessageBuilder.withPayload("test2") .setSequenceNumber(3).build(); - assertEquals(0, comparator.compare(message1, message2)); + assertThat(comparator.compare(message1, message2)).isEqualTo(0); } @Test @@ -58,7 +58,7 @@ public class MessageSequenceComparatorTests { .setSequenceNumber(5).build(); Message message2 = MessageBuilder.withPayload("test2") .setSequenceNumber(3).build(); - assertEquals(1, comparator.compare(message1, message2)); + assertThat(comparator.compare(message1, message2)).isEqualTo(1); } @Test @@ -66,7 +66,7 @@ public class MessageSequenceComparatorTests { Comparator> comparator = new MessageSequenceComparator(); Message message1 = MessageBuilder.withPayload("test1").build(); Message message2 = MessageBuilder.withPayload("test2").build(); - assertEquals(0, comparator.compare(message1, message2)); + assertThat(comparator.compare(message1, message2)).isEqualTo(0); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java index cfb41740c7..c7be73e916 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java @@ -16,12 +16,8 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -108,7 +104,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); } @Test @@ -132,7 +128,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); } @Test @@ -156,7 +152,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); } @Test @@ -184,7 +180,8 @@ public class MethodInvokingMessageGroupProcessorTests { messagesUpForProcessing.add(MessageBuilder.withPayload(3).setHeader("foo", Arrays.asList(101, 102)).build()); when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); Object result = processor.processMessageGroup(messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is("[1, 2, 4, 3, 101, 102]")); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()) + .isEqualTo("[1, 2, 4, 3, 101, 102]"); } @Test @@ -217,7 +214,8 @@ public class MethodInvokingMessageGroupProcessorTests { .build()); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is("[1, 2, 4, 3, 101, 102]")); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()) + .isEqualTo("[1, 2, 4, 3, 101, 102]"); } @Test @@ -242,7 +240,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is("[1, 2, 4]")); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo("[1, 2, 4]"); } @Test @@ -266,7 +264,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); } @Test @@ -290,7 +288,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); } @@ -325,7 +323,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setConversionService(conversionService); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); } @Test @@ -358,7 +356,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isEqualTo(7); } @Test @@ -388,7 +386,7 @@ public class MethodInvokingMessageGroupProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); - assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), instanceOf(Iterator.class)); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload()).isInstanceOf(Iterator.class); } @Test @@ -419,8 +417,8 @@ public class MethodInvokingMessageGroupProcessorTests { when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); Object result = processor.processMessageGroup(this.messageGroupMock); Object payload = ((AbstractIntegrationMessageBuilder) result).build().getPayload(); - assertTrue(payload instanceof Integer); - assertEquals(7, payload); + assertThat(payload instanceof Integer).isTrue(); + assertThat(payload).isEqualTo(7); } @@ -447,7 +445,7 @@ public class MethodInvokingMessageGroupProcessorTests { SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(new GenericMessage<>("foo")); group.add(new GenericMessage<>("bar")); - assertEquals("foo", aggregator.aggregatePayloads(group, null)); + assertThat(aggregator.aggregatePayloads(group, null)).isEqualTo("foo"); } @Test @@ -468,7 +466,7 @@ public class MethodInvokingMessageGroupProcessorTests { SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(MessageBuilder.withPayload("foo").setHeader("foo", "bar").build()); group.add(MessageBuilder.withPayload("bar").setHeader("foo", "bar").build()); - assertEquals("foobar", processor.aggregatePayloads(group, processor.aggregateHeaders(group))); + assertThat(processor.aggregatePayloads(group, processor.aggregateHeaders(group))).isEqualTo("foobar"); } @Test @@ -489,7 +487,7 @@ public class MethodInvokingMessageGroupProcessorTests { SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(MessageBuilder.withPayload("foo").setHeader("foo", "bar").build()); group.add(MessageBuilder.withPayload("bar").setHeader("foo", "bar").build()); - assertEquals("foobar", aggregator.aggregatePayloads(group, aggregator.aggregateHeaders(group))); + assertThat(aggregator.aggregatePayloads(group, aggregator.aggregateHeaders(group))).isEqualTo("foobar"); } @Test(expected = IllegalArgumentException.class) @@ -535,7 +533,7 @@ public class MethodInvokingMessageGroupProcessorTests { SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(new GenericMessage<>("foo")); group.add(new GenericMessage<>("bar")); - assertEquals("foo", aggregator.aggregatePayloads(group, null)); + assertThat(aggregator.aggregatePayloads(group, null)).isEqualTo("foo"); } @Test(expected = IllegalArgumentException.class) @@ -593,7 +591,7 @@ public class MethodInvokingMessageGroupProcessorTests { Message message = MessageBuilder.withPayload("proxy").setCorrelationId("abc").build(); input.send(message); - assertEquals("hello proxy", output.receive(0).getPayload()); + assertThat(output.receive(0).getPayload()).isEqualTo("hello proxy"); } @Test @@ -615,7 +613,7 @@ public class MethodInvokingMessageGroupProcessorTests { Message message = MessageBuilder.withPayload("proxy").setCorrelationId("abc").build(); input.send(message); - assertEquals("hello proxy", output.receive(0).getPayload()); + assertThat(output.receive(0).getPayload()).isEqualTo("hello proxy"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java index add00e6d27..0c9d106176 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java @@ -16,8 +16,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -47,7 +46,7 @@ public class MethodInvokingReleaseStrategyTests { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new AlwaysTrueReleaseStrategy(), "checkCompleteness"); adapter.setBeanFactory(mock(BeanFactory.class)); - assertTrue(adapter.canRelease(createListOfMessages(0))); + assertThat(adapter.canRelease(createListOfMessages(0))).isTrue(); } @Test @@ -55,7 +54,7 @@ public class MethodInvokingReleaseStrategyTests { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new AlwaysFalseReleaseStrategy(), "checkCompleteness"); adapter.setBeanFactory(mock(BeanFactory.class)); - assertFalse(adapter.canRelease(createListOfMessages(0))); + assertThat(adapter.canRelease(createListOfMessages(0))).isFalse(); } @Test @@ -64,7 +63,7 @@ public class MethodInvokingReleaseStrategyTests { @SuppressWarnings("unused") public boolean checkCompletenessOnNonParameterizedListOfMessages(List> messages) { - assertTrue(messages.size() > 0); + assertThat(messages.size() > 0).isTrue(); return messages.size() > new IntegrationMessageHeaderAccessor(messages.iterator().next()).getSequenceSize(); } @@ -74,7 +73,7 @@ public class MethodInvokingReleaseStrategyTests { "checkCompletenessOnNonParameterizedListOfMessages"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test @@ -83,7 +82,7 @@ public class MethodInvokingReleaseStrategyTests { @SuppressWarnings("unused") public boolean checkCompletenessOnListOfMessagesParametrizedWithWildcard(List> messages) { - assertTrue(messages.size() > 0); + assertThat(messages.size() > 0).isTrue(); return messages.size() > new IntegrationMessageHeaderAccessor(messages.iterator().next()).getSequenceSize(); } @@ -93,7 +92,7 @@ public class MethodInvokingReleaseStrategyTests { "checkCompletenessOnListOfMessagesParametrizedWithWildcard"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test @@ -102,7 +101,7 @@ public class MethodInvokingReleaseStrategyTests { @SuppressWarnings("unused") public boolean checkCompletenessOnListOfMessagesParametrizedWithString(List> messages) { - assertTrue(messages.size() > 0); + assertThat(messages.size() > 0).isTrue(); return messages.size() > new IntegrationMessageHeaderAccessor(messages.iterator().next()) .getSequenceSize(); } @@ -112,7 +111,7 @@ public class MethodInvokingReleaseStrategyTests { "checkCompletenessOnListOfMessagesParametrizedWithString"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test @@ -135,7 +134,7 @@ public class MethodInvokingReleaseStrategyTests { "checkCompletenessOnListOfStrings"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test @@ -158,7 +157,7 @@ public class MethodInvokingReleaseStrategyTests { "checkCompletenessOnListOfStrings"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test(expected = IllegalStateException.class) @@ -183,7 +182,7 @@ public class MethodInvokingReleaseStrategyTests { new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "invalidParameterType"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test(expected = IllegalStateException.class) @@ -240,7 +239,7 @@ public class MethodInvokingReleaseStrategyTests { "listSubclassParameter"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test(expected = ConversionFailedException.class) @@ -257,7 +256,7 @@ public class MethodInvokingReleaseStrategyTests { new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "wrongReturnType"); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test(expected = IllegalArgumentException.class) @@ -288,7 +287,7 @@ public class MethodInvokingReleaseStrategyTests { TestReleaseStrategy.class.getMethod("listSubclassParameter", LinkedList.class)); adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - assertTrue(adapter.canRelease(messages)); + assertThat(adapter.canRelease(messages)).isTrue(); } @Test(expected = IllegalStateException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java index 7f49f19c32..0baa2ad176 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -80,12 +75,12 @@ public class ResequencerTests { Message reply1 = replyChannel.receive(0); Message reply2 = replyChannel.receive(0); Message reply3 = replyChannel.receive(0); - assertNotNull(reply1); - assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber(), is(1)); - assertNotNull(reply2); - assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber(), is(2)); - assertNotNull(reply3); - assertThat(new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber(), is(3)); + assertThat(reply1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()).isEqualTo(1); + assertThat(reply2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()).isEqualTo(2); + assertThat(reply3).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()).isEqualTo(3); } @Test @@ -101,10 +96,10 @@ public class ResequencerTests { Message message3 = createMessage("789", "ABC", 3, 3, replyChannel); this.resequencer.handleMessage(message3); - assertNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNull(); this.resequencer.handleMessage(message1); - assertNotNull(replyChannel.receive(0)); - assertNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNotNull(); + assertThat(replyChannel.receive(0)).isNull(); } @Test @@ -125,20 +120,20 @@ public class ResequencerTests { Message message5 = MessageBuilder.withPayload("5").setSequenceNumber(5).setReplyChannel(replyChannel).build(); this.resequencer.handleMessage(message3); - assertNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNull(); this.resequencer.handleMessage(message1); - assertNotNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNotNull(); this.resequencer.handleMessage(message2); - assertNotNull(replyChannel.receive(0)); - assertNotNull(replyChannel.receive(0)); - assertNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNotNull(); + assertThat(replyChannel.receive(0)).isNotNull(); + assertThat(replyChannel.receive(0)).isNull(); this.resequencer.handleMessage(message5); - assertNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNull(); this.resequencer.handleMessage(message4); - assertNotNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNotNull(); } @Test @@ -154,12 +149,12 @@ public class ResequencerTests { Message reply1 = replyChannel.receive(0); Message reply2 = replyChannel.receive(0); Message reply3 = replyChannel.receive(0); - assertNotNull(reply1); - assertEquals(1, new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()); - assertNotNull(reply2); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()); - assertNotNull(reply3); - assertEquals(3, new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()); + assertThat(reply1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()).isEqualTo(1); + assertThat(reply2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()).isEqualTo(2); + assertThat(reply3).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()).isEqualTo(3); } @Test @@ -179,19 +174,19 @@ public class ResequencerTests { Message reply2 = replyChannel.receive(0); Message reply3 = replyChannel.receive(0); // only messages 1 and 2 should have been received by now - assertNotNull(reply1); - assertEquals(1, new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()); - assertNotNull(reply2); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()); - assertNull(reply3); + assertThat(reply1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()).isEqualTo(1); + assertThat(reply2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()).isEqualTo(2); + assertThat(reply3).isNull(); // when sending the last message, the whole sequence must have been sent this.resequencer.handleMessage(message4); reply3 = replyChannel.receive(0); Message reply4 = replyChannel.receive(0); - assertNotNull(reply3); - assertEquals(3, new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()); - assertNotNull(reply4); - assertEquals(4, new IntegrationMessageHeaderAccessor(reply4).getSequenceNumber()); + assertThat(reply3).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()).isEqualTo(3); + assertThat(reply4).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply4).getSequenceNumber()).isEqualTo(4); } @Test @@ -210,7 +205,7 @@ public class ResequencerTests { fail("Expected exception"); } catch (MessagingException e) { - assertThat(e.getMessage(), containsString("out of capacity (2) for group 'ABC'")); + assertThat(e.getMessage()).contains("out of capacity (2) for group 'ABC'"); } } @@ -229,19 +224,19 @@ public class ResequencerTests { Message reply2 = replyChannel.receive(0); Message reply3 = replyChannel.receive(0); // only messages 1 and 2 should have been received by now - assertNotNull(reply1); - assertEquals(1, new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()); - assertNotNull(reply2); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()); - assertNull(reply3); + assertThat(reply1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()).isEqualTo(1); + assertThat(reply2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()).isEqualTo(2); + assertThat(reply3).isNull(); // when sending the last message, the whole sequence must have been sent this.resequencer.handleMessage(message4); reply3 = replyChannel.receive(0); Message reply4 = replyChannel.receive(0); - assertNotNull(reply3); - assertEquals(3, new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()); - assertNotNull(reply4); - assertEquals(4, new IntegrationMessageHeaderAccessor(reply4).getSequenceNumber()); + assertThat(reply3).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()).isEqualTo(3); + assertThat(reply4).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply4).getSequenceNumber()).isEqualTo(4); } @Test @@ -254,23 +249,23 @@ public class ResequencerTests { this.resequencer.setDiscardChannel(discardChannel); this.resequencer.handleMessage(message1); this.resequencer.handleMessage(message2); - assertEquals(1, store.expireMessageGroups(-10000)); + assertThat(store.expireMessageGroups(-10000)).isEqualTo(1); Message reply1 = discardChannel.receive(0); Message reply2 = discardChannel.receive(0); Message reply3 = discardChannel.receive(0); // only messages 1 and 2 should have been received by now - assertNotNull(reply1); - assertNotNull(reply2); - assertNull(reply3); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNotNull(); + assertThat(reply3).isNull(); ArrayList sequence = new ArrayList<>( Arrays.asList(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber(), new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber())); Collections.sort(sequence); - assertEquals("[1, 2]", sequence.toString()); + assertThat(sequence.toString()).isEqualTo("[1, 2]"); // Once a group is expired, late messages are discarded immediately by default this.resequencer.handleMessage(message3); reply3 = discardChannel.receive(0); - assertNotNull(reply3); + assertThat(reply3).isNotNull(); } @Test @@ -287,9 +282,9 @@ public class ResequencerTests { Message discard1 = discardChannel.receive(0); Message discard2 = discardChannel.receive(0); // message2 has been discarded because it came in with the wrong sequence size - assertNotNull(discard1); - assertEquals(1, new IntegrationMessageHeaderAccessor(discard1).getSequenceNumber()); - assertNull(discard2); + assertThat(discard1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(discard1).getSequenceNumber()).isEqualTo(1); + assertThat(discard2).isNull(); } @Test @@ -302,7 +297,7 @@ public class ResequencerTests { // this.resequencer.discardBarrier(this.resequencer.barriers.get("ABC")); Message reply1 = discardChannel.receive(0); // No message has been received - the message has been rejected. - assertNull(reply1); + assertThat(reply1).isNull(); } @Test @@ -319,23 +314,23 @@ public class ResequencerTests { Message reply2 = replyChannel.receive(0); Message reply3 = replyChannel.receive(0); // no messages should have been received yet - assertNull(reply1); - assertNull(reply2); - assertNull(reply3); + assertThat(reply1).isNull(); + assertThat(reply2).isNull(); + assertThat(reply3).isNull(); // after sending the last message, the whole sequence should have been sent this.resequencer.handleMessage(message4); reply1 = replyChannel.receive(0); reply2 = replyChannel.receive(0); reply3 = replyChannel.receive(0); Message reply4 = replyChannel.receive(0); - assertNotNull(reply1); - assertEquals(1, new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()); - assertNotNull(reply2); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()); - assertNotNull(reply3); - assertEquals(3, new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()); - assertNotNull(reply4); - assertEquals(4, new IntegrationMessageHeaderAccessor(reply4).getSequenceNumber()); + assertThat(reply1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()).isEqualTo(1); + assertThat(reply2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()).isEqualTo(2); + assertThat(reply3).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply3).getSequenceNumber()).isEqualTo(3); + assertThat(reply4).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply4).getSequenceNumber()).isEqualTo(4); } @Test @@ -344,7 +339,7 @@ public class ResequencerTests { String correlationId = "ABC"; Message message1 = createMessage("123", correlationId, 1, 1, replyChannel); resequencer.handleMessage(message1); - assertEquals(0, store.getMessageGroup(correlationId).size()); + assertThat(store.getMessageGroup(correlationId).size()).isEqualTo(0); } @Test @@ -363,15 +358,15 @@ public class ResequencerTests { this.resequencer.handleMessage(message3); this.resequencer.handleMessage(message2); Message out1 = replyChannel.receive(10); - assertNull(out1); + assertThat(out1).isNull(); out1 = discardChannel.receive(10000); - assertNotNull(out1); + assertThat(out1).isNotNull(); Message out2 = discardChannel.receive(10); - assertNotNull(out2); + assertThat(out2).isNotNull(); Message message1 = createMessage("123", "ABC", 3, 1, null); this.resequencer.handleMessage(message1); Message out3 = discardChannel.receive(0); - assertNotNull(out3); + assertThat(out3).isNotNull(); } @Test @@ -391,17 +386,17 @@ public class ResequencerTests { this.resequencer.handleMessage(message3); this.resequencer.handleMessage(message2); Message out1 = replyChannel.receive(0); - assertNull(out1); + assertThat(out1).isNull(); out1 = discardChannel.receive(10_000); - assertNotNull(out1); + assertThat(out1).isNotNull(); Message out2 = discardChannel.receive(10_000); - assertNotNull(out2); + assertThat(out2).isNotNull(); Message message1 = createMessage("123", "ABC", 3, 1, null); this.resequencer.handleMessage(message1); Message out3 = discardChannel.receive(0); - assertNull(out3); + assertThat(out3).isNull(); out3 = discardChannel.receive(10_000); - assertNotNull(out3); + assertThat(out3).isNotNull(); } private static Message createMessage(String payload, Object correlationId, int sequenceSize, int sequenceNumber, diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessorTests.java index d588bc6b8b..7ddf3d71b5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencingMessageGroupProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -50,7 +48,7 @@ public class ResequencingMessageGroupProcessorTests { messages.add(message3); SimpleMessageGroup group = new SimpleMessageGroup(messages, "x"); List processedMessages = (List) processor.processMessageGroup(group); - assertThat(processedMessages, hasItems(message1, message2, message3)); + assertThat(processedMessages).contains(message1, message2, message3); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -66,8 +64,8 @@ public class ResequencingMessageGroupProcessorTests { messages.add(message3); SimpleMessageGroup group = new SimpleMessageGroup(messages, "x"); List processedMessages = (List) processor.processMessageGroup(group); - assertThat(processedMessages, hasItems(message1)); - assertThat(processedMessages.size(), is(1)); + assertThat(processedMessages).contains(message1); + assertThat(processedMessages.size()).isEqualTo(1); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/SequenceSizeReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/SequenceSizeReleaseStrategyTests.java index 196e908ac2..cddfcd63ef 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/SequenceSizeReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/SequenceSizeReleaseStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -39,7 +38,7 @@ public class SequenceSizeReleaseStrategyTests { SimpleMessageGroup messages = new SimpleMessageGroup("FOO"); messages.add(message); SequenceSizeReleaseStrategy releaseStrategy = new SequenceSizeReleaseStrategy(); - assertFalse(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isFalse(); } @Test @@ -50,13 +49,13 @@ public class SequenceSizeReleaseStrategyTests { messages.add(message1); messages.add(message2); SequenceSizeReleaseStrategy releaseStrategy = new SequenceSizeReleaseStrategy(); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); } @Test public void testEmptyList() { SequenceSizeReleaseStrategy releaseStrategy = new SequenceSizeReleaseStrategy(); - assertTrue(releaseStrategy.canRelease(new SimpleMessageGroup("FOO"))); + assertThat(releaseStrategy.canRelease(new SimpleMessageGroup("FOO"))).isTrue(); } @Test @@ -67,7 +66,7 @@ public class SequenceSizeReleaseStrategyTests { Message message = MessageBuilder.withPayload("test1").setSequenceSize(1).build(); messages.add(message); messages.remove(message); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); } @Test @@ -77,7 +76,7 @@ public class SequenceSizeReleaseStrategyTests { SimpleMessageGroup messages = new SimpleMessageGroup("FOO"); - assertTrue(releaseStrategy.canRelease(groupWithFirstMessagesOfIncompleteSequence(messages))); + assertThat(releaseStrategy.canRelease(groupWithFirstMessagesOfIncompleteSequence(messages))).isTrue(); } private SimpleMessageGroup groupWithFirstMessagesOfIncompleteSequence(SimpleMessageGroup messages) { @@ -96,7 +95,7 @@ public class SequenceSizeReleaseStrategyTests { boolean canRelease = releaseStrategy.canRelease(groupWithLastAndFirstMessagesOfIncompleteSequence()); - assertTrue(canRelease); + assertThat(canRelease).isTrue(); } private MessageGroup groupWithLastAndFirstMessagesOfIncompleteSequence() { @@ -124,15 +123,15 @@ public class SequenceSizeReleaseStrategyTests { Message message5 = MessageBuilder.withPayload("test5").setSequenceSize(5).setSequenceNumber(5).build(); messages.add(message5); - assertFalse(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isFalse(); messages.add(message1); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); messages.add(message2); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); messages.add(message3); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); messages.add(message4); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/TimeoutCountSequenceSizeReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/TimeoutCountSequenceSizeReleaseStrategyTests.java index 4eb2815a7c..29f0baf249 100755 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/TimeoutCountSequenceSizeReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/TimeoutCountSequenceSizeReleaseStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -38,7 +37,7 @@ public class TimeoutCountSequenceSizeReleaseStrategyTests { SimpleMessageGroup messages = new SimpleMessageGroup("FOO"); messages.add(message); TimeoutCountSequenceSizeReleaseStrategy releaseStrategy = new TimeoutCountSequenceSizeReleaseStrategy(); - assertFalse(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isFalse(); } @Test @@ -50,7 +49,7 @@ public class TimeoutCountSequenceSizeReleaseStrategyTests { TimeoutCountSequenceSizeReleaseStrategy releaseStrategy = new TimeoutCountSequenceSizeReleaseStrategy(TimeoutCountSequenceSizeReleaseStrategy.DEFAULT_THRESHOLD, -100); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); } @Test @@ -62,7 +61,7 @@ public class TimeoutCountSequenceSizeReleaseStrategyTests { TimeoutCountSequenceSizeReleaseStrategy releaseStrategy = new TimeoutCountSequenceSizeReleaseStrategy(1, TimeoutCountSequenceSizeReleaseStrategy.DEFAULT_TIMEOUT); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); } @Test @@ -75,13 +74,13 @@ public class TimeoutCountSequenceSizeReleaseStrategyTests { messages.add(message1); messages.add(message2); SequenceSizeReleaseStrategy releaseStrategy = new SequenceSizeReleaseStrategy(); - assertTrue(releaseStrategy.canRelease(messages)); + assertThat(releaseStrategy.canRelease(messages)).isTrue(); } @Test public void testEmptyList() { SequenceSizeReleaseStrategy releaseStrategy = new SequenceSizeReleaseStrategy(); - assertTrue(releaseStrategy.canRelease(new SimpleMessageGroup("FOO"))); + assertThat(releaseStrategy.canRelease(new SimpleMessageGroup("FOO"))).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorExpressionIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorExpressionIntegrationTests.java index 51f6467ff3..d58c7348b7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorExpressionIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorExpressionIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator.integration; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; @@ -57,7 +57,7 @@ public class AggregatorExpressionIntegrationTests { Map headers = stubHeaders(i, 5, 1); this.input.send(new GenericMessage<>(i, headers)); } - assertEquals("[0, 1, 2, 3, 4]", this.output.receive().getPayload()); + assertThat(this.output.receive().getPayload()).isEqualTo("[0, 1, 2, 3, 4]"); } private Map stubHeaders(int sequenceNumber, int sequenceSize, int correllationId) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorIntegrationTests.java index 11e977e164..29c42e5ffe 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.aggregator.integration; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.Collections; @@ -95,8 +90,8 @@ public class AggregatorIntegrationTests { input.send(new GenericMessage<>(i, headers)); } Message receive = output.receive(10000); - assertNotNull(receive); - assertEquals(1 + 2 + 3 + 4, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(1 + 2 + 3 + 4); } @Test @@ -105,21 +100,21 @@ public class AggregatorIntegrationTests { Map headers = stubHeaders(i, 5, 1); nonExpiringAggregatorInput.send(new GenericMessage<>(i, headers)); } - assertNotNull(output.receive(0)); + assertThat(output.receive(0)).isNotNull(); - assertNull(discard.receive(0)); + assertThat(discard.receive(0)).isNull(); for (int i = 5; i < 10; i++) { Map headers = stubHeaders(i, 5, 1); nonExpiringAggregatorInput.send(new GenericMessage<>(i, headers)); } - assertNull(output.receive(0)); + assertThat(output.receive(0)).isNull(); - assertNotNull(discard.receive(0)); - assertNotNull(discard.receive(0)); - assertNotNull(discard.receive(0)); - assertNotNull(discard.receive(0)); - assertNotNull(discard.receive(0)); + assertThat(discard.receive(0)).isNotNull(); + assertThat(discard.receive(0)).isNotNull(); + assertThat(discard.receive(0)).isNotNull(); + assertThat(discard.receive(0)).isNotNull(); + assertThat(discard.receive(0)).isNotNull(); } @Test @@ -128,17 +123,17 @@ public class AggregatorIntegrationTests { Map headers = stubHeaders(i, 5, 1); expiringAggregatorInput.send(new GenericMessage<>(i, headers)); } - assertNotNull(output.receive(0)); + assertThat(output.receive(0)).isNotNull(); - assertNull(discard.receive(0)); + assertThat(discard.receive(0)).isNull(); for (int i = 5; i < 10; i++) { Map headers = stubHeaders(i, 5, 1); expiringAggregatorInput.send(new GenericMessage<>(i, headers)); } - assertNotNull(output.receive(0)); + assertThat(output.receive(0)).isNotNull(); - assertNull(discard.receive(0)); + assertThat(discard.receive(0)).isNull(); } @@ -155,9 +150,9 @@ public class AggregatorIntegrationTests { while (n++ < 100 && mgs.getMessageGroupCount() > 0) { Thread.sleep(100); } - assertTrue("Group did not complete", n < 100); - assertNotNull(this.output.receive(10000)); - assertNull(this.discard.receive(0)); + assertThat(n < 100).as("Group did not complete").isTrue(); + assertThat(this.output.receive(10000)).isNotNull(); + assertThat(this.discard.receive(0)).isNull(); } } @@ -180,50 +175,50 @@ public class AggregatorIntegrationTests { TestUtils.getPropertyValue(this.output, "queue", Queue.class).clear(); } } - assertTrue("Group did not complete", n < 100); + assertThat(n < 100).as("Group did not complete").isTrue(); Message receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(Collections.singletonList(1), receive.getPayload()); - assertNull(this.discard.receive(0)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(Collections.singletonList(1)); + assertThat(this.discard.receive(0)).isNull(); } @Test public void testGroupTimeoutExpressionScheduling() { // Since group-timeout-expression="size() >= 2 ? 100 : null". The first message won't be scheduled to 'forceComplete' this.groupTimeoutExpressionAggregatorInput.send(new GenericMessage<>(1, stubHeaders(1, 6, 1))); - assertNull(this.output.receive(0)); - assertNull(this.discard.receive(0)); + assertThat(this.output.receive(0)).isNull(); + assertThat(this.discard.receive(0)).isNull(); // As far as 'group.size() >= 2' it will be scheduled to 'forceComplete' this.groupTimeoutExpressionAggregatorInput.send(new GenericMessage<>(2, stubHeaders(2, 6, 1))); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); Message receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(2, ((Collection) receive.getPayload()).size()); - assertNull(this.discard.receive(0)); + assertThat(receive).isNotNull(); + assertThat(((Collection) receive.getPayload()).size()).isEqualTo(2); + assertThat(this.discard.receive(0)).isNull(); // The same with these three messages this.groupTimeoutExpressionAggregatorInput.send(new GenericMessage<>(3, stubHeaders(3, 6, 1))); - assertNull(this.output.receive(0)); - assertNull(this.discard.receive(0)); + assertThat(this.output.receive(0)).isNull(); + assertThat(this.discard.receive(0)).isNull(); this.groupTimeoutExpressionAggregatorInput.send(new GenericMessage<>(4, stubHeaders(4, 6, 1))); - assertNull(this.output.receive(0)); - assertNull(this.discard.receive(0)); + assertThat(this.output.receive(0)).isNull(); + assertThat(this.discard.receive(0)).isNull(); this.groupTimeoutExpressionAggregatorInput.send(new GenericMessage<>(5, stubHeaders(5, 6, 1))); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(3, ((Collection) receive.getPayload()).size()); - assertNull(this.discard.receive(0)); + assertThat(receive).isNotNull(); + assertThat(((Collection) receive.getPayload()).size()).isEqualTo(3); + assertThat(this.discard.receive(0)).isNull(); // The last message in the sequence - normal release by provided 'ReleaseStrategy' this.groupTimeoutExpressionAggregatorInput.send(new GenericMessage<>(6, stubHeaders(6, 6, 1))); receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(1, ((Collection) receive.getPayload()).size()); - assertNull(this.discard.receive(0)); + assertThat(receive).isNotNull(); + assertThat(((Collection) receive.getPayload()).size()).isEqualTo(1); + assertThat(this.discard.receive(0)).isNull(); } @Test @@ -239,9 +234,9 @@ public class AggregatorIntegrationTests { this.output.send(message); this.zeroGroupTimeoutExpressionAggregatorInput.send(new GenericMessage<>(1, stubHeaders(1, 2, 1))); ErrorMessage em = (ErrorMessage) this.errors.receive(10000); - assertNotNull(em); - assertThat(em.getPayload().getMessage().toLowerCase(), - containsString("failed to send message to channel 'output' within timeout: 10")); + assertThat(em).isNotNull(); + assertThat(em.getPayload().getMessage().toLowerCase()) + .contains("failed to send message to channel 'output' within timeout: 10"); } finally { this.output.purge(null); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java index 10bb4f8995..009f5de762 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator.integration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -56,19 +54,19 @@ public class AggregatorSupportedUseCasesTests { for (int i = 0; i < 5; i++) { defaultHandler.handleMessage(MessageBuilder.withPayload(i).setSequenceSize(5).setCorrelationId("A").setSequenceNumber(i).build()); } - assertEquals(5, ((List) outputChannel.receive(0).getPayload()).size()); - assertNull(discardChannel.receive(0)); - assertEquals(0, store.getMessageGroup("A").getMessages().size()); + assertThat(((List) outputChannel.receive(0).getPayload()).size()).isEqualTo(5); + assertThat(discardChannel.receive(0)).isNull(); + assertThat(store.getMessageGroup("A").getMessages().size()).isEqualTo(0); // send another message with the same correlation id and see it in the discard channel defaultHandler.handleMessage(MessageBuilder.withPayload("foo").setSequenceSize(5).setCorrelationId("A").setSequenceNumber(3).build()); - assertNotNull(discardChannel.receive(0)); + assertThat(discardChannel.receive(0)).isNotNull(); // expireMessageGroups from aggregator MessageStore and the messages should start accumulating again store.expireMessageGroups(0); defaultHandler.handleMessage(MessageBuilder.withPayload("foo").setSequenceSize(5).setCorrelationId("A").setSequenceNumber(3).build()); - assertNull(discardChannel.receive(0)); - assertEquals(1, store.getMessageGroup("A").getMessages().size()); + assertThat(discardChannel.receive(0)).isNull(); + assertThat(store.getMessageGroup("A").getMessages().size()).isEqualTo(1); } @Test @@ -82,19 +80,19 @@ public class AggregatorSupportedUseCasesTests { for (int i = 0; i < 5; i++) { defaultHandler.handleMessage(MessageBuilder.withPayload(i).setCorrelationId("A").build()); } - assertEquals(5, ((List) outputChannel.receive(0).getPayload()).size()); - assertNull(discardChannel.receive(0)); - assertEquals(0, store.getMessageGroup("A").getMessages().size()); + assertThat(((List) outputChannel.receive(0).getPayload()).size()).isEqualTo(5); + assertThat(discardChannel.receive(0)).isNull(); + assertThat(store.getMessageGroup("A").getMessages().size()).isEqualTo(0); // send another message with the same correlation id and see it in the discard channel defaultHandler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("A").build()); - assertNotNull(discardChannel.receive(0)); + assertThat(discardChannel.receive(0)).isNotNull(); // expireMessageGroups from aggregator MessageStore and the messages should start accumulating again store.expireMessageGroups(0); defaultHandler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("A").build()); - assertNull(discardChannel.receive(0)); - assertEquals(1, store.getMessageGroup("A").getMessages().size()); + assertThat(discardChannel.receive(0)).isNull(); + assertThat(store.getMessageGroup("A").getMessages().size()).isEqualTo(1); } @Test @@ -108,11 +106,11 @@ public class AggregatorSupportedUseCasesTests { for (int i = 0; i < 5; i++) { defaultHandler.handleMessage(MessageBuilder.withPayload(i).setCorrelationId("A").build()); } - assertEquals(1, ((List) outputChannel.receive(0).getPayload()).size()); - assertNotNull(discardChannel.receive(0)); - assertNotNull(discardChannel.receive(0)); - assertNotNull(discardChannel.receive(0)); - assertNotNull(discardChannel.receive(0)); + assertThat(((List) outputChannel.receive(0).getPayload()).size()).isEqualTo(1); + assertThat(discardChannel.receive(0)).isNotNull(); + assertThat(discardChannel.receive(0)).isNotNull(); + assertThat(discardChannel.receive(0)).isNotNull(); + assertThat(discardChannel.receive(0)).isNotNull(); } @Test @@ -127,9 +125,9 @@ public class AggregatorSupportedUseCasesTests { for (int i = 0; i < 10; i++) { defaultHandler.handleMessage(MessageBuilder.withPayload(i).setCorrelationId("A").build()); } - assertEquals(5, ((List) outputChannel.receive(0).getPayload()).size()); - assertEquals(5, ((List) outputChannel.receive(0).getPayload()).size()); - assertNull(discardChannel.receive(0)); + assertThat(((List) outputChannel.receive(0).getPayload()).size()).isEqualTo(5); + assertThat(((List) outputChannel.receive(0).getPayload()).size()).isEqualTo(5); + assertThat(discardChannel.receive(0)).isNull(); } @Test @@ -144,10 +142,10 @@ public class AggregatorSupportedUseCasesTests { for (int i = 0; i < 12; i++) { defaultHandler.handleMessage(MessageBuilder.withPayload(i).setCorrelationId("A").build()); } - assertEquals(5, ((List) outputChannel.receive(0).getPayload()).size()); - assertEquals(5, ((List) outputChannel.receive(0).getPayload()).size()); - assertNull(discardChannel.receive(0)); - assertEquals(2, store.getMessageGroup("A").getMessages().size()); + assertThat(((List) outputChannel.receive(0).getPayload()).size()).isEqualTo(5); + assertThat(((List) outputChannel.receive(0).getPayload()).size()).isEqualTo(5); + assertThat(discardChannel.receive(0)).isNull(); + assertThat(store.getMessageGroup("A").getMessages().size()).isEqualTo(2); } private class SampleSizeReleaseStrategy implements ReleaseStrategy { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AnnotationAggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AnnotationAggregatorTests.java index 0589916adf..e731b28d5f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AnnotationAggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AnnotationAggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator.integration; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -55,8 +55,8 @@ public class AnnotationAggregatorTests { @SuppressWarnings("unchecked") Message result = (Message) output.receive(); String payload = result.getPayload(); - assertTrue("Wrong payload: " + payload, payload.matches(".*payload.*?=a.*")); - assertTrue("Wrong payload: " + payload, payload.matches(".*payload.*?=b.*")); + assertThat(payload.matches(".*payload.*?=a.*")).as("Wrong payload: " + payload).isTrue(); + assertThat(payload.matches(".*payload.*?=b.*")).as("Wrong payload: " + payload).isTrue(); } @SuppressWarnings("unused") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/DefaultMessageAggregatorIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/DefaultMessageAggregatorIntegrationTests.java index b15f168d08..3ae112b396 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/DefaultMessageAggregatorIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/DefaultMessageAggregatorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.aggregator.integration; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashMap; @@ -64,9 +61,9 @@ public class DefaultMessageAggregatorIntegrationTests { this.input.send(new GenericMessage<>(i, headers)); } Object payload = this.output.receive().getPayload(); - assertThat(payload, is(instanceOf(List.class))); - assertTrue(payload + " doesn't contain all of {0,1,2,3,4}", - ((List) payload).containsAll(Arrays.asList(0, 1, 2, 3, 4))); + assertThat(payload).isInstanceOf(List.class); + assertThat(((List) payload).containsAll(Arrays.asList(0, 1, 2, 3, 4))) + .as(payload + " doesn't contain all of {0,1,2,3,4}").isTrue(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/MethodInvokingAggregatorReturningMessageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/MethodInvokingAggregatorReturningMessageTests.java index 785d3b37f6..7718f19950 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/MethodInvokingAggregatorReturningMessageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/MethodInvokingAggregatorReturningMessageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator.integration; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.List; @@ -58,7 +58,7 @@ public class MethodInvokingAggregatorReturningMessageTests { List payload = Collections.singletonList("test"); this.pojoInput.send(MessageBuilder.withPayload(payload).build()); Message result = this.pojoOutput.receive(); - assertFalse(Message.class.isAssignableFrom(result.getPayload().getClass())); + assertThat(Message.class.isAssignableFrom(result.getPayload().getClass())).isFalse(); } @Test @@ -66,7 +66,7 @@ public class MethodInvokingAggregatorReturningMessageTests { List payload = Collections.singletonList("test"); this.defaultInput.send(MessageBuilder.withPayload(payload).build()); Message result = this.defaultOutput.receive(); - assertFalse(Message.class.isAssignableFrom(result.getPayload().getClass())); + assertThat(Message.class.isAssignableFrom(result.getPayload().getClass())).isFalse(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/ResequencerIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/ResequencerIntegrationTests.java index 92694487d6..5ca8845993 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/ResequencerIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/ResequencerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.aggregator.integration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -77,45 +73,45 @@ public class ResequencerIntegrationTests { Message message6 = MessageBuilder.withPayload("6").setCorrelationId("A").setSequenceNumber(6).build(); inputChannel.send(message3); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); inputChannel.send(message1); message1 = outputChannel.receive(0); - assertNotNull(message1); - assertEquals(1, new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()); - assertFalse(message1.getHeaders().containsKey("foo")); + assertThat(message1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()).isEqualTo(1); + assertThat(message1.getHeaders().containsKey("foo")).isFalse(); inputChannel.send(message2); message2 = outputChannel.receive(0); message3 = outputChannel.receive(0); - assertNotNull(message2); - assertNotNull(message3); - assertEquals(2, new IntegrationMessageHeaderAccessor(message2).getSequenceNumber()); - assertTrue(message2.getHeaders().containsKey("foo")); - assertEquals(3, new IntegrationMessageHeaderAccessor(message3).getSequenceNumber()); - assertFalse(message3.getHeaders().containsKey("foo")); + assertThat(message2).isNotNull(); + assertThat(message3).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(message2).getSequenceNumber()).isEqualTo(2); + assertThat(message2.getHeaders().containsKey("foo")).isTrue(); + assertThat(new IntegrationMessageHeaderAccessor(message3).getSequenceNumber()).isEqualTo(3); + assertThat(message3.getHeaders().containsKey("foo")).isFalse(); inputChannel.send(message5); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); inputChannel.send(message6); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); inputChannel.send(message4); message4 = outputChannel.receive(0); message5 = outputChannel.receive(0); message6 = outputChannel.receive(0); - assertNotNull(message4); - assertNotNull(message5); - assertNotNull(message6); - assertEquals(4, new IntegrationMessageHeaderAccessor(message4).getSequenceNumber()); - assertTrue(message4.getHeaders().containsKey("foo")); - assertEquals(5, new IntegrationMessageHeaderAccessor(message5).getSequenceNumber()); - assertFalse(message5.getHeaders().containsKey("foo")); - assertEquals(6, new IntegrationMessageHeaderAccessor(message6).getSequenceNumber()); - assertFalse(message6.getHeaders().containsKey("foo")); + assertThat(message4).isNotNull(); + assertThat(message5).isNotNull(); + assertThat(message6).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(message4).getSequenceNumber()).isEqualTo(4); + assertThat(message4.getHeaders().containsKey("foo")).isTrue(); + assertThat(new IntegrationMessageHeaderAccessor(message5).getSequenceNumber()).isEqualTo(5); + assertThat(message5.getHeaders().containsKey("foo")).isFalse(); + assertThat(new IntegrationMessageHeaderAccessor(message6).getSequenceNumber()).isEqualTo(6); + assertThat(message6.getHeaders().containsKey("foo")).isFalse(); - assertEquals(0, store.getMessageGroup("A").getMessages().size()); + assertThat(store.getMessageGroup("A").getMessages().size()).isEqualTo(0); } @Test @@ -131,13 +127,13 @@ public class ResequencerIntegrationTests { Message message3 = MessageBuilder.withPayload("3").setCorrelationId("A").setSequenceNumber(3).build(); inputChannel.send(message3); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); inputChannel.send(message1); - assertNotNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNotNull(); inputChannel.send(message2); - assertNotNull(outputChannel.receive(0)); - assertNotNull(outputChannel.receive(0)); - assertEquals(0, store.getMessageGroup("A").getMessages().size()); + assertThat(outputChannel.receive(0)).isNotNull(); + assertThat(outputChannel.receive(0)).isNotNull(); + assertThat(store.getMessageGroup("A").getMessages().size()).isEqualTo(0); } @Test @@ -147,8 +143,8 @@ public class ResequencerIntegrationTests { Message message1 = MessageBuilder.withPayload("1").setCorrelationId("A").setSequenceNumber(1).build(); inputChannel.send(message1); message1 = outputChannel.receive(0); - assertNotNull(message1); - assertEquals(1, new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()); + assertThat(message1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()).isEqualTo(1); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregationResendTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregationResendTests.java index 3f73305318..47c800c350 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregationResendTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregationResendTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,11 @@ package org.springframework.integration.aggregator.scenarios; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.ArrayList; import java.util.List; -import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; @@ -99,7 +100,7 @@ public class AggregationResendTests { } while (null != replyMessage); - Assert.assertEquals(1, messageCount); + assertThat(messageCount).isEqualTo(1); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorReplyChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorReplyChannelTests.java index 8ad93418be..36d85c3af1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorReplyChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorReplyChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.aggregator.scenarios; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -73,15 +70,15 @@ public class AggregatorReplyChannelTests { } private void verifyReply(Message message) { - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); this.input.send(message); Message result = this.output.receive(0); - assertNotNull(result); - assertTrue(result.getPayload() instanceof List); + assertThat(result).isNotNull(); + assertThat(result.getPayload() instanceof List).isTrue(); List resultList = (List) result.getPayload(); - assertEquals(2, resultList.size()); - assertTrue(resultList.contains("foo")); - assertTrue(resultList.contains("bar")); + assertThat(resultList.size()).isEqualTo(2); + assertThat(resultList.contains("foo")).isTrue(); + assertThat(resultList.contains("bar")).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java index b19bad68c2..6fc15ecdeb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator.scenarios; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -92,7 +91,8 @@ public class AggregatorWithCustomReleaseStrategyTests { }); } - assertTrue("Sends failed to complete: " + latch.getCount() + " remain", latch.await(120, TimeUnit.SECONDS)); + assertThat(latch.await(120, TimeUnit.SECONDS)).as("Sends failed to complete: " + latch.getCount() + " remain") + .isTrue(); Message message = resultChannel.receive(1000); int counter = 0; @@ -100,7 +100,7 @@ public class AggregatorWithCustomReleaseStrategyTests { counter++; message = resultChannel.receive(1000); } - assertEquals(600, counter); + assertThat(counter).isEqualTo(600); context.close(); } @@ -127,14 +127,15 @@ public class AggregatorWithCustomReleaseStrategyTests { }); } - assertTrue("Sends failed to complete: " + latch.getCount() + " remain", latch.await(60, TimeUnit.SECONDS)); + assertThat(latch.await(60, TimeUnit.SECONDS)).as("Sends failed to complete: " + latch.getCount() + " remain") + .isTrue(); Message message = resultChannel.receive(1000); int counter = 0; while (message != null && ++counter < 7200) { message = resultChannel.receive(1000); } - assertEquals(7200, counter); + assertThat(counter).isEqualTo(7200); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java index 02080affd5..34ca64e440 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/NestedAggregationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator.scenarios; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; @@ -55,16 +54,16 @@ public class NestedAggregationTests { Arrays.asList("foo", "bar", "spam"), Arrays.asList("bar", "foo"))); List result = sendAndReceiveMessage(splitter, 2000, input); - assertNotNull("Expected result and got null", result); - assertEquals("[[foo, bar, spam], [bar, foo]]", result.toString()); + assertThat(result).as("Expected result and got null").isNotNull(); + assertThat(result.toString()).isEqualTo("[[foo, bar, spam], [bar, foo]]"); } @Test public void testAggregatorWithNestedRouter() { Message input = new GenericMessage<>(Arrays.asList("bar", "foo")); List result = sendAndReceiveMessage(router, 2000, input); - assertNotNull("Expected result and got null", result); - assertEquals("[[bar, foo], [bar, foo]]", result.toString()); + assertThat(result).as("Expected result and got null").isNotNull(); + assertThat(result.toString()).isEqualTo("[[bar, foo], [bar, foo]]"); } private List sendAndReceiveMessage(DirectChannel channel, int timeout, Message input) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java index 1db0ebbaa9..a8583f08cf 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aggregator.scenarios; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; @@ -63,14 +61,14 @@ public class PartialSequencesWithGapsTests { in.send(message(6, 6)); in.send(message(2, 6)); in.send(message(1, 6)); - assertThat(new IntegrationMessageHeaderAccessor(received.poll()).getSequenceNumber(), is(1)); - assertThat(new IntegrationMessageHeaderAccessor(received.poll()).getSequenceNumber(), is(2)); + assertThat(new IntegrationMessageHeaderAccessor(received.poll()).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(received.poll()).getSequenceNumber()).isEqualTo(2); received.poll(); received.poll(); in.send(message(5, 6)); - assertThat(received.poll(), is(nullValue())); + assertThat(received.poll()).isNull(); in.send(message(4, 6)); - assertThat(received.poll(), is(nullValue())); + assertThat(received.poll()).isNull(); } private Message message(int sequenceNumber, int sequenceSize) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/AnnotationConfigRegistrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/AnnotationConfigRegistrationTests.java index eac9f552aa..df483a69cc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/AnnotationConfigRegistrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/AnnotationConfigRegistrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.aop; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.junit.runner.RunWith; @@ -53,21 +54,21 @@ public class AnnotationConfigRegistrationTests { @Test // INT-1200 public void verifyInterception() { String name = this.testBean.setName("John", "Doe", 123); - Assert.assertNotNull(name); + assertThat(name).isNotNull(); Message message = this.annotationConfigRegistrationTest.receive(0); - Assert.assertNotNull(message); - Assert.assertEquals("John DoeDoe", message.getPayload()); - Assert.assertEquals(123, message.getHeaders().get("x")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("John DoeDoe"); + assertThat(message.getHeaders().get("x")).isEqualTo(123); } @Test public void defaultChannel() { String result = this.testBean.exclaim("hello"); - Assert.assertNotNull(result); - Assert.assertEquals("HELLO!!!", result); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("HELLO!!!"); Message message = this.defaultChannel.receive(0); - Assert.assertNotNull(message); - Assert.assertEquals("HELLO!!!", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("HELLO!!!"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingAnnotationUsageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingAnnotationUsageTests.java index 7c73581d75..cdcab2db58 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingAnnotationUsageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingAnnotationUsageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aop; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -52,32 +51,32 @@ public class MessagePublishingAnnotationUsageTests { @Test public void headerWithExplicitName() { String name = this.testBean.defaultPayload("John", "Doe"); - assertNotNull(name); + assertThat(name).isNotNull(); Message message = this.channel.receive(1000); - assertNotNull(message); - assertEquals("John Doe", message.getPayload()); - assertEquals("Doe", message.getHeaders().get("last")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("John Doe"); + assertThat(message.getHeaders().get("last")).isEqualTo("Doe"); } @Test public void headerWithImplicitName() { String name = this.testBean.defaultPayloadButExplicitAnnotation("John", "Doe"); - assertNotNull(name); + assertThat(name).isNotNull(); Message message = this.channel.receive(1000); - assertNotNull(message); - assertEquals("John Doe", message.getPayload()); - assertEquals("Doe", message.getHeaders().get("lname")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("John Doe"); + assertThat(message.getHeaders().get("lname")).isEqualTo("Doe"); } @Test public void payloadAsArgument() { String name = this.testBean.argumentAsPayload("John", "Doe"); - assertNotNull(name); - assertEquals("John Doe", name); + assertThat(name).isNotNull(); + assertThat(name).isEqualTo("John Doe"); Message message = this.channel.receive(1000); - assertNotNull(message); - assertEquals("John", message.getPayload()); - assertEquals("Doe", message.getHeaders().get("lname")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("John"); + assertThat(message.getHeaders().get("lname")).isEqualTo("Doe"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java index 4fff07bd91..19ae167079 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aop; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.HashMap; @@ -68,8 +67,8 @@ public class MessagePublishingInterceptorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("test-foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("test-foo"); } @Test @@ -96,10 +95,10 @@ public class MessagePublishingInterceptorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); - assertEquals("foo", message.getHeaders().get("bar")); - assertEquals("oleg", message.getHeaders().get("name")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); + assertThat(message.getHeaders().get("bar")).isEqualTo("foo"); + assertThat(message.getHeaders().get("name")).isEqualTo("oleg"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorUsageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorUsageTests.java index 031a10a597..a7971605ba 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorUsageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorUsageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.aop; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.junit.runner.RunWith; @@ -46,11 +47,11 @@ public class MessagePublishingInterceptorUsageTests { @Test public void demoMessagePublishingInterceptor() { String name = this.testBean.setName("John", "Doe"); - Assert.assertNotNull(name); + assertThat(name).isNotNull(); Message message = this.channel.receive(1000); - Assert.assertNotNull(message); - Assert.assertEquals("John Doe", message.getPayload()); - Assert.assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("John Doe"); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/MethodAnnotationPublisherMetadataSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/MethodAnnotationPublisherMetadataSourceTests.java index 9ae1b0f68f..a0dd2e07c1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/MethodAnnotationPublisherMetadataSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/MethodAnnotationPublisherMetadataSourceTests.java @@ -16,10 +16,7 @@ package org.springframework.integration.aop; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -52,8 +49,8 @@ public class MethodAnnotationPublisherMetadataSourceTests { Method method = getMethod("methodWithChannelAndExplicitReturnAsPayload"); String channelName = source.getChannelName(method); Expression payloadExpression = source.getExpressionForPayload(method); - assertEquals("foo", channelName); - assertEquals("#return", payloadExpression.getExpressionString()); + assertThat(channelName).isEqualTo("foo"); + assertThat(payloadExpression.getExpressionString()).isEqualTo("#return"); } @Test @@ -61,40 +58,40 @@ public class MethodAnnotationPublisherMetadataSourceTests { Method method = getMethod("methodWithChannelAndEmptyPayloadAnnotation"); String channelName = source.getChannelName(method); Expression payloadExpression = source.getExpressionForPayload(method); - assertEquals("foo", channelName); - assertEquals("#return", payloadExpression.getExpressionString()); + assertThat(channelName).isEqualTo("foo"); + assertThat(payloadExpression.getExpressionString()).isEqualTo("#return"); } @Test public void payloadButNoHeaders() { Method method = getMethod("methodWithPayloadAnnotation", String.class, int.class); String expressionString = source.getExpressionForPayload(method).getExpressionString(); - assertEquals("testExpression1", expressionString); + assertThat(expressionString).isEqualTo("testExpression1"); Map headerMap = source.getExpressionsForHeaders(method); - assertNotNull(headerMap); - assertEquals(0, headerMap.size()); + assertThat(headerMap).isNotNull(); + assertThat(headerMap.size()).isEqualTo(0); } @Test public void payloadAndHeaders() { Method method = getMethod("methodWithHeaderAnnotations", String.class, String.class, String.class); String expressionString = source.getExpressionForPayload(method).getExpressionString(); - assertEquals("testExpression2", expressionString); + assertThat(expressionString).isEqualTo("testExpression2"); Map headerMap = source.getExpressionsForHeaders(method); - assertNotNull(headerMap); - assertEquals(2, headerMap.size()); - assertEquals("#args[1]", headerMap.get("foo").getExpressionString()); - assertEquals("#args[2]", headerMap.get("bar").getExpressionString()); + assertThat(headerMap).isNotNull(); + assertThat(headerMap.size()).isEqualTo(2); + assertThat(headerMap.get("foo").getExpressionString()).isEqualTo("#args[1]"); + assertThat(headerMap.get("bar").getExpressionString()).isEqualTo("#args[2]"); } @Test public void expressionsAreConcurrentHashMap() { - assertThat("Expressions should be concurrent to allow startup", - ReflectionTestUtils.getField(source, "channels"), instanceOf(ConcurrentHashMap.class)); - assertThat("Expressions should be concurrent to allow startup", - ReflectionTestUtils.getField(source, "payloadExpressions"), instanceOf(ConcurrentHashMap.class)); - assertThat("Expressions should be concurrent to allow startup", - ReflectionTestUtils.getField(source, "headersExpressions"), instanceOf(ConcurrentHashMap.class)); + assertThat(ReflectionTestUtils.getField(source, "channels")) + .as("Expressions should be concurrent to allow startup").isInstanceOf(ConcurrentHashMap.class); + assertThat(ReflectionTestUtils.getField(source, "payloadExpressions")) + .as("Expressions should be concurrent to allow startup").isInstanceOf(ConcurrentHashMap.class); + assertThat(ReflectionTestUtils.getField(source, "headersExpressions")) + .as("Expressions should be concurrent to allow startup").isInstanceOf(ConcurrentHashMap.class); } @Test @@ -102,8 +99,8 @@ public class MethodAnnotationPublisherMetadataSourceTests { Method method = getMethod("methodWithVoidReturnAndMethodNameAsPayload"); String channelName = source.getChannelName(method); String payloadExpression = source.getExpressionForPayload(method).getExpressionString(); - assertEquals("foo", channelName); - assertEquals("#method", payloadExpression); + assertThat(channelName).isEqualTo("foo"); + assertThat(payloadExpression).isEqualTo("#method"); } @Test(expected = IllegalArgumentException.class) @@ -116,7 +113,7 @@ public class MethodAnnotationPublisherMetadataSourceTests { public void voidReturnAndParameterPayloadAnnotation() { Method method = getMethod("methodWithVoidReturnAndParameterPayloadAnnotation", String.class); String payloadExpression = source.getExpressionForPayload(method).getExpressionString(); - assertEquals("#args[0]", payloadExpression); + assertThat(payloadExpression).isEqualTo("#args[0]"); } @Test(expected = IllegalArgumentException.class) @@ -129,14 +126,14 @@ public class MethodAnnotationPublisherMetadataSourceTests { public void explicitAnnotationAttributeOverride() { Method method = getMethod("methodWithExplicitAnnotationAttributeOverride"); String channelName = source.getChannelName(method); - assertEquals("foo", channelName); + assertThat(channelName).isEqualTo("foo"); } @Test public void explicitAnnotationAttributeOverrideOnDeclaringClass() { Method method = getMethodFromTestClass("methodWithAnnotationOnTheDeclaringClass"); String channelName = source.getChannelName(method); - assertEquals("bar", channelName); + assertThat(channelName).isEqualTo("bar"); } private static Method getMethodFromTestClass(String name, Class... params) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java index 87af422207..d8169414c4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherAnnotationAdvisorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aop; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -60,8 +59,8 @@ public class PublisherAnnotationAdvisorTests { TestVoidBean proxy = (TestVoidBean) pf.getProxy(); proxy.testVoidMethod("foo"); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -74,8 +73,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -88,8 +87,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -102,8 +101,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testMetaChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -116,8 +115,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testMetaChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -130,8 +129,8 @@ public class PublisherAnnotationAdvisorTests { TestVoidBean proxy = (TestVoidBean) pf.getProxy(); proxy.testVoidMethod("foo"); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -144,8 +143,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -158,8 +157,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -172,8 +171,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testMetaChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -186,8 +185,8 @@ public class PublisherAnnotationAdvisorTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test(); Message message = testMetaChannel.receive(0); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } interface TestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherExpressionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherExpressionTests.java index be476963fa..3a6cc645cd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherExpressionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/PublisherExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.aop; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; @@ -74,9 +73,9 @@ public class PublisherExpressionTests { TestBean proxy = (TestBean) pf.getProxy(); proxy.test("123"); Message message = testChannel.receive(0); - assertNotNull(message); - assertEquals("hellofoo", message.getPayload()); - assertEquals("123", message.getHeaders().get("foo")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("hellofoo"); + assertThat(message.getHeaders().get("foo")).isEqualTo("123"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java b/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java index fb4f86e08f..5c1219f940 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java @@ -16,10 +16,7 @@ package org.springframework.integration.bus; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.concurrent.CountDownLatch; @@ -78,7 +75,7 @@ public class ApplicationContextMessageBusTests { context.registerEndpoint("testEndpoint", endpoint); context.refresh(); Message result = targetChannel.receive(10000); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); context.close(); } @@ -92,7 +89,7 @@ public class ApplicationContextMessageBusTests { context.registerChannel("targetChannel", targetChannel); context.refresh(); Message result = targetChannel.receive(10); - assertNull(result); + assertThat(result).isNull(); context.close(); } @@ -105,7 +102,7 @@ public class ApplicationContextMessageBusTests { sourceChannel.send(new GenericMessage<>("test")); PollableChannel targetChannel = (PollableChannel) context.getBean("targetChannel"); Message result = targetChannel.receive(10000); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); context.close(); } @@ -145,7 +142,7 @@ public class ApplicationContextMessageBusTests { Message message1 = outputChannel1.receive(10000); Message message2 = outputChannel2.receive(0); context.close(); - assertTrue("exactly one message should be null", message1 == null ^ message2 == null); + assertThat(message1 == null ^ message2 == null).as("exactly one message should be null").isTrue(); } @Test @@ -183,12 +180,12 @@ public class ApplicationContextMessageBusTests { context.refresh(); inputChannel.send(new GenericMessage("testing")); latch.await(500, TimeUnit.MILLISECONDS); - assertEquals("both handlers should have been invoked", 0, latch.getCount()); + assertThat(latch.getCount()).as("both handlers should have been invoked").isEqualTo(0); Message message1 = outputChannel1.receive(500); Message message2 = outputChannel2.receive(500); context.close(); - assertNotNull("both handlers should have replied to the message", message1); - assertNotNull("both handlers should have replied to the message", message2); + assertThat(message1).as("both handlers should have replied to the message").isNotNull(); + assertThat(message2).as("both handlers should have replied to the message").isNotNull(); } @Test @@ -208,11 +205,11 @@ public class ApplicationContextMessageBusTests { latch.await(2000, TimeUnit.MILLISECONDS); Message message = errorChannel.receive(5000); context.close(); - assertNull(outputChannel.receive(100)); - assertNotNull("message should not be null", message); - assertTrue(message instanceof ErrorMessage); + assertThat(outputChannel.receive(100)).isNull(); + assertThat(message).as("message should not be null").isNotNull(); + assertThat(message instanceof ErrorMessage).isTrue(); Throwable exception = ((ErrorMessage) message).getPayload(); - assertEquals("intentional test failure", exception.getCause().getMessage()); + assertThat(exception.getCause().getMessage()).isEqualTo("intentional test failure"); } @Test @@ -235,7 +232,7 @@ public class ApplicationContextMessageBusTests { context.refresh(); errorChannel.send(new ErrorMessage(new RuntimeException("test-exception"))); latch.await(1000, TimeUnit.MILLISECONDS); - assertEquals("handler should have received error message", 0, latch.getCount()); + assertThat(latch.getCount()).as("handler should have received error message").isEqualTo(0); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java index d7a15119cd..271fe76f2d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java @@ -16,7 +16,7 @@ package org.springframework.integration.bus; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; @@ -73,7 +73,7 @@ public class DirectChannelSubscriptionTests { context.refresh(); this.sourceChannel.send(new GenericMessage<>("foo")); Message response = this.targetChannel.receive(); - assertEquals("foo!", response.getPayload()); + assertThat(response.getPayload()).isEqualTo("foo!"); } @Test @@ -86,7 +86,7 @@ public class DirectChannelSubscriptionTests { this.context.refresh(); this.sourceChannel.send(new GenericMessage<>("foo")); Message response = this.targetChannel.receive(); - assertEquals("foo-from-annotated-endpoint", response.getPayload()); + assertThat(response.getPayload()).isEqualTo("foo-from-annotated-endpoint"); } @Test(expected = MessagingException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/CGLibProxyChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/CGLibProxyChannelTests.java index 1ce128ab7f..552f62c0c2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/CGLibProxyChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/CGLibProxyChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; @@ -61,23 +60,23 @@ public class CGLibProxyChannelTests { @Test public void testProxyDirect() { - assertTrue(AopUtils.isCglibProxy(this.directChannel)); + assertThat(AopUtils.isCglibProxy(this.directChannel)).isTrue(); final AtomicReference> message = new AtomicReference<>(); this.directChannel.subscribe(m -> message.set(m)); this.directChannel.send(new GenericMessage<>("foo")); - assertNotNull(message.get()); + assertThat(message.get()).isNotNull(); } @Test public void testProxyQueue() { - assertTrue(AopUtils.isCglibProxy(this.queueChannel)); + assertThat(AopUtils.isCglibProxy(this.queueChannel)).isTrue(); this.queueChannel.send(new GenericMessage<>("foo")); - assertNotNull(this.queueChannel.receive(0)); + assertThat(this.queueChannel.receive(0)).isNotNull(); } @Test public void testProxyExecutor() throws Exception { - assertTrue(AopUtils.isCglibProxy(this.executorChannel)); + assertThat(AopUtils.isCglibProxy(this.executorChannel)).isTrue(); final AtomicReference> message = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); this.executorChannel.subscribe(m -> { @@ -85,13 +84,13 @@ public class CGLibProxyChannelTests { latch.countDown(); }); this.executorChannel.send(new GenericMessage<>("foo")); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertNotNull(message.get()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(message.get()).isNotNull(); } @Test public void testProxyPubSubWithExec() throws Exception { - assertTrue(AopUtils.isCglibProxy(this.publishSubscribeChannel)); + assertThat(AopUtils.isCglibProxy(this.publishSubscribeChannel)).isTrue(); final AtomicReference> message = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); this.publishSubscribeChannel.subscribe(m -> { @@ -99,8 +98,8 @@ public class CGLibProxyChannelTests { latch.countDown(); }); this.publishSubscribeChannel.send(new GenericMessage<>("foo")); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertNotNull(message.get()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(message.get()).isNotNull(); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java index 44713eeafd..0714da9fa4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -40,8 +38,8 @@ public class ChannelPurgerTests { channel.send(new GenericMessage("test3")); ChannelPurger purger = new ChannelPurger(channel); List> purgedMessages = purger.purge(); - assertEquals(3, purgedMessages.size()); - assertNull(channel.receive(0)); + assertThat(purgedMessages.size()).isEqualTo(3); + assertThat(channel.receive(0)).isNull(); } @Test @@ -52,8 +50,8 @@ public class ChannelPurgerTests { channel.send(new GenericMessage("test3")); ChannelPurger purger = new ChannelPurger(message -> false, channel); List> purgedMessages = purger.purge(); - assertEquals(3, purgedMessages.size()); - assertNull(channel.receive(0)); + assertThat(purgedMessages.size()).isEqualTo(3); + assertThat(channel.receive(0)).isNull(); } @Test @@ -64,10 +62,10 @@ public class ChannelPurgerTests { channel.send(new GenericMessage("test3")); ChannelPurger purger = new ChannelPurger(message -> true, channel); List> purgedMessages = purger.purge(); - assertEquals(0, purgedMessages.size()); - assertNotNull(channel.receive(0)); - assertNotNull(channel.receive(0)); - assertNotNull(channel.receive(0)); + assertThat(purgedMessages.size()).isEqualTo(0); + assertThat(channel.receive(0)).isNotNull(); + assertThat(channel.receive(0)).isNotNull(); + assertThat(channel.receive(0)).isNotNull(); } @Test @@ -78,11 +76,11 @@ public class ChannelPurgerTests { channel.send(new GenericMessage("test3")); ChannelPurger purger = new ChannelPurger(message -> (message.getPayload().equals("test2")), channel); List> purgedMessages = purger.purge(); - assertEquals(2, purgedMessages.size()); + assertThat(purgedMessages.size()).isEqualTo(2); Message message = channel.receive(0); - assertNotNull(message); - assertEquals("test2", message.getPayload()); - assertNull(channel.receive(0)); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("test2"); + assertThat(channel.receive(0)).isNull(); } @Test @@ -95,9 +93,9 @@ public class ChannelPurgerTests { channel2.send(new GenericMessage("test2")); ChannelPurger purger = new ChannelPurger(channel1, channel2); List> purgedMessages = purger.purge(); - assertEquals(4, purgedMessages.size()); - assertNull(channel1.receive(0)); - assertNull(channel2.receive(0)); + assertThat(purgedMessages.size()).isEqualTo(4); + assertThat(channel1.receive(0)).isNull(); + assertThat(channel2.receive(0)).isNull(); } @Test @@ -112,15 +110,15 @@ public class ChannelPurgerTests { channel2.send(new GenericMessage("test3")); ChannelPurger purger = new ChannelPurger(message -> (message.getPayload().equals("test2")), channel1, channel2); List> purgedMessages = purger.purge(); - assertEquals(4, purgedMessages.size()); + assertThat(purgedMessages.size()).isEqualTo(4); Message message1 = channel1.receive(0); - assertNotNull(message1); - assertEquals("test2", message1.getPayload()); - assertNull(channel1.receive(0)); + assertThat(message1).isNotNull(); + assertThat(message1.getPayload()).isEqualTo("test2"); + assertThat(channel1.receive(0)).isNull(); Message message2 = channel2.receive(0); - assertNotNull(message2); - assertEquals("test2", message2.getPayload()); - assertNull(channel2.receive(0)); + assertThat(message2).isNotNull(); + assertThat(message2.getPayload()).isEqualTo("test2"); + assertThat(channel2.receive(0)).isNull(); } @Test @@ -133,11 +131,11 @@ public class ChannelPurgerTests { channel2.send(new GenericMessage("test2")); ChannelPurger purger = new ChannelPurger(message -> true, channel1, channel2); List> purgedMessages = purger.purge(); - assertEquals(0, purgedMessages.size()); - assertNotNull(channel1.receive(0)); - assertNotNull(channel1.receive(0)); - assertNotNull(channel2.receive(0)); - assertNotNull(channel2.receive(0)); + assertThat(purgedMessages.size()).isEqualTo(0); + assertThat(channel1.receive(0)).isNotNull(); + assertThat(channel1.receive(0)).isNotNull(); + assertThat(channel2.receive(0)).isNotNull(); + assertThat(channel2.receive(0)).isNotNull(); } @Test(expected = IllegalArgumentException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java index be791c0d73..0a4787bd51 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.channel; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Date; @@ -63,7 +58,7 @@ public class DatatypeChannelTests { @Test public void supportedType() { MessageChannel channel = createChannel(String.class); - assertTrue(channel.send(new GenericMessage("test"))); + assertThat(channel.send(new GenericMessage("test"))).isTrue(); } @Test(expected = MessageDeliveryException.class) @@ -79,7 +74,7 @@ public class DatatypeChannelTests { DefaultDatatypeChannelMessageConverter converter = new DefaultDatatypeChannelMessageConverter(); converter.setConversionService(conversionService); channel.setMessageConverter(converter); - assertTrue(channel.send(new GenericMessage("123"))); + assertThat(channel.send(new GenericMessage("123"))).isTrue(); } @Test(expected = MessageDeliveryException.class) @@ -89,7 +84,7 @@ public class DatatypeChannelTests { DefaultDatatypeChannelMessageConverter converter = new DefaultDatatypeChannelMessageConverter(); converter.setConversionService(conversionService); channel.setMessageConverter(converter); - assertTrue(channel.send(new GenericMessage(Boolean.TRUE))); + assertThat(channel.send(new GenericMessage(Boolean.TRUE))).isTrue(); } @Test @@ -105,8 +100,8 @@ public class DatatypeChannelTests { DefaultDatatypeChannelMessageConverter converter = new DefaultDatatypeChannelMessageConverter(); converter.setConversionService(conversionService); channel.setMessageConverter(converter); - assertTrue(channel.send(new GenericMessage(Boolean.TRUE))); - assertEquals(1, channel.receive().getPayload()); + assertThat(channel.send(new GenericMessage(Boolean.TRUE))).isTrue(); + assertThat(channel.receive().getPayload()).isEqualTo(1); } @Test @@ -135,10 +130,10 @@ public class DatatypeChannelTests { context.refresh(); QueueChannel channel = context.getBean("testChannel", QueueChannel.class); - assertSame(context.getBean(ConversionService.class), - TestUtils.getPropertyValue(channel, "messageConverter.conversionService")); - assertTrue(channel.send(new GenericMessage(Boolean.TRUE))); - assertEquals(1, channel.receive().getPayload()); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter.conversionService")) + .isSameAs(context.getBean(ConversionService.class)); + assertThat(channel.send(new GenericMessage(Boolean.TRUE))).isTrue(); + assertThat(channel.receive().getPayload()).isEqualTo(1); context.close(); } @@ -174,16 +169,16 @@ public class DatatypeChannelTests { context.refresh(); QueueChannel channel = context.getBean("testChannel", QueueChannel.class); - assertTrue(channel.send(new GenericMessage(Boolean.TRUE))); - assertEquals(99, channel.receive().getPayload()); + assertThat(channel.send(new GenericMessage(Boolean.TRUE))).isTrue(); + assertThat(channel.receive().getPayload()).isEqualTo(99); context.close(); } @Test public void multipleTypes() { MessageChannel channel = createChannel(String.class, Integer.class); - assertTrue(channel.send(new GenericMessage("test1"))); - assertTrue(channel.send(new GenericMessage(2))); + assertThat(channel.send(new GenericMessage("test1"))).isTrue(); + assertThat(channel.send(new GenericMessage(2))).isTrue(); Exception exception = null; try { channel.send(new GenericMessage(new Date())); @@ -191,13 +186,13 @@ public class DatatypeChannelTests { catch (MessageDeliveryException e) { exception = e; } - assertNotNull(exception); + assertThat(exception).isNotNull(); } @Test public void subclassOfAcceptedType() { MessageChannel channel = createChannel(RuntimeException.class); - assertTrue(channel.send(new ErrorMessage(new MessagingException("test")))); + assertThat(channel.send(new ErrorMessage(new MessagingException("test")))).isTrue(); } @Test(expected = MessageDeliveryException.class) @@ -215,12 +210,12 @@ public class DatatypeChannelTests { DefaultDatatypeChannelMessageConverter converter = new DefaultDatatypeChannelMessageConverter(); converter.setConversionService(conversionService); channel.setMessageConverter(converter); - assertTrue(channel.send(new GenericMessage("foo"))); + assertThat(channel.send(new GenericMessage("foo"))).isTrue(); Message out = channel.receive(0); - assertThat(out.getPayload(), instanceOf(Bar.class)); - assertTrue(channel.send(new GenericMessage(42))); + assertThat(out.getPayload()).isInstanceOf(Bar.class); + assertThat(channel.send(new GenericMessage(42))).isTrue(); out = channel.receive(0); - assertThat(out.getPayload(), instanceOf(Baz.class)); + assertThat(out.getPayload()).isInstanceOf(Baz.class); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelParserTests.java index 86ef0e17a4..7b60bee83a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -37,9 +36,10 @@ public class DirectChannelParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "directChannelParserTests.xml", DirectChannelParserTests.class); Object channel = context.getBean("channel"); - assertEquals(DirectChannel.class, channel.getClass()); + assertThat(channel.getClass()).isEqualTo(DirectChannel.class); DirectFieldAccessor dcAccessor = new DirectFieldAccessor(((DirectChannel) channel).getDispatcher()); - assertTrue(dcAccessor.getPropertyValue("loadBalancingStrategy") instanceof RoundRobinLoadBalancingStrategy); + assertThat(dcAccessor.getPropertyValue("loadBalancingStrategy") instanceof RoundRobinLoadBalancingStrategy) + .isTrue(); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java index cd745eb0d4..eb7992a87a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.channel; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -64,19 +60,19 @@ public class DirectChannelTests { ThreadNameExtractingTestTarget target = new ThreadNameExtractingTestTarget(); channel.subscribe(target); GenericMessage message = new GenericMessage("test"); - assertTrue(channel.send(message)); - assertEquals(Thread.currentThread().getName(), target.threadName); + assertThat(channel.send(message)).isTrue(); + assertThat(target.threadName).isEqualTo(Thread.currentThread().getName()); DirectFieldAccessor channelAccessor = new DirectFieldAccessor(channel); UnicastingDispatcher dispatcher = (UnicastingDispatcher) channelAccessor.getPropertyValue("dispatcher"); DirectFieldAccessor dispatcherAccessor = new DirectFieldAccessor(dispatcher); Object loadBalancingStrategy = dispatcherAccessor.getPropertyValue("loadBalancingStrategy"); - assertTrue(loadBalancingStrategy instanceof RoundRobinLoadBalancingStrategy); + assertThat(loadBalancingStrategy instanceof RoundRobinLoadBalancingStrategy).isTrue(); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(logger, times(2)).debug(captor.capture()); List logs = captor.getAllValues(); - assertEquals(2, logs.size()); - assertThat(logs.get(0), startsWith("preSend")); - assertThat(logs.get(1), startsWith("postSend")); + assertThat(logs.size()).isEqualTo(2); + assertThat(logs.get(0)).startsWith("preSend"); + assertThat(logs.get(1)).startsWith("postSend"); } @Test @@ -94,7 +90,7 @@ public class DirectChannelTests { final AtomicInteger count = new AtomicInteger(); channel.subscribe(message -> count.incrementAndGet()); GenericMessage message = new GenericMessage("test"); - assertTrue(channel.send(message)); + assertThat(channel.send(message)).isTrue(); for (int i = 0; i < 10000000; i++) { channel.send(message); } @@ -115,12 +111,12 @@ public class DirectChannelTests { channel.subscribe(message -> count1.incrementAndGet()); channel.subscribe(message -> count2.getAndIncrement()); GenericMessage message = new GenericMessage("test"); - assertTrue(channel.send(message)); + assertThat(channel.send(message)).isTrue(); for (int i = 0; i < 10000000; i++) { channel.send(message); } - assertEquals(5000001, count1.get()); - assertEquals(5000000, count2.get()); + assertThat(count1.get()).isEqualTo(5000001); + assertThat(count2.get()).isEqualTo(5000000); } @Test @@ -135,7 +131,7 @@ public class DirectChannelTests { final AtomicInteger count = new AtomicInteger(); FixedSubscriberChannel channel = new FixedSubscriberChannel(message -> count.incrementAndGet()); GenericMessage message = new GenericMessage("test"); - assertTrue(channel.send(message)); + assertThat(channel.send(message)).isTrue(); for (int i = 0; i < 100000000; i++) { channel.send(message, 0); } @@ -150,7 +146,7 @@ public class DirectChannelTests { final GenericMessage message = new GenericMessage("test"); new Thread((Runnable) () -> channel.send(message), "test-thread").start(); latch.await(1000, TimeUnit.MILLISECONDS); - assertEquals("test-thread", target.threadName); + assertThat(target.threadName).isEqualTo("test-thread"); } @Test // See INT-2434 @@ -166,40 +162,43 @@ public class DirectChannelTests { Method method = ReflectionUtils.findMethod(ClassPathXmlApplicationContext.class, "obtainFreshBeanFactory"); method.setAccessible(true); method.invoke(context); - assertFalse(context.containsBean("channelA")); - assertFalse(context.containsBean("channelB")); - assertTrue(context.containsBean("channelC")); - assertTrue(context.containsBean("channelD")); + assertThat(context.containsBean("channelA")).isFalse(); + assertThat(context.containsBean("channelB")).isFalse(); + assertThat(context.containsBean("channelC")).isTrue(); + assertThat(context.containsBean("channelD")).isTrue(); context.refresh(); PublishSubscribeChannel channelEarly = context.getBean("channelEarly", PublishSubscribeChannel.class); - assertTrue(context.containsBean("channelA")); - assertTrue(context.containsBean("channelB")); - assertTrue(context.containsBean("channelC")); - assertTrue(context.containsBean("channelD")); + assertThat(context.containsBean("channelA")).isTrue(); + assertThat(context.containsBean("channelB")).isTrue(); + assertThat(context.containsBean("channelC")).isTrue(); + assertThat(context.containsBean("channelD")).isTrue(); EventDrivenConsumer consumerA = context.getBean("serviceA", EventDrivenConsumer.class); - assertEquals(context.getBean("channelA"), TestUtils.getPropertyValue(consumerA, "inputChannel")); - assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerA, "handler.outputChannel")); + assertThat(TestUtils.getPropertyValue(consumerA, "inputChannel")).isEqualTo(context.getBean("channelA")); + assertThat(TestUtils.getPropertyValue(consumerA, "handler.outputChannel")) + .isEqualTo(context.getBean("channelB")); EventDrivenConsumer consumerB = context.getBean("serviceB", EventDrivenConsumer.class); - assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerB, "inputChannel")); - assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerB, "handler.outputChannel")); + assertThat(TestUtils.getPropertyValue(consumerB, "inputChannel")).isEqualTo(context.getBean("channelB")); + assertThat(TestUtils.getPropertyValue(consumerB, "handler.outputChannel")) + .isEqualTo(context.getBean("channelC")); EventDrivenConsumer consumerC = context.getBean("serviceC", EventDrivenConsumer.class); - assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerC, "inputChannel")); - assertEquals(context.getBean("channelD"), TestUtils.getPropertyValue(consumerC, "handler.outputChannel")); + assertThat(TestUtils.getPropertyValue(consumerC, "inputChannel")).isEqualTo(context.getBean("channelC")); + assertThat(TestUtils.getPropertyValue(consumerC, "handler.outputChannel")) + .isEqualTo(context.getBean("channelD")); EventDrivenConsumer consumerD = context.getBean("serviceD", EventDrivenConsumer.class); - assertEquals(parentChannelA, TestUtils.getPropertyValue(consumerD, "inputChannel")); - assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerD, "handler.outputChannel")); + assertThat(TestUtils.getPropertyValue(consumerD, "inputChannel")).isEqualTo(parentChannelA); + assertThat(TestUtils.getPropertyValue(consumerD, "handler.outputChannel")).isEqualTo(parentChannelB); EventDrivenConsumer consumerE = context.getBean("serviceE", EventDrivenConsumer.class); - assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerE, "inputChannel")); + assertThat(TestUtils.getPropertyValue(consumerE, "inputChannel")).isEqualTo(parentChannelB); EventDrivenConsumer consumerF = context.getBean("serviceF", EventDrivenConsumer.class); - assertEquals(channelEarly, TestUtils.getPropertyValue(consumerF, "inputChannel")); + assertThat(TestUtils.getPropertyValue(consumerF, "inputChannel")).isEqualTo(channelEarly); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatcherHasNoSubscribersTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatcherHasNoSubscribersTests.java index 73fe15d375..edb0e23ba2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatcherHasNoSubscribersTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatcherHasNoSubscribersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.channel; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.Before; import org.junit.Test; @@ -63,8 +62,8 @@ public class DispatcherHasNoSubscribersTests { fail("Exception expected"); } catch (MessagingException e) { - assertThat(e.getMessage(), - containsString("Dispatcher has no subscribers for channel 'foo.noSubscribersChannel'.")); + assertThat(e.getMessage()) + .contains("Dispatcher has no subscribers for channel 'foo.noSubscribersChannel'."); } } @@ -75,8 +74,8 @@ public class DispatcherHasNoSubscribersTests { fail("Exception expected"); } catch (MessagingException e) { - assertThat(e.getMessage(), - containsString("Dispatcher has no subscribers for channel 'foo.noSubscribersChannel'.")); + assertThat(e.getMessage()) + .contains("Dispatcher has no subscribers for channel 'foo.noSubscribersChannel'."); } } @@ -89,8 +88,7 @@ public class DispatcherHasNoSubscribersTests { fail("Exception expected"); } catch (MessagingException e) { - assertThat(e.getMessage(), - containsString("Dispatcher has no subscribers for channel 'bar'.")); + assertThat(e.getMessage()).contains("Dispatcher has no subscribers for channel 'bar'."); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java index 16066e0cba..c56a0c325a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -76,11 +74,11 @@ public class DispatchingChannelErrorHandlingTests { channel.send(message); this.waitForLatch(10000); Message errorMessage = resultHandler.lastMessage; - assertEquals(MessagingException.class, errorMessage.getPayload().getClass()); + assertThat(errorMessage.getPayload().getClass()).isEqualTo(MessagingException.class); MessagingException exceptionPayload = (MessagingException) errorMessage.getPayload(); - assertEquals(UnsupportedOperationException.class, exceptionPayload.getCause().getClass()); - assertSame(message, exceptionPayload.getFailedMessage()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(exceptionPayload.getCause().getClass()).isEqualTo(UnsupportedOperationException.class); + assertThat(exceptionPayload.getFailedMessage()).isSameAs(message); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -105,11 +103,11 @@ public class DispatchingChannelErrorHandlingTests { channel.send(message); this.waitForLatch(10000); Message errorMessage = resultHandler.lastMessage; - assertEquals(MessagingException.class, errorMessage.getPayload().getClass()); + assertThat(errorMessage.getPayload().getClass()).isEqualTo(MessagingException.class); MessagingException exceptionPayload = (MessagingException) errorMessage.getPayload(); - assertEquals(UnsupportedOperationException.class, exceptionPayload.getCause().getClass()); - assertSame(message, exceptionPayload.getFailedMessage()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(exceptionPayload.getCause().getClass()).isEqualTo(UnsupportedOperationException.class); + assertThat(exceptionPayload.getFailedMessage()).isSameAs(message); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java index 975570eba9..1e8836adb8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,15 +16,8 @@ package org.springframework.integration.channel; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -65,12 +58,12 @@ public class ExecutorChannelTests { CountDownLatch latch = new CountDownLatch(1); TestHandler handler = new TestHandler(latch); channel.subscribe(handler); - channel.send(new GenericMessage("test")); + channel.send(new GenericMessage<>("test")); latch.await(1000, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); - assertNotNull(handler.thread); - assertFalse(Thread.currentThread().equals(handler.thread)); - assertEquals("test-1", handler.thread.getName()); + assertThat(latch.getCount()).isEqualTo(0); + assertThat(handler.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler.thread)).isFalse(); + assertThat(handler.thread.getName()).isEqualTo("test-1"); } @Test @@ -89,22 +82,22 @@ public class ExecutorChannelTests { channel.subscribe(handler2); channel.subscribe(handler3); for (int i = 0; i < numberOfMessages; i++) { - channel.send(new GenericMessage("test-" + i)); + channel.send(new GenericMessage<>("test-" + i)); } latch.await(3000, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); - assertNotNull(handler1.thread); - assertFalse(Thread.currentThread().equals(handler1.thread)); - assertTrue(handler1.thread.getName().startsWith("test-")); - assertNotNull(handler2.thread); - assertFalse(Thread.currentThread().equals(handler2.thread)); - assertTrue(handler2.thread.getName().startsWith("test-")); - assertNotNull(handler3.thread); - assertFalse(Thread.currentThread().equals(handler3.thread)); - assertTrue(handler3.thread.getName().startsWith("test-")); - assertEquals(4, handler1.count.get()); - assertEquals(4, handler2.count.get()); - assertEquals(3, handler3.count.get()); + assertThat(latch.getCount()).isEqualTo(0); + assertThat(handler1.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler1.thread)).isFalse(); + assertThat(handler1.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler2.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler2.thread)).isFalse(); + assertThat(handler2.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler3.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler3.thread)).isFalse(); + assertThat(handler3.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler1.count.get()).isEqualTo(4); + assertThat(handler2.count.get()).isEqualTo(4); + assertThat(handler3.count.get()).isEqualTo(3); exec.shutdownNow(); } @@ -125,22 +118,22 @@ public class ExecutorChannelTests { channel.subscribe(handler3); handler2.shouldFail = true; for (int i = 0; i < numberOfMessages; i++) { - channel.send(new GenericMessage("test-" + i)); + channel.send(new GenericMessage<>("test-" + i)); } latch.await(3000, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); - assertNotNull(handler1.thread); - assertFalse(Thread.currentThread().equals(handler1.thread)); - assertTrue(handler1.thread.getName().startsWith("test-")); - assertNotNull(handler2.thread); - assertFalse(Thread.currentThread().equals(handler2.thread)); - assertTrue(handler2.thread.getName().startsWith("test-")); - assertNotNull(handler3.thread); - assertFalse(Thread.currentThread().equals(handler3.thread)); - assertTrue(handler3.thread.getName().startsWith("test-")); - assertEquals(0, handler2.count.get()); - assertEquals(4, handler1.count.get()); - assertEquals(7, handler3.count.get()); + assertThat(latch.getCount()).isEqualTo(0); + assertThat(handler1.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler1.thread)).isFalse(); + assertThat(handler1.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler2.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler2.thread)).isFalse(); + assertThat(handler2.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler3.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler3.thread)).isFalse(); + assertThat(handler3.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler2.count.get()).isEqualTo(0); + assertThat(handler1.count.get()).isEqualTo(4); + assertThat(handler3.count.get()).isEqualTo(7); exec.shutdownNow(); } @@ -160,20 +153,20 @@ public class ExecutorChannelTests { channel.subscribe(handler3); handler1.shouldFail = true; for (int i = 0; i < numberOfMessages; i++) { - channel.send(new GenericMessage("test-" + i)); + channel.send(new GenericMessage<>("test-" + i)); } latch.await(3000, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); - assertNotNull(handler1.thread); - assertFalse(Thread.currentThread().equals(handler1.thread)); - assertTrue(handler1.thread.getName().startsWith("test-")); - assertNotNull(handler2.thread); - assertFalse(Thread.currentThread().equals(handler2.thread)); - assertTrue(handler2.thread.getName().startsWith("test-")); - assertNull(handler3.thread); - assertEquals(0, handler1.count.get()); - assertEquals(0, handler3.count.get()); - assertEquals(numberOfMessages, handler2.count.get()); + assertThat(latch.getCount()).isEqualTo(0); + assertThat(handler1.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler1.thread)).isFalse(); + assertThat(handler1.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler2.thread).isNotNull(); + assertThat(Thread.currentThread().equals(handler2.thread)).isFalse(); + assertThat(handler2.thread.getName().startsWith("test-")).isTrue(); + assertThat(handler3.thread).isNull(); + assertThat(handler1.count.get()).isEqualTo(0); + assertThat(handler3.count.get()).isEqualTo(0); + assertThat(handler2.count.get()).isEqualTo(numberOfMessages); exec.shutdownNow(); } @@ -191,8 +184,8 @@ public class ExecutorChannelTests { channel.subscribe(handler); channel.send(new GenericMessage("foo")); verify(handler).handleMessage(expected); - assertEquals(1, interceptor.getCounter().get()); - assertTrue(interceptor.wasAfterHandledInvoked()); + assertThat(interceptor.getCounter().get()).isEqualTo(1); + assertThat(interceptor.wasAfterHandledInvoked()).isTrue(); } @Test @@ -201,7 +194,7 @@ public class ExecutorChannelTests { channel.setBeanFactory(mock(BeanFactory.class)); channel.afterPropertiesSet(); - Message message = new GenericMessage("foo"); + Message message = new GenericMessage<>("foo"); MessageHandler handler = mock(MessageHandler.class); IllegalStateException expected = new IllegalStateException("Fake exception"); @@ -213,25 +206,26 @@ public class ExecutorChannelTests { channel.send(message); } catch (MessageDeliveryException actual) { - assertSame(expected, actual.getCause()); + assertThat(actual.getCause()).isSameAs(expected); } verify(handler).handleMessage(message); - assertEquals(1, interceptor.getCounter().get()); - assertTrue(interceptor.wasAfterHandledInvoked()); + assertThat(interceptor.getCounter().get()).isEqualTo(1); + assertThat(interceptor.wasAfterHandledInvoked()).isTrue(); } @Test public void testEarlySubscribe() { ExecutorChannel channel = new ExecutorChannel(mock(Executor.class)); try { - channel.subscribe(m -> { }); + channel.subscribe(m -> { + }); channel.setBeanFactory(mock(BeanFactory.class)); channel.afterPropertiesSet(); fail("expected Exception"); } catch (IllegalStateException e) { - assertThat(e.getMessage(), equalTo("You cannot subscribe() until the channel " - + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition")); + assertThat(e.getMessage()).isEqualTo("You cannot subscribe() until the channel " + + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition"); } } @@ -259,6 +253,7 @@ public class ExecutorChannelTests { this.count.incrementAndGet(); this.latch.countDown(); } + } private static class BeforeHandleInterceptor implements ExecutorChannelInterceptor { @@ -287,14 +282,15 @@ public class ExecutorChannelTests { @Override public Message beforeHandle(Message message, MessageChannel channel, MessageHandler handler) { - assertNotNull(message); + assertThat(message).isNotNull(); this.counter.incrementAndGet(); return (this.messageToReturn != null ? this.messageToReturn : message); } @Override public void afterMessageHandled(Message message, MessageChannel channel, MessageHandler handler, - Exception ex) { + Exception ex) { + this.afterHandledInvoked = true; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/FixedSubscriberChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/FixedSubscriberChannelTests.java index 5eb9a9abf0..61e82acb4b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/FixedSubscriberChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/FixedSubscriberChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,12 +16,9 @@ package org.springframework.integration.channel; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,8 +54,8 @@ public class FixedSubscriberChannelTests { public void testHappyDay() { this.in.send(new GenericMessage("foo")); Message out = this.out.receive(0); - assertEquals("FOO", out.getPayload()); - assertThat(this.in, instanceOf(FixedSubscriberChannel.class)); + assertThat(out.getPayload()).isEqualTo("FOO"); + assertThat(this.in).isInstanceOf(FixedSubscriberChannel.class); } @Test @@ -70,10 +67,10 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(BeanCreationException.class)); - assertThat(e.getCause(), instanceOf(BeanInstantiationException.class)); - assertThat(e.getCause().getCause(), instanceOf(IllegalArgumentException.class)); - assertThat(e.getCause().getCause().getMessage(), Matchers.containsString("Cannot instantiate a")); + assertThat(e).isInstanceOf(BeanCreationException.class); + assertThat(e.getCause()).isInstanceOf(BeanInstantiationException.class); + assertThat(e.getCause().getCause()).isInstanceOf(IllegalArgumentException.class); + assertThat(e.getCause().getCause().getMessage()).contains("Cannot instantiate a"); } if (context != null) { context.close(); @@ -89,8 +86,8 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(BeanDefinitionParsingException.class)); - assertThat(e.getMessage(), Matchers.containsString("Only one subscriber is allowed for a FixedSubscriberChannel.")); + assertThat(e).isInstanceOf(BeanDefinitionParsingException.class); + assertThat(e.getMessage()).contains("Only one subscriber is allowed for a FixedSubscriberChannel."); } if (context != null) { context.close(); @@ -106,8 +103,8 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(IllegalArgumentException.class)); - assertThat(e.getMessage(), Matchers.containsString("Only one subscriber is allowed for a FixedSubscriberChannel.")); + assertThat(e).isInstanceOf(IllegalArgumentException.class); + assertThat(e.getMessage()).contains("Only one subscriber is allowed for a FixedSubscriberChannel."); } if (context != null) { context.close(); @@ -123,8 +120,8 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(BeanDefinitionParsingException.class)); - assertThat(e.getMessage(), Matchers.containsString("Cannot have interceptors when 'fixed-subscriber=\"true\"'")); + assertThat(e).isInstanceOf(BeanDefinitionParsingException.class); + assertThat(e.getMessage()).contains("Cannot have interceptors when 'fixed-subscriber=\"true\"'"); } if (context != null) { context.close(); @@ -140,8 +137,8 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(BeanDefinitionParsingException.class)); - assertThat(e.getMessage(), Matchers.containsString("Cannot have 'datatype' when 'fixed-subscriber=\"true\"'")); + assertThat(e).isInstanceOf(BeanDefinitionParsingException.class); + assertThat(e.getMessage()).contains("Cannot have 'datatype' when 'fixed-subscriber=\"true\"'"); } if (context != null) { context.close(); @@ -157,8 +154,8 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(BeanDefinitionParsingException.class)); - assertThat(e.getMessage(), Matchers.containsString("Cannot have 'message-converter' when 'fixed-subscriber=\"true\"'")); + assertThat(e).isInstanceOf(BeanDefinitionParsingException.class); + assertThat(e.getMessage()).contains("Cannot have 'message-converter' when 'fixed-subscriber=\"true\"'"); } if (context != null) { context.close(); @@ -174,8 +171,9 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(BeanDefinitionParsingException.class)); - assertThat(e.getMessage(), Matchers.containsString("The 'fixed-subscriber' attribute is not allowed when a child element is present.")); + assertThat(e).isInstanceOf(BeanDefinitionParsingException.class); + assertThat(e.getMessage()) + .contains("The 'fixed-subscriber' attribute is not allowed when a child element is present."); } if (context != null) { context.close(); @@ -191,8 +189,9 @@ public class FixedSubscriberChannelTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e, instanceOf(BeanDefinitionParsingException.class)); - assertThat(e.getMessage(), Matchers.containsString("The 'fixed-subscriber' attribute is not allowed when a child element is present.")); + assertThat(e).isInstanceOf(BeanDefinitionParsingException.class); + assertThat(e.getMessage()) + .contains("The 'fixed-subscriber' attribute is not allowed when a child element is present."); } if (context != null) { context.close(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java index 02bc0d4e6c..99734095d6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -158,12 +157,12 @@ public class MixedDispatcherConfigurationScenarioTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); - assertTrue("not all messages were accepted", failed.get()); + assertThat(failed.get()).as("not all messages were accepted").isTrue(); verify(handlerA, times(TOTAL_EXECUTIONS)).handleMessage(message); verify(handlerB, times(0)).handleMessage(message); verify(exceptionRegistry, times(TOTAL_EXECUTIONS)).add(any(Exception.class)); @@ -199,12 +198,12 @@ public class MixedDispatcherConfigurationScenarioTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); - assertTrue("not all messages were accepted", failed.get()); + assertThat(failed.get()).as("not all messages were accepted").isTrue(); verify(handlerA, times(TOTAL_EXECUTIONS)).handleMessage(message); verify(handlerB, times(0)).handleMessage(message); verify(exceptionRegistry, times(TOTAL_EXECUTIONS)).add(any(Exception.class)); @@ -280,12 +279,12 @@ public class MixedDispatcherConfigurationScenarioTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); - assertTrue("not all messages were accepted", failed.get()); + assertThat(failed.get()).as("not all messages were accepted").isTrue(); verify(handlerA, times(14)).handleMessage(message); verify(handlerB, times(13)).handleMessage(message); verify(handlerC, times(13)).handleMessage(message); @@ -333,12 +332,12 @@ public class MixedDispatcherConfigurationScenarioTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); - assertTrue("not all messages were accepted", failed.get()); + assertThat(failed.get()).as("not all messages were accepted").isTrue(); verify(handlerA, times(14)).handleMessage(message); verify(handlerB, times(13)).handleMessage(message); verify(handlerC, times(13)).handleMessage(message); @@ -414,12 +413,12 @@ public class MixedDispatcherConfigurationScenarioTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); - assertFalse("not all messages were accepted", failed.get()); + assertThat(failed.get()).as("not all messages were accepted").isFalse(); verify(handlerA, times(TOTAL_EXECUTIONS)).handleMessage(message); verify(handlerB, times(TOTAL_EXECUTIONS)).handleMessage(message); verify(handlerC, never()).handleMessage(message); @@ -458,7 +457,7 @@ public class MixedDispatcherConfigurationScenarioTests { } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java index 2d9a510a12..923adc3ae5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -73,21 +73,21 @@ public class P2pChannelTests { MessageHandler handler1 = mock(MessageHandler.class); channel.subscribe(handler1); - assertEquals(1, channel.getSubscriberCount()); - assertEquals(String.format(log, 1), logs.remove(0)); + assertThat(channel.getSubscriberCount()).isEqualTo(1); + assertThat(logs.remove(0)).isEqualTo(String.format(log, 1)); MessageHandler handler2 = mock(MessageHandler.class); channel.subscribe(handler2); - assertEquals(2, channel.getSubscriberCount()); - assertEquals(String.format(log, 2), logs.remove(0)); + assertThat(channel.getSubscriberCount()).isEqualTo(2); + assertThat(logs.remove(0)).isEqualTo(String.format(log, 2)); channel.unsubscribe(handler1); - assertEquals(1, channel.getSubscriberCount()); - assertEquals(String.format(log, 1), logs.remove(0)); + assertThat(channel.getSubscriberCount()).isEqualTo(1); + assertThat(logs.remove(0)).isEqualTo(String.format(log, 1)); channel.unsubscribe(handler1); - assertEquals(1, channel.getSubscriberCount()); - assertEquals(0, logs.size()); + assertThat(channel.getSubscriberCount()).isEqualTo(1); + assertThat(logs.size()).isEqualTo(0); channel.unsubscribe(handler2); - assertEquals(0, channel.getSubscriberCount()); - assertEquals(String.format(log, 0), logs.remove(0)); + assertThat(channel.getSubscriberCount()).isEqualTo(0); + assertThat(logs.remove(0)).isEqualTo(String.format(log, 0)); verify(logger, times(4)).info(Mockito.anyString()); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java index e2f00dd6f6..5a6598c1eb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Comparator; import java.util.concurrent.CountDownLatch; @@ -45,12 +41,12 @@ public class PriorityChannelTests { @Test public void testCapacityEnforced() { PriorityChannel channel = new PriorityChannel(3); - assertTrue(channel.send(new GenericMessage<>("test1"), 0)); - assertTrue(channel.send(new GenericMessage<>("test2"), 0)); - assertTrue(channel.send(new GenericMessage<>("test3"), 0)); - assertFalse(channel.send(new GenericMessage<>("test4"), 0)); + assertThat(channel.send(new GenericMessage<>("test1"), 0)).isTrue(); + assertThat(channel.send(new GenericMessage<>("test2"), 0)).isTrue(); + assertThat(channel.send(new GenericMessage<>("test3"), 0)).isTrue(); + assertThat(channel.send(new GenericMessage<>("test4"), 0)).isFalse(); channel.receive(0); - assertTrue(channel.send(new GenericMessage<>("test5"))); + assertThat(channel.send(new GenericMessage<>("test5"))).isTrue(); } @Test @@ -60,7 +56,7 @@ public class PriorityChannelTests { channel.send(new GenericMessage<>(i)); } for (int i = 0; i < 1000; i++) { - assertEquals(i, channel.receive().getPayload()); + assertThat(channel.receive().getPayload()).isEqualTo(i); } } @@ -77,11 +73,11 @@ public class PriorityChannelTests { channel.send(priority5); channel.send(priority1); channel.send(priority2); - assertEquals("test:10", channel.receive(0).getPayload()); - assertEquals("test:7", channel.receive(0).getPayload()); - assertEquals("test:0", channel.receive(0).getPayload()); - assertEquals("test:-3", channel.receive(0).getPayload()); - assertEquals("test:-99", channel.receive(0).getPayload()); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:10"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:7"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:0"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:-3"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:-99"); } // although this test has no assertions it results in ConcurrentModificationException @@ -110,11 +106,11 @@ public class PriorityChannelTests { channel.send(messageE); channel.send(messageD); channel.send(messageB); - assertEquals("A", channel.receive(0).getPayload()); - assertEquals("B", channel.receive(0).getPayload()); - assertEquals("C", channel.receive(0).getPayload()); - assertEquals("D", channel.receive(0).getPayload()); - assertEquals("E", channel.receive(0).getPayload()); + assertThat(channel.receive(0).getPayload()).isEqualTo("A"); + assertThat(channel.receive(0).getPayload()).isEqualTo("B"); + assertThat(channel.receive(0).getPayload()).isEqualTo("C"); + assertThat(channel.receive(0).getPayload()).isEqualTo("D"); + assertThat(channel.receive(0).getPayload()).isEqualTo("E"); } @Test @@ -149,14 +145,14 @@ public class PriorityChannelTests { Object receivedSeven = channel.receive(0).getPayload(); Object receivedEight = channel.receive(0).getPayload(); - assertEquals(7, receivedOne); - assertEquals(8, receivedTwo); - assertEquals(5, receivedThree); - assertEquals(6, receivedFour); - assertEquals(1, receivedFive); - assertEquals(2, receivedSix); - assertEquals(3, receivedSeven); - assertEquals(4, receivedEight); + assertThat(receivedOne).isEqualTo(7); + assertThat(receivedTwo).isEqualTo(8); + assertThat(receivedThree).isEqualTo(5); + assertThat(receivedFour).isEqualTo(6); + assertThat(receivedFive).isEqualTo(1); + assertThat(receivedSix).isEqualTo(2); + assertThat(receivedSeven).isEqualTo(3); + assertThat(receivedEight).isEqualTo(4); } @Test @@ -187,13 +183,13 @@ public class PriorityChannelTests { Object receivedSix = channel.receive(0).getPayload(); Object receivedSeven = channel.receive(0).getPayload(); - assertEquals(4, receivedOne); - assertEquals(5, receivedTwo); - assertEquals(1, receivedThree); - assertEquals(2, receivedFour); - assertEquals(3, receivedFive); - assertEquals(6, receivedSix); - assertEquals(7, receivedSeven); + assertThat(receivedOne).isEqualTo(4); + assertThat(receivedTwo).isEqualTo(5); + assertThat(receivedThree).isEqualTo(1); + assertThat(receivedFour).isEqualTo(2); + assertThat(receivedFive).isEqualTo(3); + assertThat(receivedSix).isEqualTo(6); + assertThat(receivedSeven).isEqualTo(7); } @Test @@ -205,9 +201,9 @@ public class PriorityChannelTests { channel.send(lowPriority); channel.send(highPriority); channel.send(nullPriority); - assertEquals("test:5", channel.receive(0).getPayload()); - assertEquals("test:NULL", channel.receive(0).getPayload()); - assertEquals("test:-5", channel.receive(0).getPayload()); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:5"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:NULL"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:-5"); } @Test @@ -219,9 +215,9 @@ public class PriorityChannelTests { channel.send(lowPriority); channel.send(highPriority); channel.send(nullPriority); - assertEquals("test:5", channel.receive(0).getPayload()); - assertEquals("test:NULL", channel.receive(0).getPayload()); - assertEquals("test:-5", channel.receive(0).getPayload()); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:5"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:NULL"); + assertThat(channel.receive(0).getPayload()).isEqualTo("test:-5"); } @Test @@ -231,15 +227,15 @@ public class PriorityChannelTests { ExecutorService executor = Executors.newSingleThreadScheduledExecutor(); channel.send(new GenericMessage<>("test-1")); executor.execute(() -> sentSecondMessage.set(channel.send(new GenericMessage<>("test-2"), 10))); - assertFalse(sentSecondMessage.get()); + assertThat(sentSecondMessage.get()).isFalse(); executor.shutdown(); - assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); Message message1 = channel.receive(10000); - assertNotNull(message1); - assertEquals("test-1", message1.getPayload()); - assertFalse(sentSecondMessage.get()); - assertNull(channel.receive(0)); + assertThat(message1).isNotNull(); + assertThat(message1.getPayload()).isEqualTo("test-1"); + assertThat(sentSecondMessage.get()).isFalse(); + assertThat(channel.receive(0)).isNull(); } @Test @@ -253,16 +249,16 @@ public class PriorityChannelTests { sentSecondMessage.set(channel.send(new GenericMessage<>("test-2"), 3000)); latch.countDown(); }); - assertFalse(sentSecondMessage.get()); + assertThat(sentSecondMessage.get()).isFalse(); Thread.sleep(10); Message message1 = channel.receive(); - assertNotNull(message1); - assertEquals("test-1", message1.getPayload()); - assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); - assertTrue(sentSecondMessage.get()); + assertThat(message1).isNotNull(); + assertThat(message1.getPayload()).isEqualTo("test-1"); + assertThat(latch.await(10000, TimeUnit.MILLISECONDS)).isTrue(); + assertThat(sentSecondMessage.get()).isTrue(); Message message2 = channel.receive(); - assertNotNull(message2); - assertEquals("test-2", message2.getPayload()); + assertThat(message2).isNotNull(); + assertThat(message2.getPayload()).isEqualTo("test-2"); executor.shutdownNow(); } @@ -273,17 +269,17 @@ public class PriorityChannelTests { ExecutorService executor = Executors.newSingleThreadScheduledExecutor(); channel.send(new GenericMessage("test-1")); executor.execute(() -> sentSecondMessage.set(channel.send(new GenericMessage<>("test-2"), -1))); - assertFalse(sentSecondMessage.get()); + assertThat(sentSecondMessage.get()).isFalse(); Thread.sleep(10); Message message1 = channel.receive(10000); - assertNotNull(message1); - assertEquals("test-1", message1.getPayload()); + assertThat(message1).isNotNull(); + assertThat(message1.getPayload()).isEqualTo("test-1"); executor.shutdown(); - assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS)); - assertTrue(sentSecondMessage.get()); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + assertThat(sentSecondMessage.get()).isTrue(); Message message2 = channel.receive(); - assertNotNull(message2); - assertEquals("test-2", message2.getPayload()); + assertThat(message2).isNotNull(); + assertThat(message2.getPayload()).isEqualTo("test-2"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/PublishSubscribeChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/PublishSubscribeChannelTests.java index 87b211a3c2..7c90ce41c8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/PublishSubscribeChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/PublishSubscribeChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2019 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,8 @@ package org.springframework.integration.channel; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.util.concurrent.Executor; @@ -44,8 +43,9 @@ public class PublishSubscribeChannelTests { fail("expected Exception"); } catch (IllegalStateException e) { - assertThat(e.getMessage(), equalTo("When providing an Executor, you cannot subscribe() until the channel " - + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition")); + assertThat(e.getMessage()).isEqualTo("When providing an Executor, you cannot subscribe() until the " + + "channel " + + "bean is fully initialized by the framework. Do not subscribe in a @Bean definition"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java index 2f82b99ff3..43a7f20977 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.spy; @@ -60,7 +57,7 @@ public class QueueChannelTests { } }); channel.send(new GenericMessage<>("testing")); - assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); + assertThat(latch.await(10000, TimeUnit.MILLISECONDS)).isTrue(); exec.shutdownNow(); } @@ -76,7 +73,7 @@ public class QueueChannelTests { } }); channel.send(new GenericMessage<>("testing")); - assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); + assertThat(latch.await(10000, TimeUnit.MILLISECONDS)).isTrue(); exec.shutdownNow(); } @@ -92,7 +89,7 @@ public class QueueChannelTests { } }); channel.send(new GenericMessage<>("testing")); - assertTrue(latch.await(10000, TimeUnit.MILLISECONDS)); + assertThat(latch.await(10000, TimeUnit.MILLISECONDS)).isTrue(); exec.shutdownNow(); } @@ -110,7 +107,7 @@ public class QueueChannelTests { }; Runnable sendTask = () -> channel.send(new GenericMessage<>("testing")); singleThreadExecutor.execute(receiveTask1); - assertTrue(latch1.await(10, TimeUnit.SECONDS)); + assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); singleThreadExecutor.execute(sendTask); Runnable receiveTask2 = () -> { Message message = channel.receive(0); @@ -119,7 +116,7 @@ public class QueueChannelTests { } }; singleThreadExecutor.execute(receiveTask2); - assertTrue(latch2.await(10, TimeUnit.SECONDS)); + assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); singleThreadExecutor.shutdownNow(); } @@ -135,8 +132,8 @@ public class QueueChannelTests { latch.countDown(); }); exec.shutdownNow(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertTrue(messageNull.get()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(messageNull.get()).isTrue(); } @Test @@ -151,8 +148,8 @@ public class QueueChannelTests { latch.countDown(); }); exec.shutdownNow(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertTrue(messageNull.get()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(messageNull.get()).isTrue(); } @Test @@ -173,9 +170,9 @@ public class QueueChannelTests { latch.countDown(); } }); - assertTrue(pollLatch.await(10, TimeUnit.SECONDS)); + assertThat(pollLatch.await(10, TimeUnit.SECONDS)).isTrue(); channel.send(new GenericMessage<>("testing")); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); exec.shutdownNow(); } @@ -197,9 +194,9 @@ public class QueueChannelTests { latch.countDown(); } }); - assertTrue(pollLatch.await(10, TimeUnit.SECONDS)); + assertThat(pollLatch.await(10, TimeUnit.SECONDS)).isTrue(); channel.send(new GenericMessage<>("testing")); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); exec.shutdownNow(); } @@ -207,20 +204,20 @@ public class QueueChannelTests { public void testImmediateSend() { QueueChannel channel = new QueueChannel(3); boolean result1 = channel.send(new GenericMessage<>("test-1")); - assertTrue(result1); + assertThat(result1).isTrue(); boolean result2 = channel.send(new GenericMessage<>("test-2"), 100); - assertTrue(result2); + assertThat(result2).isTrue(); boolean result3 = channel.send(new GenericMessage<>("test-3"), 0); - assertTrue(result3); + assertThat(result3).isTrue(); boolean result4 = channel.send(new GenericMessage<>("test-4"), 0); - assertFalse(result4); + assertThat(result4).isFalse(); } @Test public void testBlockingSendWithNoTimeout() throws Exception { final QueueChannel channel = new QueueChannel(1); boolean result1 = channel.send(new GenericMessage<>("test-1")); - assertTrue(result1); + assertThat(result1).isTrue(); final CountDownLatch latch = new CountDownLatch(1); ExecutorService exec = Executors.newSingleThreadExecutor(); exec.execute(() -> { @@ -228,14 +225,14 @@ public class QueueChannelTests { latch.countDown(); }); exec.shutdownNow(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test public void testBlockingSendWithTimeout() throws Exception { final QueueChannel channel = new QueueChannel(1); boolean result1 = channel.send(new GenericMessage<>("test-1")); - assertTrue(result1); + assertThat(result1).isTrue(); final CountDownLatch latch = new CountDownLatch(1); ExecutorService exec = Executors.newSingleThreadExecutor(); exec.execute(() -> { @@ -243,7 +240,7 @@ public class QueueChannelTests { latch.countDown(); }); exec.shutdownNow(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test @@ -252,21 +249,21 @@ public class QueueChannelTests { GenericMessage message1 = new GenericMessage<>("test1"); GenericMessage message2 = new GenericMessage<>("test2"); GenericMessage message3 = new GenericMessage<>("test3"); - assertTrue(channel.send(message1)); - assertTrue(channel.send(message2)); - assertFalse(channel.send(message3, 0)); + assertThat(channel.send(message1)).isTrue(); + assertThat(channel.send(message2)).isTrue(); + assertThat(channel.send(message3, 0)).isFalse(); List> clearedMessages = channel.clear(); - assertNotNull(clearedMessages); - assertEquals(2, clearedMessages.size()); - assertTrue(channel.send(message3)); + assertThat(clearedMessages).isNotNull(); + assertThat(clearedMessages.size()).isEqualTo(2); + assertThat(channel.send(message3)).isTrue(); } @Test public void testClearEmptyChannel() { QueueChannel channel = new QueueChannel(); List> clearedMessages = channel.clear(); - assertNotNull(clearedMessages); - assertEquals(0, clearedMessages.size()); + assertThat(clearedMessages).isNotNull(); + assertThat(clearedMessages.size()).isEqualTo(0); } @Test @@ -280,13 +277,13 @@ public class QueueChannelTests { .setExpirationDate(past).build(); Message unexpiredMessage = MessageBuilder.withPayload("test2") .setExpirationDate(future).build(); - assertTrue(channel.send(expiredMessage, 0)); - assertTrue(channel.send(unexpiredMessage, 0)); - assertFalse(channel.send(new GenericMessage<>("atCapacity"), 0)); + assertThat(channel.send(expiredMessage, 0)).isTrue(); + assertThat(channel.send(unexpiredMessage, 0)).isTrue(); + assertThat(channel.send(new GenericMessage<>("atCapacity"), 0)).isFalse(); List> purgedMessages = channel.purge(new UnexpiredMessageSelector()); - assertNotNull(purgedMessages); - assertEquals(1, purgedMessages.size()); - assertTrue(channel.send(new GenericMessage<>("roomAvailable"), 0)); + assertThat(purgedMessages).isNotNull(); + assertThat(purgedMessages.size()).isEqualTo(1); + assertThat(channel.send(new GenericMessage<>("roomAvailable"), 0)).isTrue(); } @Rule diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/TransactionSynchronizationQueueChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/TransactionSynchronizationQueueChannelTests.java index 67e46f967a..42fd7ebdc2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/TransactionSynchronizationQueueChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/TransactionSynchronizationQueueChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; @@ -65,17 +63,17 @@ public class TransactionSynchronizationQueueChannelTests { GenericMessage sentMessage = new GenericMessage<>("hello"); this.queueChannel.send(sentMessage); Message message = this.good.receive(10000); - assertNotNull(message); - assertEquals("hello", message.getPayload()); - assertSame(message, sentMessage); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("hello"); + assertThat(sentMessage).isSameAs(message); } @Test public void testRollback() throws Exception { this.queueChannel.send(new GenericMessage<>("fail")); Message message = this.good.receive(10000); - assertNotNull(message); - assertEquals("retry:fail", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("retry:fail"); } @Test @@ -84,10 +82,10 @@ public class TransactionSynchronizationQueueChannelTests { .setHeader("foo", "bar").build(); queueChannel2.send(sentMessage); Message message = good.receive(10000); - assertNotNull(message); - assertEquals("hello processed ok from queueChannel2", message.getPayload()); - assertNotNull(message.getHeaders().get("foo")); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("hello processed ok from queueChannel2"); + assertThat(message.getHeaders().get("foo")).isNotNull(); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } public static class Service { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/AutoGeneratedChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/AutoGeneratedChannelTests.java index 49d852c3f0..324176853e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/AutoGeneratedChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/AutoGeneratedChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -41,8 +40,8 @@ public class AutoGeneratedChannelTests { @Test public void checkConfig() { Object input = context.getBean("input"); - assertNotNull(input); - assertEquals(DirectChannel.class, input.getClass()); + assertThat(input).isNotNull(); + assertThat(input.getClass()).isEqualTo(DirectChannel.class); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelCapacityPlaceholderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelCapacityPlaceholderTests.java index 4e0ed1f4cc..5da68da5f0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelCapacityPlaceholderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelCapacityPlaceholderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -44,25 +43,25 @@ public class ChannelCapacityPlaceholderTests { @Test public void verifyCapacityValueChanges() { QueueChannel channel = context.getBean("channel", QueueChannel.class); - assertNotNull(channel); - assertEquals(99, channel.getRemainingCapacity()); + assertThat(channel).isNotNull(); + assertThat(channel.getRemainingCapacity()).isEqualTo(99); channel.send(MessageBuilder.withPayload("test1").build()); channel.send(MessageBuilder.withPayload("test2").build()); - assertEquals(97, channel.getRemainingCapacity()); - assertNotNull(channel.receive(0)); - assertEquals(98, channel.getRemainingCapacity()); + assertThat(channel.getRemainingCapacity()).isEqualTo(97); + assertThat(channel.receive(0)).isNotNull(); + assertThat(channel.getRemainingCapacity()).isEqualTo(98); } @Test public void testCapacityOnPriorityChannel() { PriorityChannel channel = context.getBean("priorityChannel", PriorityChannel.class); - assertNotNull(channel); - assertEquals(99, channel.getRemainingCapacity()); + assertThat(channel).isNotNull(); + assertThat(channel.getRemainingCapacity()).isEqualTo(99); channel.send(MessageBuilder.withPayload("test1").build()); channel.send(MessageBuilder.withPayload("test2").build()); - assertEquals(97, channel.getRemainingCapacity()); - assertNotNull(channel.receive(0)); - assertEquals(98, channel.getRemainingCapacity()); + assertThat(channel.getRemainingCapacity()).isEqualTo(97); + assertThat(channel.receive(0)).isNotNull(); + assertThat(channel.getRemainingCapacity()).isEqualTo(98); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelParserTests.java index e0ed47cac1..15b5199ebd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,15 +16,7 @@ package org.springframework.integration.channel.config; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.Executor; @@ -89,28 +81,28 @@ public class ChannelParserTests { MessageChannel channel = (MessageChannel) context.getBean("capacityChannel"); for (int i = 0; i < 10; i++) { boolean result = channel.send(new GenericMessage("test"), 10); - assertTrue(result); + assertThat(result).isTrue(); } - assertFalse(channel.send(new GenericMessage("test"), 3)); + assertThat(channel.send(new GenericMessage("test"), 3)).isFalse(); } @Test public void testDirectChannelByDefault() throws InterruptedException { MessageChannel channel = (MessageChannel) context.getBean("defaultChannel"); - assertThat(channel, instanceOf(DirectChannel.class)); + assertThat(channel).isInstanceOf(DirectChannel.class); DirectFieldAccessor accessor = new DirectFieldAccessor(channel); Object dispatcher = accessor.getPropertyValue("dispatcher"); - assertThat(dispatcher, is(instanceOf(UnicastingDispatcher.class))); - assertThat(new DirectFieldAccessor(dispatcher).getPropertyValue("loadBalancingStrategy"), - is(instanceOf(RoundRobinLoadBalancingStrategy.class))); + assertThat(dispatcher).isInstanceOf(UnicastingDispatcher.class); + assertThat(new DirectFieldAccessor(dispatcher).getPropertyValue("loadBalancingStrategy")) + .isInstanceOf(RoundRobinLoadBalancingStrategy.class); } @Test public void testExecutorChannel() throws InterruptedException { MessageChannel channel = context.getBean("executorChannel", MessageChannel.class); - assertThat(channel, instanceOf(ExecutorChannel.class)); - assertNotNull(TestUtils.getPropertyValue(channel, "messageConverter")); - assertNotNull(TestUtils.getPropertyValue(channel, "messageConverter.conversionService")); + assertThat(channel).isInstanceOf(ExecutorChannel.class); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter")).isNotNull(); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter.conversionService")).isNotNull(); } @Test @@ -118,63 +110,63 @@ public class ChannelParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "ChannelParserTests-no-converter-context.xml", this.getClass()); MessageChannel channel = context.getBean("executorChannel", MessageChannel.class); - assertThat(channel, instanceOf(ExecutorChannel.class)); - assertNotNull(TestUtils.getPropertyValue(channel, "messageConverter")); - assertNotNull(TestUtils.getPropertyValue(channel, "messageConverter.conversionService")); + assertThat(channel).isInstanceOf(ExecutorChannel.class); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter")).isNotNull(); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter.conversionService")).isNotNull(); context.close(); } @Test public void channelWithFailoverDispatcherAttribute() throws Exception { MessageChannel channel = (MessageChannel) context.getBean("channelWithFailover"); - assertEquals(DirectChannel.class, channel.getClass()); + assertThat(channel.getClass()).isEqualTo(DirectChannel.class); DirectFieldAccessor accessor = new DirectFieldAccessor(channel); Object dispatcher = accessor.getPropertyValue("dispatcher"); - assertThat(dispatcher, is(instanceOf(UnicastingDispatcher.class))); - assertNull(new DirectFieldAccessor(dispatcher).getPropertyValue("loadBalancingStrategy")); + assertThat(dispatcher).isInstanceOf(UnicastingDispatcher.class); + assertThat(new DirectFieldAccessor(dispatcher).getPropertyValue("loadBalancingStrategy")).isNull(); } @Test public void testPublishSubscribeChannel() throws InterruptedException { MessageChannel channel = (MessageChannel) context.getBean("publishSubscribeChannel"); - assertEquals(PublishSubscribeChannel.class, channel.getClass()); + assertThat(channel.getClass()).isEqualTo(PublishSubscribeChannel.class); } @Test public void testPublishSubscribeChannelWithTaskExecutorReference() throws InterruptedException { MessageChannel channel = (MessageChannel) context.getBean("publishSubscribeChannelWithTaskExecutorRef"); - assertEquals(PublishSubscribeChannel.class, channel.getClass()); + assertThat(channel.getClass()).isEqualTo(PublishSubscribeChannel.class); DirectFieldAccessor accessor = new DirectFieldAccessor(channel); accessor = new DirectFieldAccessor(accessor.getPropertyValue("dispatcher")); Object executorProperty = accessor.getPropertyValue("executor"); - assertNotNull(executorProperty); - assertEquals(ErrorHandlingTaskExecutor.class, executorProperty.getClass()); + assertThat(executorProperty).isNotNull(); + assertThat(executorProperty.getClass()).isEqualTo(ErrorHandlingTaskExecutor.class); DirectFieldAccessor executorAccessor = new DirectFieldAccessor(executorProperty); Executor innerExecutor = (Executor) executorAccessor.getPropertyValue("executor"); Object executorBean = context.getBean("taskExecutor"); - assertEquals(executorBean, innerExecutor); + assertThat(innerExecutor).isEqualTo(executorBean); } @Test public void channelWithCustomQueue() { Object customQueue = context.getBean("customQueue"); Object channelWithCustomQueue = context.getBean("channelWithCustomQueue"); - assertEquals(QueueChannel.class, channelWithCustomQueue.getClass()); + assertThat(channelWithCustomQueue.getClass()).isEqualTo(QueueChannel.class); Object actualQueue = new DirectFieldAccessor(channelWithCustomQueue).getPropertyValue("queue"); - assertSame(customQueue, actualQueue); + assertThat(actualQueue).isSameAs(customQueue); } @Test public void testDatatypeChannelWithCorrectType() { MessageChannel channel = (MessageChannel) context.getBean("integerChannel"); - assertTrue(channel.send(new GenericMessage(123))); + assertThat(channel.send(new GenericMessage(123))).isTrue(); } @Test(expected = MessageDeliveryException.class) public void testDatatypeChannelWithIncorrectType() { MessageChannel channel = (MessageChannel) context.getBean("integerChannel"); channel.send(new GenericMessage("incorrect type")); - assertTrue(TestUtils.getPropertyValue(channel, "messageConverter") instanceof UselessMessageConverter); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter") instanceof UselessMessageConverter).isTrue(); } @Test @@ -183,25 +175,25 @@ public class ChannelParserTests { new ClassPathXmlApplicationContext("channelParserGlobalConverterTests.xml", getClass()); MessageChannel channel = context.getBean("integerChannel", MessageChannel.class); context.close(); - assertTrue(TestUtils.getPropertyValue(channel, "messageConverter") instanceof UselessMessageConverter); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter") instanceof UselessMessageConverter).isTrue(); } @Test public void testDatatypeChannelWithAssignableSubTypes() { MessageChannel channel = (MessageChannel) context.getBean("numberChannel"); - assertTrue(channel.send(new GenericMessage<>(123))); - assertTrue(channel.send(new GenericMessage<>(123.45))); - assertTrue(channel.send(new GenericMessage<>(Boolean.TRUE))); - assertThat(TestUtils.getPropertyValue(channel, "messageConverter"), - instanceOf(DefaultDatatypeChannelMessageConverter.class)); - assertNotNull(TestUtils.getPropertyValue(channel, "messageConverter.conversionService")); + assertThat(channel.send(new GenericMessage<>(123))).isTrue(); + assertThat(channel.send(new GenericMessage<>(123.45))).isTrue(); + assertThat(channel.send(new GenericMessage<>(Boolean.TRUE))).isTrue(); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter")) + .isInstanceOf(DefaultDatatypeChannelMessageConverter.class); + assertThat(TestUtils.getPropertyValue(channel, "messageConverter.conversionService")).isNotNull(); } @Test public void testMultipleDatatypeChannelWithCorrectTypes() { MessageChannel channel = (MessageChannel) context.getBean("stringOrNumberChannel"); - assertTrue(channel.send(new GenericMessage<>(123))); - assertTrue(channel.send(new GenericMessage<>("accepted type"))); + assertThat(channel.send(new GenericMessage<>(123))).isTrue(); + assertThat(channel.send(new GenericMessage<>("accepted type"))).isTrue(); } @Test(expected = MessageDeliveryException.class) @@ -216,12 +208,12 @@ public class ChannelParserTests { new ClassPathXmlApplicationContext("channelInterceptorParserTests.xml", getClass()); PollableChannel channel = (PollableChannel) context.getBean("channelWithInterceptorRef"); TestChannelInterceptor interceptor = (TestChannelInterceptor) context.getBean("interceptor"); - assertEquals(0, interceptor.getSendCount()); + assertThat(interceptor.getSendCount()).isEqualTo(0); channel.send(new GenericMessage<>("test")); - assertEquals(1, interceptor.getSendCount()); - assertEquals(0, interceptor.getReceiveCount()); + assertThat(interceptor.getSendCount()).isEqualTo(1); + assertThat(interceptor.getReceiveCount()).isEqualTo(0); channel.receive(); - assertEquals(1, interceptor.getReceiveCount()); + assertThat(interceptor.getReceiveCount()).isEqualTo(1); context.close(); } @@ -232,7 +224,7 @@ public class ChannelParserTests { PollableChannel channel = (PollableChannel) context.getBean("channelWithInterceptorInnerBean"); channel.send(new GenericMessage("test")); Message transformed = channel.receive(1000); - assertEquals("TEST", transformed.getPayload()); + assertThat(transformed.getPayload()).isEqualTo("TEST"); context.close(); } @@ -248,9 +240,9 @@ public class ChannelParserTests { Message reply1 = channel.receive(0); Message reply2 = channel.receive(0); Message reply3 = channel.receive(0); - assertEquals("high", reply1.getPayload()); - assertEquals("mid", reply2.getPayload()); - assertEquals("low", reply3.getPayload()); + assertThat(reply1.getPayload()).isEqualTo("high"); + assertThat(reply2.getPayload()).isEqualTo("mid"); + assertThat(reply3.getPayload()).isEqualTo("low"); } @Test @@ -264,10 +256,10 @@ public class ChannelParserTests { Message reply2 = channel.receive(0); Message reply3 = channel.receive(0); Message reply4 = channel.receive(0); - assertEquals("A", reply1.getPayload()); - assertEquals("B", reply2.getPayload()); - assertEquals("C", reply3.getPayload()); - assertEquals("D", reply4.getPayload()); + assertThat(reply1.getPayload()).isEqualTo("A"); + assertThat(reply2.getPayload()).isEqualTo("B"); + assertThat(reply3.getPayload()).isEqualTo("C"); + assertThat(reply4.getPayload()).isEqualTo("D"); } @Test @@ -276,18 +268,18 @@ public class ChannelParserTests { channel.send(new GenericMessage<>(3)); channel.send(new GenericMessage<>(2)); channel.send(new GenericMessage<>(1)); - assertEquals(1, channel.receive(0).getPayload()); - assertEquals(2, channel.receive(0).getPayload()); - assertEquals(3, channel.receive(0).getPayload()); + assertThat(channel.receive(0).getPayload()).isEqualTo(1); + assertThat(channel.receive(0).getPayload()).isEqualTo(2); + assertThat(channel.receive(0).getPayload()).isEqualTo(3); boolean threwException = false; try { channel.send(new GenericMessage<>("wrong type")); } catch (MessageDeliveryException e) { - assertEquals("wrong type", e.getFailedMessage().getPayload()); + assertThat(e.getFailedMessage().getPayload()).isEqualTo("wrong type"); threwException = true; } - assertTrue(threwException); + assertThat(threwException).isTrue(); } public static class TestInterceptor implements ChannelInterceptor { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelWithCustomQueueParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelWithCustomQueueParserTests.java index 169519945f..dd2b5528e2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelWithCustomQueueParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ChannelWithCustomQueueParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.channel.config; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; @@ -54,16 +51,16 @@ public class ChannelWithCustomQueueParserTests { @Test public void parseConfig() throws Exception { - assertNotNull(customQueueChannel); + assertThat(customQueueChannel).isNotNull(); } @Test public void queueTypeSet() throws Exception { DirectFieldAccessor accessor = new DirectFieldAccessor(customQueueChannel); Object queue = accessor.getPropertyValue("queue"); - assertNotNull(queue); - assertThat(queue, is(instanceOf(ArrayBlockingQueue.class))); - assertThat(((BlockingQueue) queue).remainingCapacity(), is(2)); + assertThat(queue).isNotNull(); + assertThat(queue).isInstanceOf(ArrayBlockingQueue.class); + assertThat(((BlockingQueue) queue).remainingCapacity()).isEqualTo(2); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/DispatchingChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/DispatchingChannelParserTests.java index 21df7b2d47..cac03fe82d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/DispatchingChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/DispatchingChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,18 +16,12 @@ package org.springframework.integration.channel.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.Iterator; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -66,72 +60,73 @@ public class DispatchingChannelParserTests { @Test public void taskExecutorOnly() { MessageChannel channel = channels.get("taskExecutorOnly"); - assertEquals(ExecutorChannel.class, channel.getClass()); + assertThat(channel.getClass()).isEqualTo(ExecutorChannel.class); Object executor = getDispatcherProperty("executor", channel); - assertEquals(ErrorHandlingTaskExecutor.class, executor.getClass()); - assertSame(context.getBean("taskExecutor"), - new DirectFieldAccessor(executor).getPropertyValue("executor")); - assertTrue((Boolean) getDispatcherProperty("failover", channel)); - assertEquals(RoundRobinLoadBalancingStrategy.class, - getDispatcherProperty("loadBalancingStrategy", channel).getClass()); + assertThat(executor.getClass()).isEqualTo(ErrorHandlingTaskExecutor.class); + assertThat(new DirectFieldAccessor(executor).getPropertyValue("executor")) + .isSameAs(context.getBean("taskExecutor")); + assertThat((Boolean) getDispatcherProperty("failover", channel)).isTrue(); + assertThat(getDispatcherProperty("loadBalancingStrategy", channel).getClass()) + .isEqualTo(RoundRobinLoadBalancingStrategy.class); } @Test public void failoverFalse() { MessageChannel channel = channels.get("failoverFalse"); - assertEquals(DirectChannel.class, channel.getClass()); - assertFalse((Boolean) getDispatcherProperty("failover", channel)); - assertEquals(RoundRobinLoadBalancingStrategy.class, - getDispatcherProperty("loadBalancingStrategy", channel).getClass()); + assertThat(channel.getClass()).isEqualTo(DirectChannel.class); + assertThat((Boolean) getDispatcherProperty("failover", channel)).isFalse(); + assertThat(getDispatcherProperty("loadBalancingStrategy", channel).getClass()) + .isEqualTo(RoundRobinLoadBalancingStrategy.class); } @Test public void failoverTrue() { MessageChannel channel = channels.get("failoverTrue"); - assertEquals(DirectChannel.class, channel.getClass()); - assertTrue((Boolean) getDispatcherProperty("failover", channel)); - assertEquals(RoundRobinLoadBalancingStrategy.class, - getDispatcherProperty("loadBalancingStrategy", channel).getClass()); + assertThat(channel.getClass()).isEqualTo(DirectChannel.class); + assertThat((Boolean) getDispatcherProperty("failover", channel)).isTrue(); + assertThat(getDispatcherProperty("loadBalancingStrategy", channel).getClass()) + .isEqualTo(RoundRobinLoadBalancingStrategy.class); } @Test public void loadBalancerDisabled() { MessageChannel channel = channels.get("loadBalancerDisabled"); - assertEquals(DirectChannel.class, channel.getClass()); - assertTrue((Boolean) getDispatcherProperty("failover", channel)); - assertNull(getDispatcherProperty("loadBalancingStrategy", channel)); + assertThat(channel.getClass()).isEqualTo(DirectChannel.class); + assertThat((Boolean) getDispatcherProperty("failover", channel)).isTrue(); + assertThat(getDispatcherProperty("loadBalancingStrategy", channel)).isNull(); } @Test public void loadBalancerDisabledAndTaskExecutor() { MessageChannel channel = channels.get("loadBalancerDisabledAndTaskExecutor"); - assertEquals(ExecutorChannel.class, channel.getClass()); - assertTrue((Boolean) getDispatcherProperty("failover", channel)); - assertNull(getDispatcherProperty("loadBalancingStrategy", channel)); + assertThat(channel.getClass()).isEqualTo(ExecutorChannel.class); + assertThat((Boolean) getDispatcherProperty("failover", channel)).isTrue(); + assertThat(getDispatcherProperty("loadBalancingStrategy", channel)).isNull(); Object executor = getDispatcherProperty("executor", channel); - assertEquals(ErrorHandlingTaskExecutor.class, executor.getClass()); - assertSame(context.getBean("taskExecutor"), - new DirectFieldAccessor(executor).getPropertyValue("executor")); + assertThat(executor.getClass()).isEqualTo(ErrorHandlingTaskExecutor.class); + assertThat(new DirectFieldAccessor(executor).getPropertyValue("executor")) + .isSameAs(context.getBean("taskExecutor")); } @Test public void roundRobinLoadBalancerAndTaskExecutor() { MessageChannel channel = channels.get("roundRobinLoadBalancerAndTaskExecutor"); - assertEquals(ExecutorChannel.class, channel.getClass()); - assertTrue((Boolean) getDispatcherProperty("failover", channel)); - assertEquals(RoundRobinLoadBalancingStrategy.class, - getDispatcherProperty("loadBalancingStrategy", channel).getClass()); + assertThat(channel.getClass()).isEqualTo(ExecutorChannel.class); + assertThat((Boolean) getDispatcherProperty("failover", channel)).isTrue(); + assertThat(getDispatcherProperty("loadBalancingStrategy", channel).getClass()) + .isEqualTo(RoundRobinLoadBalancingStrategy.class); Object executor = getDispatcherProperty("executor", channel); - assertEquals(ErrorHandlingTaskExecutor.class, executor.getClass()); - assertSame(context.getBean("taskExecutor"), - new DirectFieldAccessor(executor).getPropertyValue("executor")); + assertThat(executor.getClass()).isEqualTo(ErrorHandlingTaskExecutor.class); + assertThat(new DirectFieldAccessor(executor).getPropertyValue("executor")) + .isSameAs(context.getBean("taskExecutor")); } @Test public void loadBalancerRef() { MessageChannel channel = channels.get("lbRefChannel"); - LoadBalancingStrategy lbStrategy = TestUtils.getPropertyValue(channel, "dispatcher.loadBalancingStrategy", LoadBalancingStrategy.class); - assertTrue(lbStrategy instanceof SampleLoadBalancingStrategy); + LoadBalancingStrategy lbStrategy = TestUtils.getPropertyValue(channel, "dispatcher.loadBalancingStrategy", + LoadBalancingStrategy.class); + assertThat(lbStrategy instanceof SampleLoadBalancingStrategy).isTrue(); } @Test @@ -141,7 +136,7 @@ public class DispatchingChannelParserTests { new ClassPathXmlApplicationContext("ChannelWithLoadBalancerRef-fail-config.xml", this.getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), Matchers.containsString("'load-balancer' and 'load-balancer-ref' are mutually exclusive")); + assertThat(e.getMessage()).contains("'load-balancer' and 'load-balancer-ref' are mutually exclusive"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/RendezvousChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/RendezvousChannelParserTests.java index b3090441d7..8f0ab71b15 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/RendezvousChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/RendezvousChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.config; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -35,7 +35,7 @@ public class RendezvousChannelParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "rendezvousChannelParserTests.xml", RendezvousChannelParserTests.class); MessageChannel channel = (MessageChannel) context.getBean("channel"); - assertEquals(RendezvousChannel.class, channel.getClass()); + assertThat(channel.getClass()).isEqualTo(RendezvousChannel.class); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java index 896f2ba6b8..07a25e826e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -67,10 +65,10 @@ public class ThreadLocalChannelParserTests { simpleChannel.send(new GenericMessage("crap")); latch.countDown(); }); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertEquals("test", simpleChannel.receive(10).getPayload()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(simpleChannel.receive(10).getPayload()).isEqualTo("test"); // Message sent on another thread is not collected here - assertEquals(null, simpleChannel.receive(10)); + assertThat(simpleChannel.receive(10)).isEqualTo(null); } @Test @@ -91,24 +89,24 @@ public class ThreadLocalChannelParserTests { otherThreadResults.add(channelWithInterceptor.receive(0)); latch.countDown(); }); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertEquals(2, otherThreadResults.size()); - assertNull(otherThreadResults.get(0)); - assertNull(otherThreadResults.get(1)); - assertEquals("test-1.1", simpleChannel.receive(0).getPayload()); - assertEquals("test-1.2", simpleChannel.receive(0).getPayload()); - assertEquals("test-1.3", simpleChannel.receive(0).getPayload()); - assertNull(simpleChannel.receive(0)); - assertEquals("test-2.1", channelWithInterceptor.receive(0).getPayload()); - assertEquals("test-2.2", channelWithInterceptor.receive(0).getPayload()); - assertNull(channelWithInterceptor.receive(0)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(otherThreadResults.size()).isEqualTo(2); + assertThat(otherThreadResults.get(0)).isNull(); + assertThat(otherThreadResults.get(1)).isNull(); + assertThat(simpleChannel.receive(0).getPayload()).isEqualTo("test-1.1"); + assertThat(simpleChannel.receive(0).getPayload()).isEqualTo("test-1.2"); + assertThat(simpleChannel.receive(0).getPayload()).isEqualTo("test-1.3"); + assertThat(simpleChannel.receive(0)).isNull(); + assertThat(channelWithInterceptor.receive(0).getPayload()).isEqualTo("test-2.1"); + assertThat(channelWithInterceptor.receive(0).getPayload()).isEqualTo("test-2.2"); + assertThat(channelWithInterceptor.receive(0)).isNull(); } @Test public void testInterceptor() { int before = interceptor.getSendCount(); channelWithInterceptor.send(new GenericMessage("test")); - assertEquals(before + 1, interceptor.getSendCount()); + assertThat(interceptor.getSendCount()).isEqualTo(before + 1); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java index 90210f6cc2..3d21be2eb0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.interceptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -31,7 +25,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.context.ConfigurableApplicationContext; @@ -67,10 +60,10 @@ public class ChannelInterceptorTests { channel.addInterceptor(interceptor); channel.send(new GenericMessage("test")); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); - assertEquals(1, result.getHeaders().get(PreSendReturnsMessageInterceptor.class.getSimpleName())); - assertTrue(interceptor.wasAfterCompletionInvoked()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get(PreSendReturnsMessageInterceptor.class.getSimpleName())).isEqualTo(1); + assertThat(interceptor.wasAfterCompletionInvoked()).isTrue(); } @Test @@ -79,16 +72,16 @@ public class ChannelInterceptorTests { channel.addInterceptor(interceptor); Message message = new GenericMessage("test"); channel.send(message); - assertEquals(1, interceptor.getCount()); + assertThat(interceptor.getCount()).isEqualTo(1); - assertTrue(channel.removeInterceptor(interceptor)); + assertThat(channel.removeInterceptor(interceptor)).isTrue(); channel.send(new GenericMessage("TEST")); - assertEquals(1, interceptor.getCount()); + assertThat(interceptor.getCount()).isEqualTo(1); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); } @Test @@ -98,16 +91,16 @@ public class ChannelInterceptorTests { @Override public void postSend(Message message, MessageChannel channel, boolean sent) { - assertNotNull(message); - assertNotNull(channel); - assertSame(ChannelInterceptorTests.this.channel, channel); - assertTrue(sent); + assertThat(message).isNotNull(); + assertThat(channel).isNotNull(); + assertThat(channel).isSameAs(ChannelInterceptorTests.this.channel); + assertThat(sent).isTrue(); invoked.set(true); } }); channel.send(new GenericMessage("test")); - assertTrue(invoked.get()); + assertThat(invoked.get()).isTrue(); } @Test @@ -119,9 +112,9 @@ public class ChannelInterceptorTests { @Override public void postSend(Message message, MessageChannel channel, boolean sent) { - assertNotNull(message); - assertNotNull(channel); - assertSame(singleItemChannel, channel); + assertThat(message).isNotNull(); + assertThat(channel).isNotNull(); + assertThat(channel).isSameAs(singleItemChannel); if (sent) { sentCounter.incrementAndGet(); } @@ -129,19 +122,19 @@ public class ChannelInterceptorTests { } }); - assertEquals(0, invokedCounter.get()); - assertEquals(0, sentCounter.get()); + assertThat(invokedCounter.get()).isEqualTo(0); + assertThat(sentCounter.get()).isEqualTo(0); singleItemChannel.send(new GenericMessage("test1")); - assertEquals(1, invokedCounter.get()); - assertEquals(1, sentCounter.get()); + assertThat(invokedCounter.get()).isEqualTo(1); + assertThat(sentCounter.get()).isEqualTo(1); singleItemChannel.send(new GenericMessage("test2"), 0); - assertEquals(2, invokedCounter.get()); - assertEquals(1, sentCounter.get()); + assertThat(invokedCounter.get()).isEqualTo(2); + assertThat(sentCounter.get()).isEqualTo(1); - assertNotNull(singleItemChannel.removeInterceptor(0)); + assertThat(singleItemChannel.removeInterceptor(0)).isNotNull(); singleItemChannel.send(new GenericMessage("test2"), 0); - assertEquals(2, invokedCounter.get()); - assertEquals(1, sentCounter.get()); + assertThat(invokedCounter.get()).isEqualTo(2); + assertThat(sentCounter.get()).isEqualTo(1); } @Test @@ -161,10 +154,10 @@ public class ChannelInterceptorTests { testChannel.send(MessageBuilder.withPayload("test").build()); } catch (Exception ex) { - assertEquals("Simulated exception", ex.getCause().getMessage()); + assertThat(ex.getCause().getMessage()).isEqualTo("Simulated exception"); } - assertTrue(interceptor1.wasAfterCompletionInvoked()); - assertTrue(interceptor2.wasAfterCompletionInvoked()); + assertThat(interceptor1.wasAfterCompletionInvoked()).isTrue(); + assertThat(interceptor2.wasAfterCompletionInvoked()).isTrue(); } @Test @@ -178,10 +171,10 @@ public class ChannelInterceptorTests { this.channel.send(MessageBuilder.withPayload("test").build()); } catch (Exception ex) { - assertEquals("Simulated exception", ex.getCause().getMessage()); + assertThat(ex.getCause().getMessage()).isEqualTo("Simulated exception"); } - assertTrue(interceptor1.wasAfterCompletionInvoked()); - assertFalse(interceptor2.wasAfterCompletionInvoked()); + assertThat(interceptor1.wasAfterCompletionInvoked()).isTrue(); + assertThat(interceptor2.wasAfterCompletionInvoked()).isFalse(); } @Test @@ -191,9 +184,9 @@ public class ChannelInterceptorTests { Message message = new GenericMessage("test"); channel.send(message); Message result = channel.receive(0); - assertEquals(1, interceptor.getCounter().get()); - assertNotNull(result); - assertTrue(interceptor.wasAfterCompletionInvoked()); + assertThat(interceptor.getCounter().get()).isEqualTo(1); + assertThat(result).isNotNull(); + assertThat(interceptor.wasAfterCompletionInvoked()).isTrue(); } @Test @@ -202,8 +195,8 @@ public class ChannelInterceptorTests { Message message = new GenericMessage("test"); channel.send(message); Message result = channel.receive(0); - assertEquals(1, PreReceiveReturnsFalseInterceptor.counter.get()); - assertNull(result); + assertThat(PreReceiveReturnsFalseInterceptor.counter.get()).isEqualTo(1); + assertThat(result).isNull(); } @Test @@ -213,19 +206,19 @@ public class ChannelInterceptorTests { @Override public Message postReceive(Message message, MessageChannel channel) { - assertNotNull(channel); - assertSame(ChannelInterceptorTests.this.channel, channel); + assertThat(channel).isNotNull(); + assertThat(channel).isSameAs(ChannelInterceptorTests.this.channel); messageCount.incrementAndGet(); return message; } }); channel.receive(0); - assertEquals(0, messageCount.get()); + assertThat(messageCount.get()).isEqualTo(0); channel.send(new GenericMessage("test")); Message result = channel.receive(0); - assertNotNull(result); - assertEquals(1, messageCount.get()); + assertThat(result).isNotNull(); + assertThat(messageCount.get()).isEqualTo(1); } @Test @@ -240,10 +233,10 @@ public class ChannelInterceptorTests { channel.receive(0); } catch (Exception ex) { - assertEquals("Simulated exception", ex.getMessage()); + assertThat(ex.getMessage()).isEqualTo("Simulated exception"); } - assertTrue(interceptor1.wasAfterCompletionInvoked()); - assertFalse(interceptor2.wasAfterCompletionInvoked()); + assertThat(interceptor1.wasAfterCompletionInvoked()).isTrue(); + assertThat(interceptor2.wasAfterCompletionInvoked()).isFalse(); } @Test @@ -253,10 +246,10 @@ public class ChannelInterceptorTests { ChannelInterceptorAware channel = ac.getBean("input", AbstractMessageChannel.class); List interceptors = channel.getChannelInterceptors(); ChannelInterceptor channelInterceptor = interceptors.get(0); - assertThat(channelInterceptor, Matchers.instanceOf(PreSendReturnsMessageInterceptor.class)); + assertThat(channelInterceptor).isInstanceOf(PreSendReturnsMessageInterceptor.class); String foo = ((PreSendReturnsMessageInterceptor) channelInterceptor).getFoo(); - assertTrue(StringUtils.hasText(foo)); - assertEquals("foo", foo); + assertThat(StringUtils.hasText(foo)).isTrue(); + assertThat(foo).isEqualTo("foo"); ac.close(); } @@ -281,16 +274,16 @@ public class ChannelInterceptorTests { channel.send(new GenericMessage<>("foo")); - assertTrue(latch1.await(10, TimeUnit.SECONDS)); + assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); channel.addInterceptor(new TestExecutorInterceptor()); channel.send(new GenericMessage<>("foo")); - assertTrue(latch2.await(10, TimeUnit.SECONDS)); - assertEquals(2, messages.size()); + assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(messages.size()).isEqualTo(2); - assertEquals("foo", messages.get(0).getPayload()); - assertEquals("FOO", messages.get(1).getPayload()); + assertThat(messages.get(0).getPayload()).isEqualTo("foo"); + assertThat(messages.get(1).getPayload()).isEqualTo("FOO"); testApplicationContext.close(); } @@ -304,7 +297,7 @@ public class ChannelInterceptorTests { @Override public Message preSend(Message message, MessageChannel channel) { - assertNotNull(message); + assertThat(message).isNotNull(); return MessageBuilder.fromMessage(message) .setHeader(this.getClass().getSimpleName(), counter.incrementAndGet()) .build(); @@ -343,7 +336,7 @@ public class ChannelInterceptorTests { @Override public Message preSend(Message message, MessageChannel channel) { - assertNotNull(message); + assertThat(message).isNotNull(); counter.incrementAndGet(); return null; } @@ -376,7 +369,7 @@ public class ChannelInterceptorTests { @Override public Message preSend(Message message, MessageChannel channel) { - assertNotNull(message); + assertThat(message).isNotNull(); counter.incrementAndGet(); if (this.exceptionToRaise != null) { throw this.exceptionToRaise; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorSubElementTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorSubElementTests.java index 93e3d44b9c..124859927d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorSubElementTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorSubElementTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.interceptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -59,10 +57,10 @@ public class GlobalChannelInterceptorSubElementTests { public void testWiretapSubElement() { this.inputA.send(new GenericMessage("hello")); Message result = this.wiretapChannel.receive(100); - assertNotNull(result); - assertEquals("hello", result.getPayload()); - assertNull(this.wiretapChannel.receive(1)); - assertNull(this.wiretap1.receive(1)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("hello"); + assertThat(this.wiretapChannel.receive(1)).isNull(); + assertThat(this.wiretap1.receive(1)).isNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java index 5313598f8f..0203c0bad8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.channel.interceptor; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -76,60 +72,60 @@ public class GlobalChannelInterceptorTests { ChannelInterceptor[] interceptors = channel.getChannelInterceptors() .toArray(new ChannelInterceptor[channel.getChannelInterceptors().size()]); if (channelName.equals("inputA")) { // 328741 - assertTrue(interceptors.length == 10); - assertEquals("interceptor-three", interceptors[0].toString()); - assertEquals("interceptor-two", interceptors[1].toString()); - assertEquals("interceptor-eight", interceptors[2].toString()); - assertEquals("interceptor-seven", interceptors[3].toString()); - assertEquals("interceptor-five", interceptors[4].toString()); - assertEquals("interceptor-six", interceptors[5].toString()); - assertEquals("interceptor-ten", interceptors[6].toString()); - assertEquals("interceptor-eleven", interceptors[7].toString()); - assertEquals("interceptor-four", interceptors[8].toString()); - assertEquals("interceptor-one", interceptors[9].toString()); + assertThat(interceptors.length == 10).isTrue(); + assertThat(interceptors[0].toString()).isEqualTo("interceptor-three"); + assertThat(interceptors[1].toString()).isEqualTo("interceptor-two"); + assertThat(interceptors[2].toString()).isEqualTo("interceptor-eight"); + assertThat(interceptors[3].toString()).isEqualTo("interceptor-seven"); + assertThat(interceptors[4].toString()).isEqualTo("interceptor-five"); + assertThat(interceptors[5].toString()).isEqualTo("interceptor-six"); + assertThat(interceptors[6].toString()).isEqualTo("interceptor-ten"); + assertThat(interceptors[7].toString()).isEqualTo("interceptor-eleven"); + assertThat(interceptors[8].toString()).isEqualTo("interceptor-four"); + assertThat(interceptors[9].toString()).isEqualTo("interceptor-one"); } else if (channelName.equals("inputB")) { - assertTrue(interceptors.length == 6); - assertEquals("interceptor-three", interceptors[0].toString()); - assertEquals("interceptor-two", interceptors[1].toString()); - assertEquals("interceptor-ten", interceptors[2].toString()); - assertEquals("interceptor-eleven", interceptors[3].toString()); - assertEquals("interceptor-four", interceptors[4].toString()); - assertEquals("interceptor-one", interceptors[5].toString()); + assertThat(interceptors.length == 6).isTrue(); + assertThat(interceptors[0].toString()).isEqualTo("interceptor-three"); + assertThat(interceptors[1].toString()).isEqualTo("interceptor-two"); + assertThat(interceptors[2].toString()).isEqualTo("interceptor-ten"); + assertThat(interceptors[3].toString()).isEqualTo("interceptor-eleven"); + assertThat(interceptors[4].toString()).isEqualTo("interceptor-four"); + assertThat(interceptors[5].toString()).isEqualTo("interceptor-one"); } else if (channelName.equals("foo")) { - assertTrue(interceptors.length == 6); - assertEquals("interceptor-two", interceptors[0].toString()); - assertEquals("interceptor-five", interceptors[1].toString()); - assertEquals("interceptor-ten", interceptors[2].toString()); - assertEquals("interceptor-eleven", interceptors[3].toString()); - assertEquals("interceptor-four", interceptors[4].toString()); - assertEquals("interceptor-one", interceptors[5].toString()); + assertThat(interceptors.length == 6).isTrue(); + assertThat(interceptors[0].toString()).isEqualTo("interceptor-two"); + assertThat(interceptors[1].toString()).isEqualTo("interceptor-five"); + assertThat(interceptors[2].toString()).isEqualTo("interceptor-ten"); + assertThat(interceptors[3].toString()).isEqualTo("interceptor-eleven"); + assertThat(interceptors[4].toString()).isEqualTo("interceptor-four"); + assertThat(interceptors[5].toString()).isEqualTo("interceptor-one"); } else if (channelName.equals("bar")) { - assertTrue(interceptors.length == 4); - assertEquals("interceptor-eight", interceptors[0].toString()); - assertEquals("interceptor-seven", interceptors[1].toString()); - assertEquals("interceptor-ten", interceptors[2].toString()); - assertEquals("interceptor-eleven", interceptors[3].toString()); + assertThat(interceptors.length == 4).isTrue(); + assertThat(interceptors[0].toString()).isEqualTo("interceptor-eight"); + assertThat(interceptors[1].toString()).isEqualTo("interceptor-seven"); + assertThat(interceptors[2].toString()).isEqualTo("interceptor-ten"); + assertThat(interceptors[3].toString()).isEqualTo("interceptor-eleven"); } else if (channelName.equals("baz")) { - assertTrue(interceptors.length == 2); - assertEquals("interceptor-ten", interceptors[0].toString()); - assertEquals("interceptor-eleven", interceptors[1].toString()); + assertThat(interceptors.length == 2).isTrue(); + assertThat(interceptors[0].toString()).isEqualTo("interceptor-ten"); + assertThat(interceptors[1].toString()).isEqualTo("interceptor-eleven"); } else if (channelName.equals("inputWithProxy")) { - assertTrue(interceptors.length == 6); + assertThat(interceptors.length == 6).isTrue(); } else if (channelName.equals("test")) { - assertNotNull(interceptors); - assertTrue(interceptors.length == 2); + assertThat(interceptors).isNotNull(); + assertThat(interceptors.length == 2).isTrue(); List interceptorNames = new ArrayList(); for (ChannelInterceptor interceptor : interceptors) { interceptorNames.add(interceptor.toString()); } - assertTrue(interceptorNames.contains("interceptor-ten")); - assertTrue(interceptorNames.contains("interceptor-eleven")); + assertThat(interceptorNames.contains("interceptor-ten")).isTrue(); + assertThat(interceptorNames.contains("interceptor-eleven")).isTrue(); } } } @@ -142,8 +138,8 @@ public class GlobalChannelInterceptorTests { for (ChannelInterceptor interceptor : channelInterceptors) { interceptorNames.add(interceptor.toString()); } - assertTrue(interceptorNames.contains("interceptor-ten")); - assertTrue(interceptorNames.contains("interceptor-eleven")); + assertThat(interceptorNames.contains("interceptor-ten")).isTrue(); + assertThat(interceptorNames.contains("interceptor-eleven")).isTrue(); } @Test @@ -154,9 +150,9 @@ public class GlobalChannelInterceptorTests { List channelInterceptors = testChannel.getChannelInterceptors(); - assertEquals(2, channelInterceptors.size()); - assertThat(channelInterceptors.get(0), instanceOf(SampleInterceptor.class)); - assertThat(channelInterceptors.get(0), instanceOf(SampleInterceptor.class)); + assertThat(channelInterceptors.size()).isEqualTo(2); + assertThat(channelInterceptors.get(0)).isInstanceOf(SampleInterceptor.class); + assertThat(channelInterceptors.get(0)).isInstanceOf(SampleInterceptor.class); } public static class SampleInterceptor implements ChannelInterceptor { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalWireTapTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalWireTapTests.java index 6efc5fc3d0..af5955ec1b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalWireTapTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalWireTapTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.interceptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -73,7 +71,7 @@ public class GlobalWireTapTests { Message message = new GenericMessage("hello"); this.channel.send(message); Message wireTapMessage = this.wiretapSingle.receive(100); - assertNotNull(wireTapMessage); + assertThat(wireTapMessage).isNotNull(); // There should be 5 messages on this channel: // 'channel', 'output', 'wiretapSingle', and too for 'unnamedGlobalWireTaps'. @@ -81,15 +79,15 @@ public class GlobalWireTapTests { int msgCount = 0; while (wireTapMessage != null) { msgCount++; - assertEquals(wireTapMessage.getPayload(), message.getPayload()); + assertThat(message.getPayload()).isEqualTo(wireTapMessage.getPayload()); wireTapMessage = this.wiretapAll.receive(100); } - assertEquals(5, msgCount); + assertThat(msgCount).isEqualTo(5); - assertNull(this.wiretapAll2.receive(1)); + assertThat(this.wiretapAll2.receive(1)).isNull(); - assertEquals(4, this.channel.getChannelInterceptors().size()); + assertThat(this.channel.getChannelInterceptors().size()).isEqualTo(4); } @Test @@ -99,18 +97,18 @@ public class GlobalWireTapTests { //This time no message on wiretapSingle Message wireTapMessage = wiretapSingle.receive(100); - assertNull(wireTapMessage); + assertThat(wireTapMessage).isNull(); //There should be two messages on this channel. One for 'channel' and one for 'output' wireTapMessage = wiretapAll.receive(100); int msgCount = 0; while (wireTapMessage != null) { msgCount++; - assertEquals(wireTapMessage.getPayload(), message.getPayload()); + assertThat(message.getPayload()).isEqualTo(wireTapMessage.getPayload()); wireTapMessage = wiretapAll.receive(100); } - assertEquals(2, msgCount); + assertThat(msgCount).isEqualTo(2); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ImplicitConsumerChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ImplicitConsumerChannelTests.java index 6072a03586..efa381aec9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ImplicitConsumerChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ImplicitConsumerChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,10 +16,7 @@ package org.springframework.integration.channel.interceptor; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -57,17 +54,17 @@ public class ImplicitConsumerChannelTests { public void testImplicit() { // used to fail to load AC (no channel 'bar') List barInterceptors = bar.getChannelInterceptors(); - assertEquals(2, barInterceptors.size()); - assertThat(barInterceptors.get(0), anyOf(instanceOf(Interceptor1.class), instanceOf(Interceptor2.class))); - assertThat(barInterceptors.get(1), anyOf(instanceOf(Interceptor1.class), instanceOf(Interceptor2.class))); + assertThat(barInterceptors.size()).isEqualTo(2); + assertThat(barInterceptors.get(0)).isInstanceOfAny(Interceptor1.class, Interceptor2.class); + assertThat(barInterceptors.get(1)).isInstanceOfAny(Interceptor1.class, Interceptor2.class); List fooInterceptors = foo.getChannelInterceptors(); - assertEquals(2, fooInterceptors.size()); - assertThat(fooInterceptors.get(0), anyOf(instanceOf(WireTap.class), instanceOf(Interceptor2.class))); - assertThat(fooInterceptors.get(1), anyOf(instanceOf(WireTap.class), instanceOf(Interceptor2.class))); + assertThat(fooInterceptors.size()).isEqualTo(2); + assertThat(fooInterceptors.get(0)).isInstanceOfAny(WireTap.class, Interceptor2.class); + assertThat(fooInterceptors.get(1)).isInstanceOfAny(WireTap.class, Interceptor2.class); List bazInterceptors = baz.getChannelInterceptors(); - assertEquals(2, bazInterceptors.size()); - assertThat(bazInterceptors.get(0), anyOf(instanceOf(WireTap.class), instanceOf(Interceptor1.class))); - assertThat(bazInterceptors.get(1), anyOf(instanceOf(WireTap.class), instanceOf(Interceptor1.class))); + assertThat(bazInterceptors.size()).isEqualTo(2); + assertThat(bazInterceptors.get(0)).isInstanceOfAny(WireTap.class, Interceptor1.class); + assertThat(bazInterceptors.get(1)).isInstanceOfAny(WireTap.class, Interceptor1.class); } public static class Interceptor1 implements ChannelInterceptor, VetoCapableInterceptor { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/MessageSelectingInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/MessageSelectingInterceptorTests.java index 0dfd2c5154..bd95e33616 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/MessageSelectingInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/MessageSelectingInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.interceptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.atomic.AtomicInteger; @@ -42,7 +41,7 @@ public class MessageSelectingInterceptorTests { MessageSelectingInterceptor interceptor = new MessageSelectingInterceptor(selector); QueueChannel channel = new QueueChannel(); channel.addInterceptor(interceptor); - assertTrue(channel.send(new GenericMessage<>("test1"))); + assertThat(channel.send(new GenericMessage<>("test1"))).isTrue(); } @Test(expected = MessageDeliveryException.class) @@ -63,8 +62,8 @@ public class MessageSelectingInterceptorTests { MessageSelectingInterceptor interceptor = new MessageSelectingInterceptor(selector1, selector2); QueueChannel channel = new QueueChannel(); channel.addInterceptor(interceptor); - assertTrue(channel.send(new GenericMessage<>("test1"))); - assertEquals(2, counter.get()); + assertThat(channel.send(new GenericMessage<>("test1"))).isTrue(); + assertThat(counter.get()).isEqualTo(2); } @Test @@ -85,8 +84,8 @@ public class MessageSelectingInterceptorTests { catch (MessageDeliveryException e) { exceptionThrown = true; } - assertTrue(exceptionThrown); - assertEquals(2, counter.get()); + assertThat(exceptionThrown).isTrue(); + assertThat(counter.get()).isEqualTo(2); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/WireTapTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/WireTapTests.java index aa322da428..d35c382395 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/WireTapTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/WireTapTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.channel.interceptor; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -42,10 +40,10 @@ public class WireTapTests { mainChannel.addInterceptor(new WireTap(secondaryChannel)); mainChannel.send(new GenericMessage<>("testing")); Message original = mainChannel.receive(0); - assertNotNull(original); + assertThat(original).isNotNull(); Message intercepted = secondaryChannel.receive(0); - assertNotNull(intercepted); - assertEquals(original, intercepted); + assertThat(intercepted).isNotNull(); + assertThat(intercepted).isEqualTo(original); } @Test @@ -55,9 +53,9 @@ public class WireTapTests { mainChannel.addInterceptor(new WireTap(secondaryChannel, new TestSelector(false))); mainChannel.send(new GenericMessage<>("testing")); Message original = mainChannel.receive(0); - assertNotNull(original); + assertThat(original).isNotNull(); Message intercepted = secondaryChannel.receive(0); - assertNull(intercepted); + assertThat(intercepted).isNull(); } @Test @@ -67,10 +65,10 @@ public class WireTapTests { mainChannel.addInterceptor(new WireTap(secondaryChannel, new TestSelector(true))); mainChannel.send(new GenericMessage<>("testing")); Message original = mainChannel.receive(0); - assertNotNull(original); + assertThat(original).isNotNull(); Message intercepted = secondaryChannel.receive(0); - assertNotNull(intercepted); - assertEquals(original, intercepted); + assertThat(intercepted).isNotNull(); + assertThat(intercepted).isEqualTo(original); } @Test(expected = IllegalArgumentException.class) @@ -83,14 +81,14 @@ public class WireTapTests { QueueChannel mainChannel = new QueueChannel(); QueueChannel secondaryChannel = new QueueChannel(); mainChannel.addInterceptor(new WireTap(secondaryChannel)); - assertNull(secondaryChannel.receive(0)); + assertThat(secondaryChannel.receive(0)).isNull(); Message message = new GenericMessage<>("testing"); mainChannel.send(message); Message original = mainChannel.receive(0); Message intercepted = secondaryChannel.receive(0); - assertNotNull(original); - assertNotNull(intercepted); - assertEquals(original, intercepted); + assertThat(original).isNotNull(); + assertThat(intercepted).isNotNull(); + assertThat(intercepted).isEqualTo(original); } @Test @@ -106,9 +104,9 @@ public class WireTapTests { Message intercepted = secondaryChannel.receive(0); Object originalAttribute = original.getHeaders().get(headerName); Object interceptedAttribute = intercepted.getHeaders().get(headerName); - assertNotNull(originalAttribute); - assertNotNull(interceptedAttribute); - assertEquals(originalAttribute, interceptedAttribute); + assertThat(originalAttribute).isNotNull(); + assertThat(interceptedAttribute).isNotNull(); + assertThat(interceptedAttribute).isEqualTo(originalAttribute); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/FluxMessageChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/FluxMessageChannelTests.java index 3016e2f3fb..9d4132ed83 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/FluxMessageChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/FluxMessageChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,7 @@ package org.springframework.integration.channel.reactive; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.isOneOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -88,14 +82,14 @@ public class FluxMessageChannelTests { for (int i = 0; i < 9; i++) { Message receive = replyChannel.receive(10000); - assertNotNull(receive); - assertThat(receive.getPayload(), isOneOf("0", "1", "2", "3", "4", "6", "7", "8", "9")); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isIn("0", "1", "2", "3", "4", "6", "7", "8", "9"); } - assertNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNull(); Message error = this.errorChannel.receive(0); - assertNotNull(error); - assertEquals(5, ((MessagingException) error.getPayload()).getFailedMessage().getPayload()); + assertThat(error).isNotNull(); + assertThat(((MessagingException) error.getPayload()).getFailedMessage().getPayload()).isEqualTo(5); } @Test @@ -112,8 +106,8 @@ public class FluxMessageChannelTests { this.queueChannel.send(new GenericMessage<>("foo")); this.queueChannel.send(new GenericMessage<>("bar")); - assertTrue(done.await(10, TimeUnit.SECONDS)); - assertThat(results, contains("FOO", "BAR")); + assertThat(done.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(results).containsExactly("FOO", "BAR"); } @Test @@ -134,9 +128,9 @@ public class FluxMessageChannelTests { flowRegistration.getInputChannel().send(new GenericMessage<>("foo")); - assertTrue(finishLatch.await(10, TimeUnit.SECONDS)); + assertThat(finishLatch.await(10, TimeUnit.SECONDS)).isTrue(); - assertTrue(TestUtils.getPropertyValue(flux, "publishers", Map.class).isEmpty()); + assertThat(TestUtils.getPropertyValue(flux, "publishers", Map.class).isEmpty()).isTrue(); flowRegistration.destroy(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java index 51a903e909..8574859051 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java @@ -16,13 +16,8 @@ package org.springframework.integration.channel.reactive; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; @@ -37,7 +32,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -92,9 +86,9 @@ public class ReactiveStreamsConsumerTests { testChannel.send(testMessage); } catch (Exception e) { - assertThat(e, instanceOf(MessageDeliveryException.class)); - assertThat(e.getCause(), instanceOf(IllegalStateException.class)); - assertThat(e.getMessage(), containsString("doesn't have subscribers to accept messages")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getCause()).isInstanceOf(IllegalStateException.class); + assertThat(e.getMessage()).contains("doesn't have subscribers to accept messages"); } reactiveConsumer.start(); @@ -102,8 +96,8 @@ public class ReactiveStreamsConsumerTests { Message testMessage2 = new GenericMessage<>("test2"); testChannel.send(testMessage2); - assertTrue(stopLatch.await(10, TimeUnit.SECONDS)); - assertThat(result, Matchers.>contains(testMessage, testMessage2)); + assertThat(stopLatch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(result).containsExactly(testMessage, testMessage2); } @@ -138,7 +132,7 @@ public class ReactiveStreamsConsumerTests { subscription.request(1); Message message = messages.poll(10, TimeUnit.SECONDS); - assertSame(testMessage, message); + assertThat(message).isSameAs(testMessage); reactiveConsumer.stop(); @@ -147,7 +141,7 @@ public class ReactiveStreamsConsumerTests { fail("MessageDeliveryException"); } catch (Exception e) { - assertThat(e, instanceOf(MessageDeliveryException.class)); + assertThat(e).isInstanceOf(MessageDeliveryException.class); } reactiveConsumer.start(); @@ -159,12 +153,12 @@ public class ReactiveStreamsConsumerTests { testChannel.send(testMessage); message = messages.poll(10, TimeUnit.SECONDS); - assertSame(testMessage, message); + assertThat(message).isSameAs(testMessage); verify(testSubscriber, never()).onError(any(Throwable.class)); verify(testSubscriber, never()).onComplete(); - assertTrue(messages.isEmpty()); + assertThat(messages.isEmpty()).isTrue(); } @Test @@ -198,7 +192,7 @@ public class ReactiveStreamsConsumerTests { subscription.request(1); Message message = messages.poll(10, TimeUnit.SECONDS); - assertSame(testMessage, message); + assertThat(message).isSameAs(testMessage); reactiveConsumer.stop(); @@ -217,15 +211,15 @@ public class ReactiveStreamsConsumerTests { testChannel.send(testMessage2); message = messages.poll(10, TimeUnit.SECONDS); - assertSame(testMessage, message); + assertThat(message).isSameAs(testMessage); message = messages.poll(10, TimeUnit.SECONDS); - assertSame(testMessage2, message); + assertThat(message).isSameAs(testMessage2); verify(testSubscriber, never()).onError(any(Throwable.class)); verify(testSubscriber, never()).onComplete(); - assertTrue(messages.isEmpty()); + assertThat(messages.isEmpty()).isTrue(); } @Test @@ -257,9 +251,9 @@ public class ReactiveStreamsConsumerTests { testChannel.send(testMessage); } catch (Exception e) { - assertThat(e, instanceOf(MessageDeliveryException.class)); - assertThat(e.getCause(), instanceOf(IllegalStateException.class)); - assertThat(e.getMessage(), containsString("doesn't have subscribers to accept messages")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getCause()).isInstanceOf(IllegalStateException.class); + assertThat(e.getMessage()).contains("doesn't have subscribers to accept messages"); } endpointFactoryBean.start(); @@ -269,9 +263,9 @@ public class ReactiveStreamsConsumerTests { testChannel.send(testMessage2); testChannel.send(testMessage2); - assertTrue(stopLatch.await(10, TimeUnit.SECONDS)); - assertThat(result.size(), equalTo(3)); - assertThat(result, Matchers.>contains(testMessage, testMessage2, testMessage2)); + assertThat(stopLatch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(result.size()).isEqualTo(3); + assertThat(result).containsExactly(testMessage, testMessage2, testMessage2); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java index 1d9126d097..28ac9a1393 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 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,25 +16,14 @@ package org.springframework.integration.channel.registry; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.lessThan; -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.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -65,6 +54,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Gary Russell + * @author Artem Bilan + * * @since 3.0 * */ @@ -105,13 +96,13 @@ public class HeaderChannelRegistryTests { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.input); Message reply = template.sendAndReceive(new GenericMessage("foo")); - assertNotNull(reply); - assertEquals("echo:foo", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("echo:foo"); String stringReplyChannel = reply.getHeaders().get("stringReplyChannel", String.class); assertThat(TestUtils.getPropertyValue( TestUtils.getPropertyValue(registry, "channels", Map.class) - .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis(), - lessThan(61000L)); + .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis()) + .isLessThan(61000L); } @Test @@ -119,13 +110,13 @@ public class HeaderChannelRegistryTests { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.inputTtl); Message reply = template.sendAndReceive(new GenericMessage("ttl")); - assertNotNull(reply); - assertEquals("echo:ttl", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("echo:ttl"); String stringReplyChannel = reply.getHeaders().get("stringReplyChannel", String.class); assertThat(TestUtils.getPropertyValue( TestUtils.getPropertyValue(registry, "channels", Map.class) - .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis(), - greaterThan(100000L)); + .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis()) + .isGreaterThan(100000L); } @Test @@ -136,36 +127,36 @@ public class HeaderChannelRegistryTests { .setHeader("channelTTL", 180000) .build(); Message reply = template.sendAndReceive(requestMessage); - assertNotNull(reply); - assertEquals("echo:ttl", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("echo:ttl"); String stringReplyChannel = reply.getHeaders().get("stringReplyChannel", String.class); assertThat(TestUtils.getPropertyValue( TestUtils.getPropertyValue(registry, "channels", Map.class) - .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis(), - allOf(greaterThan(160000L), lessThan(181000L))); + .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis()) + .isGreaterThan(160000L).isLessThan(181000L); // Now for Elvis... reply = template.sendAndReceive(new GenericMessage("ttl")); - assertNotNull(reply); - assertEquals("echo:ttl", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("echo:ttl"); stringReplyChannel = reply.getHeaders().get("stringReplyChannel", String.class); assertThat(TestUtils.getPropertyValue( TestUtils.getPropertyValue(registry, "channels", Map.class) - .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis(), - greaterThan(220000L)); + .get(stringReplyChannel), "expireAt", Long.class) - System.currentTimeMillis()) + .isGreaterThan(220000L); } @Test public void testReplaceGatewayWithNoReplyChannel() { String reply = this.gatewayNoReplyChannel.exchange("foo"); - assertNotNull(reply); - assertEquals("echo:foo", reply); + assertThat(reply).isNotNull(); + assertThat(reply).isEqualTo("echo:foo"); } @Test public void testReplaceGatewayWithExplicitReplyChannel() { String reply = this.gatewayExplicitReplyChannel.exchange("foo"); - assertNotNull(reply); - assertEquals("echo:foo", reply); + assertThat(reply).isNotNull(); + assertThat(reply).isEqualTo("echo:foo"); } /** @@ -177,10 +168,10 @@ public class HeaderChannelRegistryTests { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(this.inputPolled); Message reply = template.sendAndReceive(new GenericMessage("bar")); - assertNotNull(reply); - assertTrue(reply instanceof ErrorMessage); - assertNotNull(((ErrorMessage) reply).getOriginalMessage()); - assertThat(reply.getPayload(), not(instanceOf(MessagingExceptionWrapper.class))); + assertThat(reply).isNotNull(); + assertThat(reply instanceof ErrorMessage).isTrue(); + assertThat(((ErrorMessage) reply).getOriginalMessage()).isNotNull(); + assertThat(reply.getPayload()).isNotInstanceOf(MessagingExceptionWrapper.class); } @Test @@ -191,8 +182,8 @@ public class HeaderChannelRegistryTests { .build(); this.input.send(requestMessage); Message reply = alreadyAString.receive(0); - assertNotNull(reply); - assertEquals("echo:foo", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("echo:foo"); } @Test @@ -204,7 +195,7 @@ public class HeaderChannelRegistryTests { fail("expected exception"); } catch (Exception e) { - assertThat(e.getMessage(), Matchers.containsString("no output-channel or replyChannel")); + assertThat(e.getMessage()).contains("no output-channel or replyChannel"); } } @@ -217,7 +208,7 @@ public class HeaderChannelRegistryTests { while (n++ < 100 && registry.channelNameToChannel(id) != null) { Thread.sleep(100); } - assertNull(registry.channelNameToChannel(id)); + assertThat(registry.channelNameToChannel(id)).isNull(); registry.stop(); } @@ -226,8 +217,8 @@ public class HeaderChannelRegistryTests { BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(); BeanFactory beanFactory = mock(BeanFactory.class); when(beanFactory.getBean(IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME, - HeaderChannelRegistry.class)) - .thenReturn(mock(HeaderChannelRegistry.class)); + HeaderChannelRegistry.class)) + .thenReturn(mock(HeaderChannelRegistry.class)); doAnswer(invocation -> { throw new NoSuchBeanDefinitionException("bar"); }).when(beanFactory).getBean("foo", MessageChannel.class); @@ -237,8 +228,8 @@ public class HeaderChannelRegistryTests { fail("Expected exception"); } catch (DestinationResolutionException e) { - assertThat(e.getMessage(), - Matchers.containsString("failed to look up MessageChannel with name 'foo' in the BeanFactory.")); + assertThat(e.getMessage()).contains("failed to look up MessageChannel with name 'foo' in the BeanFactory" + + "."); } } @@ -255,9 +246,9 @@ public class HeaderChannelRegistryTests { fail("Expected exception"); } catch (DestinationResolutionException e) { - assertThat(e.getMessage(), - Matchers.containsString("failed to look up MessageChannel with name 'foo' in the BeanFactory " + - "(and there is no HeaderChannelRegistry present).")); + assertThat(e.getMessage()).contains("failed to look up MessageChannel with name 'foo' in the BeanFactory" + + " " + + "(and there is no HeaderChannelRegistry present)."); } } @@ -267,12 +258,12 @@ public class HeaderChannelRegistryTests { MessageChannel channel = new DirectChannel(); String foo = (String) registry.channelToChannelName(channel); Map map = TestUtils.getPropertyValue(registry, "channels", Map.class); - assertEquals(1, map.size()); - assertSame(channel, registry.channelNameToChannel(foo)); - assertEquals(1, map.size()); + assertThat(map.size()).isEqualTo(1); + assertThat(registry.channelNameToChannel(foo)).isSameAs(channel); + assertThat(map.size()).isEqualTo(1); registry.setRemoveOnGet(true); - assertSame(channel, registry.channelNameToChannel(foo)); - assertEquals(0, map.size()); + assertThat(registry.channelNameToChannel(foo)).isSameAs(channel); + assertThat(map.size()).isEqualTo(0); } @@ -280,10 +271,14 @@ public class HeaderChannelRegistryTests { @Override protected Object handleRequestMessage(Message requestMessage) { - assertThat(requestMessage.getHeaders().getReplyChannel(), - Matchers.anyOf(instanceOf(String.class), Matchers.nullValue())); - assertThat(requestMessage.getHeaders().getErrorChannel(), - Matchers.anyOf(instanceOf(String.class), Matchers.nullValue())); + assertThat(requestMessage.getHeaders().getReplyChannel()) + .satisfiesAnyOf( + replyChannel -> assertThat(replyChannel).isInstanceOf(String.class), + replyChannel -> assertThat(replyChannel).isNull()); + assertThat(requestMessage.getHeaders().getErrorChannel()) + .satisfiesAnyOf( + errorChannel -> assertThat(errorChannel).isInstanceOf(String.class), + errorChannel -> assertThat(errorChannel).isNull()); if (requestMessage.getPayload().equals("bar")) { throw new RuntimeException("intentional"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/CompositeCodecTests.java b/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/CompositeCodecTests.java index 25af8d052c..f11b20715c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/CompositeCodecTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/CompositeCodecTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 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,7 @@ package org.springframework.integration.codec.kryo; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.util.HashMap; @@ -49,7 +49,7 @@ public class CompositeCodecTests { SomeClassWithNoDefaultConstructors foo2 = this.codec.decode( this.codec.encode(foo), SomeClassWithNoDefaultConstructors.class); - assertEquals(foo, foo2); + assertThat(foo2).isEqualTo(foo); } static class SomeClassWithNoDefaultConstructors { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/FileKryoRegistrarTests.java b/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/FileKryoRegistrarTests.java index 23c8a5914b..cce7e9fc33 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/FileKryoRegistrarTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/FileKryoRegistrarTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 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,7 @@ package org.springframework.integration.codec.kryo; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; @@ -35,7 +35,7 @@ public class FileKryoRegistrarTests { PojoCodec pc = new PojoCodec(new FileKryoRegistrar()); File file = new File("/foo/bar"); File file2 = pc.decode(pc.encode(file), File.class); - assertEquals(file, file2); + assertThat(file2).isEqualTo(file); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/KryoCodecTests.java b/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/KryoCodecTests.java index eac302d37b..f49d205d12 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/KryoCodecTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/codec/kryo/KryoCodecTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 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,7 @@ package org.springframework.integration.codec.kryo; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayOutputStream; import java.io.File; @@ -26,10 +26,13 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; +import org.assertj.core.data.Offset; import org.junit.Test; /** * @author David Turanski + * @author Artem Bilan + * * @since 4.2 */ public class KryoCodecTests { @@ -43,7 +46,7 @@ public class KryoCodecTests { codec.encode(str, bos); String s2 = codec.decode(bos.toByteArray(), String.class); - assertEquals(str, s2); + assertThat(s2).isEqualTo(str); } @Test @@ -58,7 +61,7 @@ public class KryoCodecTests { FileInputStream fis = new FileInputStream(file); String s2 = codec.decode(fis, String.class); file.delete(); - assertEquals(str, s2); + assertThat(s2).isEqualTo(str); } @Test @@ -68,7 +71,7 @@ public class KryoCodecTests { ByteArrayOutputStream bos = new ByteArrayOutputStream(); codec.encode(foo, bos); Object foo2 = codec.decode(bos.toByteArray(), SomeClassWithNoDefaultConstructors.class); - assertEquals(foo, foo2); + assertThat(foo2).isEqualTo(foo); } @Test @@ -78,36 +81,36 @@ public class KryoCodecTests { ByteArrayOutputStream bos = new ByteArrayOutputStream(); codec.encode(true, bos); boolean b = codec.decode(bos.toByteArray(), Boolean.class); - assertEquals(true, b); + assertThat(b).isEqualTo(true); b = codec.decode(bos.toByteArray(), boolean.class); - assertEquals(true, b); + assertThat(b).isEqualTo(true); bos = new ByteArrayOutputStream(); codec.encode(3.14159, bos); double d = codec.decode(bos.toByteArray(), double.class); - assertEquals(3.14159, d, 0.00001); + assertThat(d).isCloseTo(3.14159, Offset.offset(0.00001)); bos = new ByteArrayOutputStream(); codec.encode(3.14159, bos); d = codec.decode(bos.toByteArray(), Double.class); - assertEquals(3.14159, d, 0.00001); + assertThat(d).isCloseTo(3.14159, Offset.offset(0.00001)); } @Test public void testMapSerialization() throws IOException { PojoCodec codec = new PojoCodec(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("one", 1); map.put("two", 2); ByteArrayOutputStream bos = new ByteArrayOutputStream(); codec.encode(map, bos); Map m2 = (Map) codec.decode(bos.toByteArray(), HashMap.class); - assertEquals(2, m2.size()); - assertEquals(1, m2.get("one")); - assertEquals(2, m2.get("two")); + assertThat(m2.size()).isEqualTo(2); + assertThat(m2.get("one")).isEqualTo(1); + assertThat(m2.get("two")).isEqualTo(2); } @Test @@ -120,8 +123,8 @@ public class KryoCodecTests { codec.encode(foo, bos); Foo foo2 = codec.decode(bos.toByteArray(), Foo.class); - assertEquals(1, foo2.get("one")); - assertEquals(2, foo2.get("two")); + assertThat(foo2.get("one")).isEqualTo(1); + assertThat(foo2.get("two")).isEqualTo(2); } static class SomeClassWithNoDefaultConstructors { @@ -158,7 +161,7 @@ public class KryoCodecTests { private Map map; Foo() { - map = new HashMap(); + this.map = new HashMap<>(); } public void put(Object key, Object value) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java index a893087fd1..4a3309ddd3 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,24 +16,14 @@ package org.springframework.integration.config; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -92,14 +82,15 @@ public class AggregatorParserTests { outboundMessages.forEach(input::send); - assertEquals("One and only one message must have been aggregated", 1, - aggregatorBean.getAggregatedMessages().size()); + assertThat(aggregatorBean.getAggregatedMessages().size()) + .as("One and only one message must have been aggregated").isEqualTo(1); Message aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1"); - assertEquals("The aggregated message payload is not correct", "123456789", aggregatedMessage.getPayload()); + assertThat(aggregatedMessage.getPayload()).as("The aggregated message payload is not correct") + .isEqualTo("123456789"); Object mbf = context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME); Object handler = context.getBean("aggregatorWithReference.handler"); - assertSame(mbf, TestUtils.getPropertyValue(handler, "outputProcessor.messageBuilderFactory")); - assertTrue(TestUtils.getPropertyValue(handler, "releaseLockBeforeSend", Boolean.class)); + assertThat(TestUtils.getPropertyValue(handler, "outputProcessor.messageBuilderFactory")).isSameAs(mbf); + assertThat(TestUtils.getPropertyValue(handler, "releaseLockBeforeSend", Boolean.class)).isTrue(); } @Test @@ -114,10 +105,10 @@ public class AggregatorParserTests { outboundMessages.forEach(input::send); - assertEquals(3, output.getQueueSize()); + assertThat(output.getQueueSize()).isEqualTo(3); output.purge(null); - assertFalse(TestUtils.getPropertyValue(context.getBean("aggregatorWithMGPReference.handler"), - "releaseLockBeforeSend", Boolean.class)); + assertThat(TestUtils.getPropertyValue(context.getBean("aggregatorWithMGPReference.handler"), + "releaseLockBeforeSend", Boolean.class)).isFalse(); } @Test @@ -132,7 +123,7 @@ public class AggregatorParserTests { outboundMessages.forEach(input::send); - assertEquals(3, output.getQueueSize()); + assertThat(output.getQueueSize()).isEqualTo(3); output.purge(null); } @@ -149,12 +140,12 @@ public class AggregatorParserTests { outboundMessages.forEach(input::send); - assertEquals("The aggregated message payload is not correct", "[123]", aggregatedMessage.get().getPayload() - .toString()); + assertThat(aggregatedMessage.get().getPayload() + .toString()).as("The aggregated message payload is not correct").isEqualTo("[123]"); Object mbf = context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME); Object handler = context.getBean("aggregatorWithExpressions.handler"); - assertSame(mbf, TestUtils.getPropertyValue(handler, "outputProcessor.messageBuilderFactory")); - assertTrue(TestUtils.getPropertyValue(handler, "expireGroupsUponTimeout", Boolean.class)); + assertThat(TestUtils.getPropertyValue(handler, "outputProcessor.messageBuilderFactory")).isSameAs(mbf); + assertThat(TestUtils.getPropertyValue(handler, "expireGroupsUponTimeout", Boolean.class)).isTrue(); } @Test @@ -165,40 +156,46 @@ public class AggregatorParserTests { MessageChannel outputChannel = (MessageChannel) context.getBean("outputChannel"); MessageChannel discardChannel = (MessageChannel) context.getBean("discardChannel"); Object consumer = new DirectFieldAccessor(endpoint).getPropertyValue("handler"); - assertThat(consumer, is(instanceOf(AggregatingMessageHandler.class))); + assertThat(consumer).isInstanceOf(AggregatingMessageHandler.class); DirectFieldAccessor accessor = new DirectFieldAccessor(consumer); Object handlerMethods = new DirectFieldAccessor(new DirectFieldAccessor(new DirectFieldAccessor(accessor .getPropertyValue("outputProcessor")).getPropertyValue("processor")).getPropertyValue("delegate")) .getPropertyValue("handlerMethods"); - assertNull(handlerMethods); + assertThat(handlerMethods).isNull(); Object handlerMethod = new DirectFieldAccessor(new DirectFieldAccessor(new DirectFieldAccessor(accessor .getPropertyValue("outputProcessor")).getPropertyValue("processor")).getPropertyValue("delegate")) .getPropertyValue("handlerMethod"); - assertTrue(handlerMethod.toString().contains("createSingleMessageFromGroup")); - assertEquals("The AggregatorEndpoint is not injected with the appropriate ReleaseStrategy instance", - releaseStrategy, accessor.getPropertyValue("releaseStrategy")); - assertEquals("The AggregatorEndpoint is not injected with the appropriate CorrelationStrategy instance", - correlationStrategy, accessor.getPropertyValue("correlationStrategy")); - assertEquals("The AggregatorEndpoint is not injected with the appropriate output channel", - outputChannel, accessor.getPropertyValue("outputChannel")); - assertEquals("The AggregatorEndpoint is not injected with the appropriate discard channel", - discardChannel, accessor.getPropertyValue("discardChannel")); - assertEquals("The AggregatorEndpoint is not set with the appropriate timeout value", 86420000L, - TestUtils.getPropertyValue(consumer, "messagingTemplate.sendTimeout")); - assertEquals( - "The AggregatorEndpoint is not configured with the appropriate 'send partial results on timeout' flag", - true, accessor.getPropertyValue("sendPartialResultOnExpiry")); - assertFalse(TestUtils.getPropertyValue(consumer, "expireGroupsUponTimeout", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(consumer, "expireGroupsUponCompletion", Boolean.class)); - assertEquals(123L, TestUtils.getPropertyValue(consumer, "minimumTimeoutForEmptyGroups")); - assertEquals("456", TestUtils.getPropertyValue(consumer, "groupTimeoutExpression", Expression.class) - .getExpressionString()); - assertSame(this.context.getBean(LockRegistry.class), TestUtils.getPropertyValue(consumer, "lockRegistry")); - assertSame(this.context.getBean("scheduler"), TestUtils.getPropertyValue(consumer, "taskScheduler")); - assertSame(this.context.getBean("store"), TestUtils.getPropertyValue(consumer, "messageStore")); - assertEquals(5, TestUtils.getPropertyValue(consumer, "order")); - assertNotNull(TestUtils.getPropertyValue(consumer, "forceReleaseAdviceChain")); - assertFalse(TestUtils.getPropertyValue(consumer, "popSequence", Boolean.class)); + assertThat(handlerMethod.toString().contains("createSingleMessageFromGroup")).isTrue(); + assertThat(accessor.getPropertyValue("releaseStrategy")) + .as("The AggregatorEndpoint is not injected with the appropriate ReleaseStrategy instance") + .isEqualTo(releaseStrategy); + assertThat(accessor.getPropertyValue("correlationStrategy")) + .as("The AggregatorEndpoint is not injected with the appropriate CorrelationStrategy instance") + .isEqualTo(correlationStrategy); + assertThat(accessor.getPropertyValue("outputChannel")) + .as("The AggregatorEndpoint is not injected with the appropriate output channel") + .isEqualTo(outputChannel); + assertThat(accessor.getPropertyValue("discardChannel")) + .as("The AggregatorEndpoint is not injected with the appropriate discard channel") + .isEqualTo(discardChannel); + assertThat(TestUtils.getPropertyValue(consumer, "messagingTemplate.sendTimeout")) + .as("The AggregatorEndpoint is not set with the appropriate timeout value").isEqualTo(86420000L); + assertThat(accessor.getPropertyValue("sendPartialResultOnExpiry")) + .as("The AggregatorEndpoint is not configured with the appropriate 'send partial results on timeout' " + + "flag") + .isEqualTo(true); + assertThat(TestUtils.getPropertyValue(consumer, "expireGroupsUponTimeout", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(consumer, "expireGroupsUponCompletion", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(consumer, "minimumTimeoutForEmptyGroups")).isEqualTo(123L); + assertThat(TestUtils.getPropertyValue(consumer, "groupTimeoutExpression", Expression.class) + .getExpressionString()).isEqualTo("456"); + assertThat(TestUtils.getPropertyValue(consumer, "lockRegistry")) + .isSameAs(this.context.getBean(LockRegistry.class)); + assertThat(TestUtils.getPropertyValue(consumer, "taskScheduler")).isSameAs(this.context.getBean("scheduler")); + assertThat(TestUtils.getPropertyValue(consumer, "messageStore")).isSameAs(this.context.getBean("store")); + assertThat(TestUtils.getPropertyValue(consumer, "order")).isEqualTo(5); + assertThat(TestUtils.getPropertyValue(consumer, "forceReleaseAdviceChain")).isNotNull(); + assertThat(TestUtils.getPropertyValue(consumer, "popSequence", Boolean.class)).isFalse(); } @Test @@ -211,10 +208,10 @@ public class AggregatorParserTests { outboundMessages.forEach(input::send); PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); Message response = outputChannel.receive(10); - Assert.assertEquals(6L, response.getPayload()); + assertThat(response.getPayload()).isEqualTo(6L); Object mbf = context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME); Object handler = context.getBean("aggregatorWithReferenceAndMethod.handler"); - assertSame(mbf, TestUtils.getPropertyValue(handler, "outputProcessor.messageBuilderFactory")); + assertThat(TestUtils.getPropertyValue(handler, "outputProcessor.messageBuilderFactory")).isSameAs(mbf); } @Test @@ -224,7 +221,7 @@ public class AggregatorParserTests { fail("Expected exception"); } catch (BeanCreationException e) { - assertThat(e.getMessage(), containsString("Adder] has no eligible methods")); + assertThat(e.getMessage()).contains("Adder] has no eligible methods"); } } @@ -235,7 +232,7 @@ public class AggregatorParserTests { fail("Expected exception"); } catch (BeanCreationException e) { - assertThat(e.getMessage(), containsString("No bean named 'testReleaseStrategy' available")); + assertThat(e.getMessage()).contains("No bean named 'testReleaseStrategy' available"); } } @@ -246,23 +243,23 @@ public class AggregatorParserTests { EventDrivenConsumer endpoint = this.context.getBean("aggregatorWithPojoReleaseStrategy", EventDrivenConsumer.class); ReleaseStrategy releaseStrategy = TestUtils.getPropertyValue(endpoint, "handler.releaseStrategy", ReleaseStrategy.class); - Assert.assertTrue(releaseStrategy instanceof MethodInvokingReleaseStrategy); + assertThat(releaseStrategy instanceof MethodInvokingReleaseStrategy).isTrue(); MessagingMethodInvokerHelper methodInvokerHelper = TestUtils.getPropertyValue(releaseStrategy, "adapter.delegate", MessagingMethodInvokerHelper.class); Object handlerMethods = TestUtils.getPropertyValue(methodInvokerHelper, "handlerMethods"); - assertNull(handlerMethods); + assertThat(handlerMethods).isNull(); Object handlerMethod = TestUtils.getPropertyValue(methodInvokerHelper, "handlerMethod"); - assertTrue(handlerMethod.toString().contains("checkCompleteness")); + assertThat(handlerMethod.toString().contains("checkCompleteness")).isTrue(); input.send(createMessage(1L, "correlationId", 4, 0, null)); input.send(createMessage(2L, "correlationId", 4, 1, null)); input.send(createMessage(3L, "correlationId", 4, 2, null)); PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); Message reply = outputChannel.receive(0); - Assert.assertNull(reply); + assertThat(reply).isNull(); input.send(createMessage(5L, "correlationId", 4, 3, null)); reply = outputChannel.receive(0); - Assert.assertNotNull(reply); - assertEquals(11L, reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo(11L); } @Test // see INT-2011 @@ -271,23 +268,23 @@ public class AggregatorParserTests { EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("aggregatorWithPojoReleaseStrategyAsCollection"); ReleaseStrategy releaseStrategy = (ReleaseStrategy) new DirectFieldAccessor(new DirectFieldAccessor(endpoint) .getPropertyValue("handler")).getPropertyValue("releaseStrategy"); - Assert.assertTrue(releaseStrategy instanceof MethodInvokingReleaseStrategy); + assertThat(releaseStrategy instanceof MethodInvokingReleaseStrategy).isTrue(); DirectFieldAccessor releaseStrategyAccessor = new DirectFieldAccessor(new DirectFieldAccessor(new DirectFieldAccessor(releaseStrategy) .getPropertyValue("adapter")).getPropertyValue("delegate")); Object handlerMethods = releaseStrategyAccessor.getPropertyValue("handlerMethods"); - assertNull(handlerMethods); + assertThat(handlerMethods).isNull(); Object handlerMethod = releaseStrategyAccessor.getPropertyValue("handlerMethod"); - assertTrue(handlerMethod.toString().contains("checkCompleteness")); + assertThat(handlerMethod.toString().contains("checkCompleteness")).isTrue(); input.send(createMessage(1L, "correlationId", 4, 0, null)); input.send(createMessage(2L, "correlationId", 4, 1, null)); input.send(createMessage(3L, "correlationId", 4, 2, null)); PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); Message reply = outputChannel.receive(0); - Assert.assertNull(reply); + assertThat(reply).isNull(); input.send(createMessage(5L, "correlationId", 4, 3, null)); reply = outputChannel.receive(0); - Assert.assertNotNull(reply); - assertEquals(11L, reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo(11L); } @Test @@ -297,7 +294,7 @@ public class AggregatorParserTests { fail("Expected exception"); } catch (BeanCreationException e) { - assertThat(e.getMessage(), containsString("TestReleaseStrategy] has no eligible methods")); + assertThat(e.getMessage()).contains("TestReleaseStrategy] has no eligible methods"); } } @@ -306,15 +303,17 @@ public class AggregatorParserTests { EventDrivenConsumer aggregatorConsumer = (EventDrivenConsumer) context.getBean("aggregatorWithExpressionsAndPojoAggregator"); AggregatingMessageHandler aggregatingMessageHandler = (AggregatingMessageHandler) TestUtils.getPropertyValue(aggregatorConsumer, "handler"); MethodInvokingMessageGroupProcessor messageGroupProcessor = (MethodInvokingMessageGroupProcessor) TestUtils.getPropertyValue(aggregatingMessageHandler, "outputProcessor"); - Object messageGroupProcessorTargetObject = TestUtils.getPropertyValue(messageGroupProcessor, "processor.delegate.targetObject"); - assertSame(context.getBean("aggregatorBean"), messageGroupProcessorTargetObject); + Object messageGroupProcessorTargetObject = TestUtils.getPropertyValue(messageGroupProcessor, "processor" + + ".delegate.targetObject"); + assertThat(messageGroupProcessorTargetObject).isSameAs(context.getBean("aggregatorBean")); ReleaseStrategy releaseStrategy = (ReleaseStrategy) TestUtils.getPropertyValue(aggregatingMessageHandler, "releaseStrategy"); CorrelationStrategy correlationStrategy = (CorrelationStrategy) TestUtils.getPropertyValue(aggregatingMessageHandler, "correlationStrategy"); - Long minimumTimeoutForEmptyGroups = TestUtils.getPropertyValue(aggregatingMessageHandler, "minimumTimeoutForEmptyGroups", Long.class); + Long minimumTimeoutForEmptyGroups = TestUtils.getPropertyValue(aggregatingMessageHandler, + "minimumTimeoutForEmptyGroups", Long.class); - assertTrue(ExpressionEvaluatingReleaseStrategy.class.equals(releaseStrategy.getClass())); - assertTrue(ExpressionEvaluatingCorrelationStrategy.class.equals(correlationStrategy.getClass())); - assertEquals(60000L, minimumTimeoutForEmptyGroups.longValue()); + assertThat(ExpressionEvaluatingReleaseStrategy.class.equals(releaseStrategy.getClass())).isTrue(); + assertThat(ExpressionEvaluatingCorrelationStrategy.class.equals(correlationStrategy.getClass())).isTrue(); + assertThat(minimumTimeoutForEmptyGroups.longValue()).isEqualTo(60000L); } @Test @@ -323,8 +322,8 @@ public class AggregatorParserTests { new ClassPathXmlApplicationContext("aggregatorParserFailTests.xml", this.getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), containsString( - "Exactly one of the 'release-strategy' or 'release-strategy-expression' attribute is allowed.")); + assertThat(e.getMessage()) + .contains("Exactly one of the 'release-strategy' or 'release-strategy-expression' attribute is allowed."); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithCorrelationStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithCorrelationStrategyTests.java index cc0040b32f..0fe09c4723 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithCorrelationStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithCorrelationStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,12 +16,10 @@ package org.springframework.integration.config; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -97,9 +95,9 @@ public class AggregatorWithCorrelationStrategyTests { private void receiveAndCompare(PollableChannel outputChannel, String... expectedValues) { Message message = outputChannel.receive(500); - Assert.assertNotNull(message); + assertThat(message).isNotNull(); for (String expectedValue : expectedValues) { - assertThat((String) message.getPayload(), containsString(expectedValue)); + assertThat((String) message.getPayload()).contains(expectedValue); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java index 1bbfcf68e7..33e1b5c56a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -58,15 +58,16 @@ public class AggregatorWithMessageStoreParserTests { @DirtiesContext public void testAggregation() { input.send(createMessage("123", "id1", 3, 1, null)); - assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); + assertThat(messageGroupStore.getMessageGroup("id1").size()).isEqualTo(1); input.send(createMessage("789", "id1", 3, 3, null)); - assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); + assertThat(messageGroupStore.getMessageGroup("id1").size()).isEqualTo(2); input.send(createMessage("456", "id1", 3, 2, null)); - assertEquals("One and only one message should have been aggregated", 1, aggregatorBean - .getAggregatedMessages().size()); + assertThat(aggregatorBean + .getAggregatedMessages().size()).as("One and only one message should have been aggregated") + .isEqualTo(1); Message aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1"); - assertEquals("The aggregated message payload is not correct", "123456789", aggregatedMessage - .getPayload()); + assertThat(aggregatedMessage + .getPayload()).as("The aggregated message payload is not correct").isEqualTo("123456789"); } @@ -74,15 +75,16 @@ public class AggregatorWithMessageStoreParserTests { @DirtiesContext public void testExpiry() { input.send(createMessage("123", "id1", 3, 1, null)); - assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); + assertThat(messageGroupStore.getMessageGroup("id1").size()).isEqualTo(1); input.send(createMessage("456", "id1", 3, 2, null)); - assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); + assertThat(messageGroupStore.getMessageGroup("id1").size()).isEqualTo(2); this.controlBusChannel.send(new GenericMessage("@messageStore.expireMessageGroups(-10000)")); - assertEquals("One and only one message should have been aggregated", 1, aggregatorBean - .getAggregatedMessages().size()); + assertThat(aggregatorBean + .getAggregatedMessages().size()).as("One and only one message should have been aggregated") + .isEqualTo(1); Message aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1"); - assertEquals("The aggregated message payload is not correct", "123456", aggregatedMessage - .getPayload()); + assertThat(aggregatedMessage + .getPayload()).as("The aggregated message payload is not correct").isEqualTo("123456"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java index aad5f291ff..4f3ae916fc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,15 +16,8 @@ package org.springframework.integration.config; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -34,8 +27,6 @@ import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; -import org.hamcrest.Factory; -import org.hamcrest.Matcher; import org.junit.Test; import org.junit.runner.RunWith; @@ -58,9 +49,9 @@ import org.springframework.integration.handler.LoggingHandler; import org.springframework.integration.handler.MessageHandlerChain; import org.springframework.integration.handler.ReplyRequiredException; import org.springframework.integration.handler.ServiceActivatingHandler; -import org.springframework.integration.message.MessageMatcher; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.json.JsonObjectMapper; +import org.springframework.integration.test.predicate.MessagePredicate; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.transformer.MessageTransformingHandler; import org.springframework.integration.transformer.ObjectToMapTransformer; @@ -174,18 +165,13 @@ public class ChainParserTests { public static Message successMessage = MessageBuilder.withPayload("success").build(); - @Factory - public static Matcher> sameExceptImmutableHeaders(Message expected) { - return new MessageMatcher(expected); - } - @Test public void chainWithAcceptingFilter() { Message message = MessageBuilder.withPayload("test").build(); this.filterInput.send(message); Message reply = this.output.receive(1000); - assertNotNull(reply); - assertEquals("foo", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("foo"); } @Test @@ -193,7 +179,7 @@ public class ChainParserTests { Message message = MessageBuilder.withPayload(123).build(); this.filterInput.send(message); Message reply = this.output.receive(0); - assertNull(reply); + assertThat(reply).isNull(); } @Test @@ -201,11 +187,11 @@ public class ChainParserTests { Message message = MessageBuilder.withPayload(123).build(); this.headerEnricherInput.send(message); Message reply = this.replyOutput.receive(1000); - assertNotNull(reply); - assertEquals("foo", reply.getPayload()); - assertEquals("ABC", new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); - assertEquals("XYZ", reply.getHeaders().get("testValue")); - assertEquals(123, reply.getHeaders().get("testRef")); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("foo"); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()).isEqualTo("ABC"); + assertThat(reply.getHeaders().get("testValue")).isEqualTo("XYZ"); + assertThat(reply.getHeaders().get("testRef")).isEqualTo(123); } @Test @@ -213,8 +199,8 @@ public class ChainParserTests { Message message = MessageBuilder.withPayload("test").build(); this.pollableInput1.send(message); Message reply = this.output.receive(3000); - assertNotNull(reply); - assertEquals("foo", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("foo"); } @Test @@ -222,76 +208,76 @@ public class ChainParserTests { Message message = MessageBuilder.withPayload("test").build(); this.pollableInput2.send(message); Message reply = this.output.receive(3000); - assertNotNull(reply); - assertEquals("foo", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("foo"); } @Test - public void chainHandlerBean() throws Exception { + public void chainHandlerBean() { Message message = MessageBuilder.withPayload("test").build(); this.beanInput.send(message); Message reply = this.output.receive(3000); - assertNotNull(reply); - assertThat(reply, sameExceptImmutableHeaders(successMessage)); + assertThat(reply).isNotNull(); + assertThat(reply).matches(new MessagePredicate(successMessage)); } @SuppressWarnings("rawtypes") @Test - public void chainNestingAndAggregation() throws Exception { + public void chainNestingAndAggregation() { Message message = MessageBuilder.withPayload("test").setCorrelationId(1).setSequenceSize(1).build(); this.aggregatorInput.send(message); Message reply = this.output.receive(3000); - assertNotNull(reply); - assertEquals("foo", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("foo"); } @Test - public void chainWithPayloadTypeRouter() throws Exception { + public void chainWithPayloadTypeRouter() { Message message1 = MessageBuilder.withPayload("test").build(); Message message2 = MessageBuilder.withPayload(123).build(); this.payloadTypeRouterInput.send(message1); this.payloadTypeRouterInput.send(message2); Message reply1 = this.strings.receive(1000); Message reply2 = this.numbers.receive(1000); - assertNotNull(reply1); - assertNotNull(reply2); - assertEquals("test", reply1.getPayload()); - assertEquals(123, reply2.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("test"); + assertThat(reply2.getPayload()).isEqualTo(123); } @Test // INT-2315 - public void chainWithHeaderValueRouter() throws Exception { + public void chainWithHeaderValueRouter() { Message message1 = MessageBuilder.withPayload("test").setHeader("routingHeader", "strings").build(); Message message2 = MessageBuilder.withPayload(123).setHeader("routingHeader", "numbers").build(); this.headerValueRouterInput.send(message1); this.headerValueRouterInput.send(message2); Message reply1 = this.strings.receive(1000); Message reply2 = this.numbers.receive(1000); - assertNotNull(reply1); - assertNotNull(reply2); - assertEquals("test", reply1.getPayload()); - assertEquals(123, reply2.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("test"); + assertThat(reply2.getPayload()).isEqualTo(123); } @Test // INT-2315 - public void chainWithHeaderValueRouterWithMapping() throws Exception { + public void chainWithHeaderValueRouterWithMapping() { Message message1 = MessageBuilder.withPayload("test").setHeader("routingHeader", "isString").build(); Message message2 = MessageBuilder.withPayload(123).setHeader("routingHeader", "isNumber").build(); this.headerValueRouterWithMappingInput.send(message1); this.headerValueRouterWithMappingInput.send(message2); Message reply1 = this.strings.receive(0); Message reply2 = this.numbers.receive(0); - assertNotNull(reply1); - assertNotNull(reply2); - assertEquals("test", reply1.getPayload()); - assertEquals(123, reply2.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("test"); + assertThat(reply2.getPayload()).isEqualTo(123); } @Test // INT-1165 public void chainWithSendTimeout() { long sendTimeout = TestUtils.getPropertyValue(this.chainWithSendTimeout, "messagingTemplate.sendTimeout", Long.class); - assertEquals(9876, sendTimeout); + assertThat(sendTimeout).isEqualTo(9876); } @Test //INT-1622 @@ -299,19 +285,19 @@ public class ChainParserTests { Message message = MessageBuilder.withPayload("test").build(); this.claimCheckInput.send(message); Message reply = this.claimCheckOutput.receive(0); - assertEquals(message.getPayload(), reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo(message.getPayload()); } @Test //INT-2275 public void chainWithOutboundChannelAdapter() { this.outboundChannelAdapterChannel.send(successMessage); - assertSame(successMessage, testConsumer.getLastMessage()); + assertThat(testConsumer.getLastMessage()).isSameAs(successMessage); } @Test //INT-2275, INT-2958 public void chainWithLoggingChannelAdapter() { Log logger = mock(Log.class); - final AtomicReference log = new AtomicReference(); + final AtomicReference log = new AtomicReference<>(); when(logger.isWarnEnabled()).thenReturn(true); doAnswer(invocation -> { log.set(invocation.getArgument(0)); @@ -321,13 +307,13 @@ public class ChainParserTests { @SuppressWarnings("unchecked") List handlers = TestUtils.getPropertyValue(this.logChain, "handlers", List.class); MessageHandler handler = handlers.get(2); - assertTrue(handler instanceof LoggingHandler); + assertThat(handler instanceof LoggingHandler).isTrue(); DirectFieldAccessor dfa = new DirectFieldAccessor(handler); dfa.setPropertyValue("messageLogger", logger); this.loggingChannelAdapterChannel.send(MessageBuilder.withPayload(new byte[] { 116, 101, 115, 116 }).build()); - assertNotNull(log.get()); - assertEquals("TEST", log.get()); + assertThat(log.get()).isNotNull(); + assertThat(log.get()).isEqualTo("TEST"); } @Test(expected = BeanCreationException.class) //INT-2275 @@ -338,9 +324,9 @@ public class ChainParserTests { fail("BeanCreationException is expected!"); } catch (BeansException e) { - assertEquals(IllegalArgumentException.class, e.getCause().getClass()); - assertTrue(e.getMessage().contains("output channel was provided")); - assertTrue(e.getMessage().contains("does not implement the MessageProducer")); + assertThat(e.getCause().getClass()).isEqualTo(IllegalArgumentException.class); + assertThat(e.getMessage()).contains("output channel was provided"); + assertThat(e.getMessage()).contains("does not implement the MessageProducer"); throw e; } } @@ -350,100 +336,134 @@ public class ChainParserTests { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "ChainParserSmartLifecycleAttributesTest.xml", this.getClass()); AbstractEndpoint chainEndpoint = ctx.getBean("chain", AbstractEndpoint.class); - assertEquals(false, chainEndpoint.isAutoStartup()); - assertEquals(256, chainEndpoint.getPhase()); + assertThat(chainEndpoint.isAutoStartup()).isEqualTo(false); + assertThat(chainEndpoint.getPhase()).isEqualTo(256); MessageHandlerChain handlerChain = ctx.getBean("chain.handler", MessageHandlerChain.class); - assertEquals(3000L, TestUtils.getPropertyValue(handlerChain, "messagingTemplate.sendTimeout")); - assertEquals(false, TestUtils.getPropertyValue(handlerChain, "running")); + assertThat(TestUtils.getPropertyValue(handlerChain, "messagingTemplate.sendTimeout")).isEqualTo(3000L); + assertThat(TestUtils.getPropertyValue(handlerChain, "running")).isEqualTo(false); //INT-3108 MessageHandler serviceActivator = ctx.getBean("chain$child.sa-within-chain.handler", MessageHandler.class); - assertTrue(TestUtils.getPropertyValue(serviceActivator, "requiresReply", Boolean.class)); + assertThat(TestUtils.getPropertyValue(serviceActivator, "requiresReply", Boolean.class)).isTrue(); ctx.close(); } @Test public void testInt2755SubComponentsIdSupport() { - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1.handler")); - assertTrue(this.beanFactory.containsBean("filterChain$child.filterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("filterChain$child.serviceActivatorWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain$child.aggregatorWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain$child.nestedChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain$child.nestedChain$child.filterWithinNestedChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain$child.nestedChain$child.doubleNestedChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain$child.nestedChain$child.doubleNestedChain$child.filterWithinDoubleNestedChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain2.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain2$child.aggregatorWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain2$child.nestedChain.handler")); - assertTrue(this.beanFactory.containsBean("aggregatorChain2$child.nestedChain$child.filterWithinNestedChain.handler")); - assertTrue(this.beanFactory.containsBean("payloadTypeRouterChain$child.payloadTypeRouterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("headerValueRouterChain$child.headerValueRouterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("chainWithClaimChecks$child.claimCheckInWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("chainWithClaimChecks$child.claimCheckOutWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("outboundChain$child.outboundChannelAdapterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("logChain$child.transformerWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("logChain$child.loggingChannelAdapterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.splitterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.resequencerWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.enricherWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.headerFilterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.payloadSerializingTransformerWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.payloadDeserializingTransformerWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.gatewayWithinChain.handler")); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("filterChain$child.filterWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("filterChain$child.serviceActivatorWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("aggregatorChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("aggregatorChain$child.aggregatorWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("aggregatorChain$child.nestedChain.handler")).isTrue(); + assertThat(this.beanFactory + .containsBean("aggregatorChain$child.nestedChain$child.filterWithinNestedChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("aggregatorChain$child.nestedChain$child.doubleNestedChain.handler")) + .isTrue(); + assertThat(this.beanFactory + .containsBean("aggregatorChain$child.nestedChain$child.doubleNestedChain$child" + + ".filterWithinDoubleNestedChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("aggregatorChain2.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("aggregatorChain2$child.aggregatorWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("aggregatorChain2$child.nestedChain.handler")).isTrue(); + assertThat(this.beanFactory + .containsBean("aggregatorChain2$child.nestedChain$child.filterWithinNestedChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("payloadTypeRouterChain$child.payloadTypeRouterWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("headerValueRouterChain$child.headerValueRouterWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("chainWithClaimChecks$child.claimCheckInWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("chainWithClaimChecks$child.claimCheckOutWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("outboundChain$child.outboundChannelAdapterWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("logChain$child.transformerWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("logChain$child.loggingChannelAdapterWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1$child.splitterWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1$child.resequencerWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1$child.enricherWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1$child.headerFilterWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory + .containsBean("subComponentsIdSupport1$child.payloadSerializingTransformerWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory + .containsBean("subComponentsIdSupport1$child.payloadDeserializingTransformerWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1$child.gatewayWithinChain.handler")).isTrue(); //INT-3117 - GatewayProxyFactoryBean gatewayProxyFactoryBean = this.beanFactory.getBean("&subComponentsIdSupport1$child.gatewayWithinChain.handler", + GatewayProxyFactoryBean gatewayProxyFactoryBean = this.beanFactory.getBean("&subComponentsIdSupport1$child" + + ".gatewayWithinChain.handler", GatewayProxyFactoryBean.class); - assertEquals("strings", TestUtils.getPropertyValue(gatewayProxyFactoryBean, "defaultRequestChannelName")); - assertEquals("numbers", TestUtils.getPropertyValue(gatewayProxyFactoryBean, "defaultReplyChannelName")); - assertEquals(1000L, TestUtils - .getPropertyValue(gatewayProxyFactoryBean, "defaultRequestTimeout", Expression.class).getValue()); - assertEquals(100L, TestUtils - .getPropertyValue(gatewayProxyFactoryBean, "defaultReplyTimeout", Expression.class).getValue()); + assertThat(TestUtils.getPropertyValue(gatewayProxyFactoryBean, "defaultRequestChannelName")) + .isEqualTo("strings"); + assertThat(TestUtils.getPropertyValue(gatewayProxyFactoryBean, "defaultReplyChannelName")).isEqualTo( + "numbers"); + assertThat(TestUtils + .getPropertyValue(gatewayProxyFactoryBean, "defaultRequestTimeout", Expression.class).getValue()) + .isEqualTo(1000L); + assertThat(TestUtils + .getPropertyValue(gatewayProxyFactoryBean, "defaultReplyTimeout", Expression.class).getValue()) + .isEqualTo(100L); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.objectToStringTransformerWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.objectToMapTransformerWithinChain.handler")); + assertThat(this.beanFactory + .containsBean("subComponentsIdSupport1$child.objectToStringTransformerWithinChain.handler")).isTrue(); + assertThat(this.beanFactory + .containsBean("subComponentsIdSupport1$child.objectToMapTransformerWithinChain.handler")).isTrue(); - Object transformerHandler = this.beanFactory.getBean("subComponentsIdSupport1$child.objectToMapTransformerWithinChain.handler"); + Object transformerHandler = this.beanFactory.getBean( + "subComponentsIdSupport1$child.objectToMapTransformerWithinChain.handler"); Object transformer = TestUtils.getPropertyValue(transformerHandler, "transformer"); - assertThat(transformer, instanceOf(ObjectToMapTransformer.class)); - assertFalse(TestUtils.getPropertyValue(transformer, "shouldFlattenKeys", Boolean.class)); - assertSame(this.beanFactory.getBean(JsonObjectMapper.class), - TestUtils.getPropertyValue(transformer, "jsonObjectMapper")); + assertThat(transformer).isInstanceOf(ObjectToMapTransformer.class); + assertThat(TestUtils.getPropertyValue(transformer, "shouldFlattenKeys", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(transformer, "jsonObjectMapper")) + .isSameAs(this.beanFactory.getBean(JsonObjectMapper.class)); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.mapToObjectTransformerWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.controlBusWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("subComponentsIdSupport1$child.routerWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("exceptionTypeRouterChain$child.exceptionTypeRouterWithinChain.handler")); - assertTrue(this.beanFactory.containsBean("recipientListRouterChain$child.recipientListRouterWithinChain.handler")); + assertThat(this.beanFactory + .containsBean("subComponentsIdSupport1$child.mapToObjectTransformerWithinChain.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1$child.controlBusWithinChain.handler")) + .isTrue(); + assertThat(this.beanFactory.containsBean("subComponentsIdSupport1$child.routerWithinChain.handler")).isTrue(); + assertThat(this.beanFactory + .containsBean("exceptionTypeRouterChain$child.exceptionTypeRouterWithinChain.handler")).isTrue(); + assertThat(this.beanFactory + .containsBean("recipientListRouterChain$child.recipientListRouterWithinChain.handler")).isTrue(); MessageHandlerChain chain = this.beanFactory.getBean("headerEnricherChain.handler", MessageHandlerChain.class); List handlers = TestUtils.getPropertyValue(chain, "handlers", List.class); - assertTrue(handlers.get(0) instanceof MessageTransformingHandler); - assertEquals("headerEnricherChain$child.headerEnricherWithinChain", TestUtils.getPropertyValue(handlers.get(0), "componentName")); - assertEquals("headerEnricherChain$child.headerEnricherWithinChain.handler", TestUtils.getPropertyValue(handlers.get(0), "beanName")); - assertTrue(this.beanFactory.containsBean("headerEnricherChain$child.headerEnricherWithinChain.handler")); + assertThat(handlers.get(0) instanceof MessageTransformingHandler).isTrue(); + assertThat(TestUtils.getPropertyValue(handlers.get(0), "componentName")) + .isEqualTo("headerEnricherChain$child.headerEnricherWithinChain"); + assertThat(TestUtils.getPropertyValue(handlers.get(0), "beanName")) + .isEqualTo("headerEnricherChain$child.headerEnricherWithinChain.handler"); + assertThat(this.beanFactory.containsBean("headerEnricherChain$child.headerEnricherWithinChain.handler")) + .isTrue(); - assertTrue(handlers.get(1) instanceof ServiceActivatingHandler); - assertEquals("headerEnricherChain$child#1", TestUtils.getPropertyValue(handlers.get(1), "componentName")); - assertEquals("headerEnricherChain$child#1.handler", TestUtils.getPropertyValue(handlers.get(1), "beanName")); - assertFalse(this.beanFactory.containsBean("headerEnricherChain$child#1.handler")); + assertThat(handlers.get(1) instanceof ServiceActivatingHandler).isTrue(); + assertThat(TestUtils.getPropertyValue(handlers.get(1), "componentName")) + .isEqualTo("headerEnricherChain$child#1"); + assertThat(TestUtils.getPropertyValue(handlers.get(1), "beanName")) + .isEqualTo("headerEnricherChain$child#1.handler"); + assertThat(this.beanFactory.containsBean("headerEnricherChain$child#1.handler")).isFalse(); } @Test public void testInt2755SubComponentException() { - GenericMessage testMessage = new GenericMessage("test"); + GenericMessage testMessage = new GenericMessage<>("test"); try { this.chainReplyRequiredChannel.send(testMessage); fail("Expected ReplyRequiredException"); } catch (Exception e) { - assertTrue(e instanceof ReplyRequiredException); - assertTrue(e.getMessage().contains("'chainReplyRequired$child.transformerReplyRequired'")); + assertThat(e instanceof ReplyRequiredException).isTrue(); + assertThat(e.getMessage().contains("'chainReplyRequired$child.transformerReplyRequired'")).isTrue(); } try { @@ -451,8 +471,9 @@ public class ChainParserTests { fail("Expected MessageRejectedException"); } catch (Exception e) { - assertTrue(e instanceof MessageRejectedException); - assertTrue(e.getMessage().contains("chainMessageRejectedException$child.filterMessageRejectedException")); + assertThat(e instanceof MessageRejectedException).isTrue(); + assertThat(e.getMessage().contains("chainMessageRejectedException$child.filterMessageRejectedException")) + .isTrue(); } } @@ -463,13 +484,13 @@ public class ChainParserTests { Message message = MessageBuilder.withPayload("foo").setHeader("myReplyChannel", replyChannel).build(); this.chainWithNoOutputChannel.send(message); Message receive = replyChannel.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); message = MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build(); Message message2 = MessageBuilder.withPayload("bar").setHeader("myMessage", message).build(); this.chainWithTransformNoOutputChannel.send(message2); receive = replyChannel.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); } public static class StubHandler extends AbstractReplyProducingMessageHandler { @@ -486,6 +507,7 @@ public class ChainParserTests { public String aggregate(List strings) { return StringUtils.collectionToCommaDelimitedString(strings); } + } public static class FooPojo { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelAdapterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelAdapterParserTests.java index c12709d842..c79bc6b86d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelAdapterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,9 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -81,16 +74,16 @@ public class ChannelAdapterParserTests { TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); testBean.store("source test"); Object adapter = this.applicationContext.getBean(beanName); - assertNotNull(adapter); - assertTrue(adapter instanceof SourcePollingChannelAdapter); - assertEquals(-1, ((SourcePollingChannelAdapter) adapter).getPhase()); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof SourcePollingChannelAdapter).isTrue(); + assertThat(((SourcePollingChannelAdapter) adapter).getPhase()).isEqualTo(-1); this.applicationContext.start(); Message message = channel.receive(10000); - assertNotNull(message); - assertEquals("source test", testBean.getMessage()); + assertThat(message).isNotNull(); + assertThat(testBean.getMessage()).isEqualTo("source test"); this.applicationContext.stop(); message = channel.receive(100); - assertNull(message); + assertThat(message).isNull(); } @Test @@ -100,63 +93,63 @@ public class ChannelAdapterParserTests { // TestBean testBean = (TestBean) this.applicationContextInner.getBean("testBean"); // testBean.store("source test"); Object adapter = this.applicationContextInner.getBean(beanName); - assertNotNull(adapter); - assertTrue(adapter instanceof SourcePollingChannelAdapter); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof SourcePollingChannelAdapter).isTrue(); this.applicationContextInner.start(); Message message = channel.receive(10000); - assertNotNull(message); + assertThat(message).isNotNull(); //assertEquals("source test", testBean.getMessage()); this.applicationContextInner.stop(); message = channel.receive(100); - assertNull(message); + assertThat(message).isNull(); } @Test public void targetOnly() { String beanName = "outboundWithImplicitChannel"; Object channel = this.applicationContext.getBean(beanName); - assertTrue(channel instanceof DirectChannel); + assertThat(channel instanceof DirectChannel).isTrue(); BeanFactoryChannelResolver channelResolver = new BeanFactoryChannelResolver(this.applicationContext); - assertNotNull(channelResolver.resolveDestination(beanName)); + assertThat(channelResolver.resolveDestination(beanName)).isNotNull(); Object adapter = this.applicationContext.getBean(beanName + ".adapter"); - assertNotNull(adapter); - assertTrue(adapter instanceof EventDrivenConsumer); - assertFalse(((EventDrivenConsumer) adapter).isAutoStartup()); - assertEquals(-1, ((EventDrivenConsumer) adapter).getPhase()); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof EventDrivenConsumer).isTrue(); + assertThat(((EventDrivenConsumer) adapter).isAutoStartup()).isFalse(); + assertThat(((EventDrivenConsumer) adapter).getPhase()).isEqualTo(-1); TestConsumer consumer = (TestConsumer) this.applicationContext.getBean("consumer"); - assertNull(consumer.getLastMessage()); + assertThat(consumer.getLastMessage()).isNull(); Message message = new GenericMessage("test"); try { ((MessageChannel) channel).send(message); fail("MessageDispatchingException is expected."); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(MessageDeliveryException.class)); - assertThat(e.getCause(), Matchers.instanceOf(MessageDispatchingException.class)); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getCause()).isInstanceOf(MessageDispatchingException.class); } ((EventDrivenConsumer) adapter).start(); ((MessageChannel) channel).send(message); - assertNotNull(consumer.getLastMessage()); - assertEquals(message, consumer.getLastMessage()); + assertThat(consumer.getLastMessage()).isNotNull(); + assertThat(consumer.getLastMessage()).isEqualTo(message); } @Test public void methodInvokingConsumer() { String beanName = "methodInvokingConsumer"; Object channel = this.applicationContext.getBean(beanName); - assertTrue(channel instanceof DirectChannel); + assertThat(channel instanceof DirectChannel).isTrue(); BeanFactoryChannelResolver channelResolver = new BeanFactoryChannelResolver(this.applicationContext); - assertNotNull(channelResolver.resolveDestination(beanName)); + assertThat(channelResolver.resolveDestination(beanName)).isNotNull(); Object adapter = this.applicationContext.getBean(beanName + ".adapter"); - assertNotNull(adapter); - assertTrue(adapter instanceof EventDrivenConsumer); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof EventDrivenConsumer).isTrue(); TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); - assertNull(testBean.getMessage()); + assertThat(testBean.getMessage()).isNull(); Message message = new GenericMessage("consumer test"); - assertTrue(((MessageChannel) channel).send(message)); - assertNotNull(testBean.getMessage()); - assertEquals("consumer test", testBean.getMessage()); + assertThat(((MessageChannel) channel).send(message)).isTrue(); + assertThat(testBean.getMessage()).isNotNull(); + assertThat(testBean.getMessage()).isEqualTo("consumer test"); } @Test @@ -166,18 +159,18 @@ public class ChannelAdapterParserTests { public void expressionConsumer() { String beanName = "expressionConsumer"; Object channel = this.applicationContext.getBean(beanName); - assertTrue(channel instanceof DirectChannel); + assertThat(channel instanceof DirectChannel).isTrue(); BeanFactoryChannelResolver channelResolver = new BeanFactoryChannelResolver(this.applicationContext); - assertNotNull(channelResolver.resolveDestination(beanName)); + assertThat(channelResolver.resolveDestination(beanName)).isNotNull(); Object adapter = this.applicationContext.getBean(beanName + ".adapter"); - assertNotNull(adapter); - assertTrue(adapter instanceof EventDrivenConsumer); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof EventDrivenConsumer).isTrue(); TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); - assertNull(testBean.getMessage()); + assertThat(testBean.getMessage()).isNull(); Message message = new GenericMessage("consumer test expression"); - assertTrue(((MessageChannel) channel).send(message)); - assertNotNull(testBean.getMessage()); - assertEquals("consumer test expression", testBean.getMessage()); + assertThat(((MessageChannel) channel).send(message)).isTrue(); + assertThat(testBean.getMessage()).isNotNull(); + assertThat(testBean.getMessage()).isEqualTo("consumer test expression"); } @Test @@ -187,12 +180,12 @@ public class ChannelAdapterParserTests { TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); testBean.store("source test"); Object adapter = this.applicationContext.getBean(beanName); - assertNotNull(adapter); - assertTrue(adapter instanceof SourcePollingChannelAdapter); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof SourcePollingChannelAdapter).isTrue(); ((SourcePollingChannelAdapter) adapter).start(); Message message = channel.receive(10000); - assertNotNull(message); - assertEquals("source test", testBean.getMessage()); + assertThat(message).isNotNull(); + assertThat(testBean.getMessage()).isEqualTo("source test"); ((SourcePollingChannelAdapter) adapter).stop(); } @@ -203,16 +196,16 @@ public class ChannelAdapterParserTests { TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); testBean.store("source test"); Object adapter = this.applicationContext.getBean(beanName); - assertNotNull(adapter); - assertTrue(adapter instanceof SourcePollingChannelAdapter); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof SourcePollingChannelAdapter).isTrue(); ((SourcePollingChannelAdapter) adapter).start(); Message message = channel.receive(10000); ((SourcePollingChannelAdapter) adapter).stop(); - assertNotNull(message); - assertEquals("source test", testBean.getMessage()); - assertEquals("source test", message.getPayload()); - assertEquals("ABC", message.getHeaders().get("foo")); - assertEquals(123, message.getHeaders().get("bar")); + assertThat(message).isNotNull(); + assertThat(testBean.getMessage()).isEqualTo("source test"); + assertThat(message.getPayload()).isEqualTo("source test"); + assertThat(message.getHeaders().get("foo")).isEqualTo("ABC"); + assertThat(message.getHeaders().get("bar")).isEqualTo(123); } @Test @@ -222,10 +215,10 @@ public class ChannelAdapterParserTests { TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); testBean.store("source test"); Object adapter = this.applicationContext.getBean(beanName); - assertNotNull(adapter); - assertTrue(adapter instanceof SourcePollingChannelAdapter); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof SourcePollingChannelAdapter).isTrue(); Message message = channel.receive(100); - assertNull(message); + assertThat(message).isNull(); } @Test @@ -235,15 +228,15 @@ public class ChannelAdapterParserTests { TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); testBean.store("source test"); Object adapter = this.applicationContext.getBean(beanName); - assertNotNull(adapter); - assertTrue(adapter instanceof SourcePollingChannelAdapter); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof SourcePollingChannelAdapter).isTrue(); ((SourcePollingChannelAdapter) adapter).start(); Message message = channel.receive(10000); - assertNotNull(message); - assertEquals("source test", testBean.getMessage()); + assertThat(message).isNotNull(); + assertThat(testBean.getMessage()).isEqualTo("source test"); ((SourcePollingChannelAdapter) adapter).stop(); message = channel.receive(100); - assertNull(message); + assertThat(message).isNull(); } @Test @@ -253,12 +246,12 @@ public class ChannelAdapterParserTests { TestBean testBean = (TestBean) this.applicationContext.getBean("testBean"); testBean.store("source test"); Object adapter = this.applicationContext.getBean(beanName); - assertNotNull(adapter); - assertTrue(adapter instanceof SourcePollingChannelAdapter); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof SourcePollingChannelAdapter).isTrue(); this.applicationContext.start(); Message message = channel.receive(1000); - assertNotNull(message); - assertEquals("source test", testBean.getMessage()); + assertThat(message).isNotNull(); + assertThat(testBean.getMessage()).isEqualTo("source test"); this.applicationContext.stop(); } @@ -274,9 +267,9 @@ public class ChannelAdapterParserTests { SourcePollingChannelAdapter adapter = this.applicationContext.getBean(beanName, SourcePollingChannelAdapter.class); - assertNotNull(adapter); + assertThat(adapter).isNotNull(); long sendTimeout = TestUtils.getPropertyValue(adapter, "messagingTemplate.sendTimeout", Long.class); - assertEquals(999, sendTimeout); + assertThat(sendTimeout).isEqualTo(999); } @Test(expected = BeanDefinitionParsingException.class) @@ -292,11 +285,11 @@ public class ChannelAdapterParserTests { for (int i = 0; i < 10; i++) { Message message = channel1.receive(5000); - assertNotNull(message); - assertEquals(i + 1, message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo(i + 1); message = channel2.receive(5000); - assertNotNull(message); - assertEquals(i + 1, message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo(i + 1); } } @@ -305,14 +298,14 @@ public class ChannelAdapterParserTests { PollableChannel channel = this.applicationContext.getBean("messageSourceRefChannel", PollableChannel.class); Message message = channel.receive(5000); - assertNotNull(message); - assertEquals("test", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("test"); MessageSource testMessageSource = this.applicationContext.getBean("testMessageSource", MessageSource.class); SourcePollingChannelAdapter adapterWithMessageSourceRef = this.applicationContext.getBean("adapterWithMessageSourceRef", SourcePollingChannelAdapter.class); MessageSource source = TestUtils.getPropertyValue(adapterWithMessageSourceRef, "source", MessageSource.class); - assertSame(testMessageSource, source); + assertThat(source).isSameAs(testMessageSource); } public static class SampleBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelWithMessageStoreParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelWithMessageStoreParserTests.java index 4838a04bc4..1997a06f34 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelWithMessageStoreParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ChannelWithMessageStoreParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.config; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.TimeUnit; @@ -79,21 +76,22 @@ public class ChannelWithMessageStoreParserTests { input.send(createMessage("123", "id1", 3, 1, null)); handler.getLatch().await(100, TimeUnit.MILLISECONDS); - assertEquals("The message payload is not correct", "123", handler.getMessageString()); + assertThat(handler.getMessageString()).as("The message payload is not correct").isEqualTo("123"); // The group id for buffered messages is the channel name - assertEquals(1, messageGroupStore.getMessageGroup("messageStore:output").size()); + assertThat(messageGroupStore.getMessageGroup("messageStore:output").size()).isEqualTo(1); Message result = output.receive(100); - assertEquals("hello", result.getPayload()); - assertEquals(0, messageGroupStore.getMessageGroup(BASE_PACKAGE + ".store:output").size()); + assertThat(result.getPayload()).isEqualTo("hello"); + assertThat(messageGroupStore.getMessageGroup(BASE_PACKAGE + ".store:output").size()).isEqualTo(0); } @Test @DirtiesContext public void testPriorityMessageStore() { - assertSame(this.priorityMessageStore, TestUtils.getPropertyValue(this.priorityChannel, "queue.messageGroupStore")); - assertThat(this.priorityChannel, instanceOf(PriorityChannel.class)); + assertThat(TestUtils.getPropertyValue(this.priorityChannel, "queue.messageGroupStore")) + .isSameAs(this.priorityMessageStore); + assertThat(this.priorityChannel).isInstanceOf(PriorityChannel.class); } private static Message createMessage(T payload, Object correlationId, int sequenceSize, int sequenceNumber, diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java index 9f2f0ad362..b931c5f94b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -37,7 +36,7 @@ public class CorrelationStrategyInvalidConfigurationTests { CorrelationStrategyInvalidConfigurationTests.class).close(); } catch (BeanCreationException e) { - assertThat(e.getMessage(), containsString("MessageCountReleaseStrategy] has no eligible methods")); + assertThat(e.getMessage()).contains("MessageCountReleaseStrategy] has no eligible methods"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/EndpointParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/EndpointParserTests.java index 0a8ded5aab..1e7c7b8a20 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/EndpointParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/EndpointParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.TimeUnit; @@ -42,10 +40,10 @@ public class EndpointParserTests { context.start(); MessageChannel channel = (MessageChannel) context.getBean("endpointParserTestInput"); TestHandler handler = (TestHandler) context.getBean("testHandler"); - assertNull(handler.getMessageString()); + assertThat(handler.getMessageString()).isNull(); channel.send(new GenericMessage<>("test")); - assertTrue(handler.getLatch().await(10000, TimeUnit.MILLISECONDS)); - assertEquals("test", handler.getMessageString()); + assertThat(handler.getLatch().await(10000, TimeUnit.MILLISECONDS)).isTrue(); + assertThat(handler.getMessageString()).isEqualTo("test"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/FilterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/FilterParserTests.java index 7acfd28ca4..096751ad41 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/FilterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/FilterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -97,8 +93,8 @@ public class FilterParserTests { @Test public void adviseDiscard() { - assertFalse(TestUtils.getPropertyValue(this.advised, "postProcessWithinAdvice", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(this.notAdvised, "postProcessWithinAdvice", Boolean.class)); + assertThat(TestUtils.getPropertyValue(this.advised, "postProcessWithinAdvice", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(this.notAdvised, "postProcessWithinAdvice", Boolean.class)).isTrue(); } @Test @@ -106,38 +102,38 @@ public class FilterParserTests { adviceCalled = 0; adapterInput.send(new GenericMessage<>("test")); Message reply = adapterOutput.receive(0); - assertNotNull(reply); - assertEquals("test", reply.getPayload()); - assertEquals(1, adviceCalled); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("test"); + assertThat(adviceCalled).isEqualTo(1); } @Test public void filterWithSelectorAdapterRejects() { adapterInput.send(new GenericMessage<>("")); Message reply = adapterOutput.receive(0); - assertNull(reply); + assertThat(reply).isNull(); } @Test public void filterWithSelectorImplementationAccepts() { implementationInput.send(new GenericMessage<>("test")); Message reply = implementationOutput.receive(0); - assertNotNull(reply); - assertEquals("test", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("test"); } @Test public void filterWithSelectorImplementationRejects() { implementationInput.send(new GenericMessage<>("")); Message reply = implementationOutput.receive(0); - assertNull(reply); + assertThat(reply).isNull(); } @Test public void exceptionThrowingFilterAccepts() { exceptionInput.send(new GenericMessage<>("test")); Message reply = implementationOutput.receive(0); - assertNotNull(reply); + assertThat(reply).isNotNull(); } @Test(expected = MessageRejectedException.class) @@ -149,9 +145,9 @@ public class FilterParserTests { public void filterWithDiscardChannel() { discardInput.send(new GenericMessage<>("")); Message discard = discardOutput.receive(0); - assertNotNull(discard); - assertEquals("", discard.getPayload()); - assertNull(adapterOutput.receive(0)); + assertThat(discard).isNotNull(); + assertThat(discard.getPayload()).isEqualTo(""); + assertThat(adapterOutput.receive(0)).isNull(); } @Test(expected = MessageRejectedException.class) @@ -164,9 +160,9 @@ public class FilterParserTests { exception = e; } Message discard = discardAndExceptionOutput.receive(0); - assertNotNull(discard); - assertEquals("", discard.getPayload()); - assertNull(adapterOutput.receive(0)); + assertThat(discard).isNotNull(); + assertThat(discard.getPayload()).isEqualTo(""); + assertThat(adapterOutput.receive(0)).isNull(); throw exception; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/IdGeneratorConfigurerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/IdGeneratorConfigurerTests.java index faa53d45ff..e90c46d2da 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/IdGeneratorConfigurerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/IdGeneratorConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; @@ -50,13 +47,13 @@ public class IdGeneratorConfigurerTests { context.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator.class)); context.refresh(); MessageHeaders headers = new MessageHeaders(null); - assertEquals(1, headers.getId().getMostSignificantBits()); - assertEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(2); context.close(); headers = new MessageHeaders(null); - assertNotEquals(1, headers.getId().getMostSignificantBits()); - assertNotEquals(2, headers.getId().getLeastSignificantBits()); - assertNull(TestUtils.getPropertyValue(headers, "idGenerator")); + assertThat(headers.getId().getMostSignificantBits()).isNotEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isNotEqualTo(2); + assertThat(TestUtils.getPropertyValue(headers, "idGenerator")).isNull(); } @Test @@ -69,7 +66,7 @@ public class IdGeneratorConfigurerTests { // multiple beans are ignored with warning MessageHeaders headers = new MessageHeaders(null); - assertNull(TestUtils.getPropertyValue(headers, "idGenerator")); + assertThat(TestUtils.getPropertyValue(headers, "idGenerator")).isNull(); context.close(); } @@ -81,7 +78,7 @@ public class IdGeneratorConfigurerTests { context.refresh(); MessageHeaders headers = new MessageHeaders(null); - assertNull(TestUtils.getPropertyValue(headers, "idGenerator")); + assertThat(TestUtils.getPropertyValue(headers, "idGenerator")).isNull(); context.close(); } @@ -93,8 +90,8 @@ public class IdGeneratorConfigurerTests { context.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator.class)); context.refresh(); MessageHeaders headers = new MessageHeaders(null); - assertEquals(1, headers.getId().getMostSignificantBits()); - assertEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(2); GenericApplicationContext context2 = new GenericApplicationContext(); context2.registerBeanDefinition("bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class)); @@ -105,10 +102,10 @@ public class IdGeneratorConfigurerTests { context2.close(); headers = new MessageHeaders(null); - assertNotEquals(1, headers.getId().getMostSignificantBits()); - assertNotEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isNotEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isNotEqualTo(2); - assertNull(TestUtils.getPropertyValue(headers, "idGenerator")); + assertThat(TestUtils.getPropertyValue(headers, "idGenerator")).isNull(); } @Test @@ -118,8 +115,8 @@ public class IdGeneratorConfigurerTests { context.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator.class)); context.refresh(); MessageHeaders headers = new MessageHeaders(null); - assertEquals(1, headers.getId().getMostSignificantBits()); - assertEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(2); GenericApplicationContext context2 = new GenericApplicationContext(); context2.registerBeanDefinition("bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class)); @@ -129,16 +126,16 @@ public class IdGeneratorConfigurerTests { context.close(); // we should still use the custom strategy headers = new MessageHeaders(null); - assertEquals(1, headers.getId().getMostSignificantBits()); - assertEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(2); context2.close(); // back to default headers = new MessageHeaders(null); - assertNotEquals(1, headers.getId().getMostSignificantBits()); - assertNotEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isNotEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isNotEqualTo(2); - assertNull(TestUtils.getPropertyValue(headers, "idGenerator")); + assertThat(TestUtils.getPropertyValue(headers, "idGenerator")).isNull(); } @Test @@ -148,8 +145,8 @@ public class IdGeneratorConfigurerTests { context.registerBeanDefinition("foo", new RootBeanDefinition(MyIdGenerator.class)); context.refresh(); MessageHeaders headers = new MessageHeaders(null); - assertEquals(1, headers.getId().getMostSignificantBits()); - assertEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(2); GenericApplicationContext context2 = new GenericApplicationContext(); context2.registerBeanDefinition("bfpp", new RootBeanDefinition(DefaultConfiguringBeanFactoryPostProcessor.class)); @@ -159,8 +156,8 @@ public class IdGeneratorConfigurerTests { fail("Expected exception"); } catch (BeanDefinitionStoreException e) { - assertEquals("'MessageHeaders.idGenerator' has already been set and can not be set again", - e.getMessage()); + assertThat(e.getMessage()) + .isEqualTo("'MessageHeaders.idGenerator' has already been set and can not be set again"); } context.close(); @@ -174,7 +171,7 @@ public class IdGeneratorConfigurerTests { context.registerBeanDefinition("foo", new RootBeanDefinition(JdkIdGenerator.class)); context.refresh(); MessageHeaders headers = new MessageHeaders(null); - assertSame(context.getBean(IdGenerator.class), TestUtils.getPropertyValue(headers, "idGenerator")); + assertThat(TestUtils.getPropertyValue(headers, "idGenerator")).isSameAs(context.getBean(IdGenerator.class)); context.close(); } @@ -187,19 +184,19 @@ public class IdGeneratorConfigurerTests { context.refresh(); IdGenerator idGenerator = context.getBean(IdGenerator.class); MessageHeaders headers = new MessageHeaders(null); - assertEquals(0, headers.getId().getMostSignificantBits()); - assertEquals(1, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(0); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(1); headers = new MessageHeaders(null); - assertEquals(0, headers.getId().getMostSignificantBits()); - assertEquals(2, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(0); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(2); AtomicLong bottomBits = TestUtils.getPropertyValue(idGenerator, "bottomBits", AtomicLong.class); bottomBits.set(0xffffffff); headers = new MessageHeaders(null); - assertEquals(1, headers.getId().getMostSignificantBits()); - assertEquals(0, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(0); headers = new MessageHeaders(null); - assertEquals(1, headers.getId().getMostSignificantBits()); - assertEquals(1, headers.getId().getLeastSignificantBits()); + assertThat(headers.getId().getMostSignificantBits()).isEqualTo(1); + assertThat(headers.getId().getLeastSignificantBits()).isEqualTo(1); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidPriorityChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidPriorityChannelParserTests.java index be726b4bbe..2e1e69890f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidPriorityChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidPriorityChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,9 @@ package org.springframework.integration.config; -import org.hamcrest.Matchers; -import org.junit.Rule; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -27,27 +26,29 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author Dave Syer * @author Manuel Jordan + * @author Artem Bilan + * * @since 4.3 */ public class InvalidPriorityChannelParserTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test - public void testMessageStoreAndCapacityIllegal() throws Exception { - this.exception.expect(BeanDefinitionParsingException.class); - this.exception.expectMessage(Matchers.containsString("'capacity' attribute is not allowed")); - new ClassPathXmlApplicationContext("InvalidPriorityChannelWithMessageStoreAndCapacityParserTests.xml", - getClass()).close(); + public void testMessageStoreAndCapacityIllegal() { + assertThatThrownBy(() -> + new ClassPathXmlApplicationContext("InvalidPriorityChannelWithMessageStoreAndCapacityParserTests.xml", + getClass())) + .isInstanceOf(BeanDefinitionParsingException.class) + .hasMessageContaining("'capacity' attribute is not allowed"); } @Test - public void testComparatorAndMessageStoreIllegal() throws Exception { - this.exception.expect(BeanDefinitionParsingException.class); - this.exception.expectMessage(Matchers.containsString("The 'message-store' attribute is not allowed")); - new ClassPathXmlApplicationContext("InvalidPriorityChannelWithComparatorAndMessageStoreParserTests.xml", - getClass()).close(); + public void testComparatorAndMessageStoreIllegal() { + assertThatThrownBy(() -> + new ClassPathXmlApplicationContext( + "InvalidPriorityChannelWithComparatorAndMessageStoreParserTests.xml", + getClass())) + .isInstanceOf(BeanDefinitionParsingException.class) + .hasMessageContaining("The 'message-store' attribute is not allowed"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidQueueChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidQueueChannelParserTests.java index b4bb15fe49..50594ca9af 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidQueueChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/InvalidQueueChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,9 @@ package org.springframework.integration.config; -import org.hamcrest.Matchers; -import org.junit.Rule; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.parsing.BeanDefinitionParsingException; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -31,31 +30,32 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; */ public class InvalidQueueChannelParserTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test - public void testMessageStoreAndCapacityIllegal() throws Exception { - this.exception.expect(BeanDefinitionParsingException.class); - this.exception.expectMessage(Matchers.containsString("'capacity' attribute is not allowed")); - new ClassPathXmlApplicationContext("InvalidQueueChannelWithMessageStoreAndCapacityParserTests.xml", - getClass()).close(); + public void testMessageStoreAndCapacityIllegal() { + assertThatThrownBy(() -> + new ClassPathXmlApplicationContext("InvalidQueueChannelWithMessageStoreAndCapacityParserTests.xml", + getClass())) + .isInstanceOf(BeanDefinitionParsingException.class) + .hasMessageContaining("'capacity' attribute is not allowed"); } @Test - public void testRefAndCapacityIllegal() throws Exception { - this.exception.expect(BeanDefinitionParsingException.class); - this.exception.expectMessage(Matchers.containsString("'capacity' attribute is not allowed")); - new ClassPathXmlApplicationContext("InvalidQueueChannelWithRefAndCapacityParserTests.xml", getClass()) - .close(); + public void testRefAndCapacityIllegal() { + assertThatThrownBy(() -> + new ClassPathXmlApplicationContext("InvalidQueueChannelWithRefAndCapacityParserTests.xml", + getClass())) + .isInstanceOf(BeanDefinitionParsingException.class) + .hasMessageContaining("'capacity' attribute is not allowed"); } @Test - public void testRefAndMessageStoreIllegal() throws Exception { - this.exception.expect(BeanDefinitionParsingException.class); - this.exception.expectMessage(Matchers.containsString("'message-store' attribute is not allowed")); - new ClassPathXmlApplicationContext("InvalidQueueChannelWithRefAndMessageStoreParserTests.xml", getClass()) - .close(); + public void testRefAndMessageStoreIllegal() { + assertThatThrownBy(() -> + new ClassPathXmlApplicationContext("InvalidQueueChannelWithRefAndMessageStoreParserTests.xml", + getClass())) + .isInstanceOf(BeanDefinitionParsingException.class) + .hasMessageContaining("The 'message-store' attribute is not allowed " + + "when providing a 'ref' to a custom queue."); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/MessageBusParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/MessageBusParserTests.java index 0c27db1f02..59743bf7f5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/MessageBusParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/MessageBusParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -45,7 +44,7 @@ public class MessageBusParserTests { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "messageBusWithErrorChannel.xml", this.getClass()); BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(context); - assertEquals(context.getBean("errorChannel"), resolver.resolveDestination("errorChannel")); + assertThat(resolver.resolveDestination("errorChannel")).isEqualTo(context.getBean("errorChannel")); context.close(); } @@ -54,7 +53,7 @@ public class MessageBusParserTests { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "messageBusWithDefaults.xml", this.getClass()); BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(context); - assertEquals(context.getBean("errorChannel"), resolver.resolveDestination("errorChannel")); + assertThat(resolver.resolveDestination("errorChannel")).isEqualTo(context.getBean("errorChannel")); context.close(); } @@ -67,10 +66,10 @@ public class MessageBusParserTests { DirectFieldAccessor accessor = new DirectFieldAccessor(multicaster); Object taskExecutor = accessor.getPropertyValue("taskExecutor"); if (SpringVersion.getVersion().startsWith("2")) { - assertEquals(SyncTaskExecutor.class, taskExecutor.getClass()); + assertThat(taskExecutor.getClass()).isEqualTo(SyncTaskExecutor.class); } else { - assertNull(taskExecutor); + assertThat(taskExecutor).isNull(); } context.close(); } @@ -85,10 +84,10 @@ public class MessageBusParserTests { DirectFieldAccessor accessor = new DirectFieldAccessor(multicaster); Object taskExecutor = accessor.getPropertyValue("taskExecutor"); if (SpringVersion.getVersion().startsWith("2")) { - assertEquals(SyncTaskExecutor.class, taskExecutor.getClass()); + assertThat(taskExecutor.getClass()).isEqualTo(SyncTaskExecutor.class); } else { - assertNull(taskExecutor); + assertThat(taskExecutor).isNull(); } context.close(); } @@ -102,7 +101,7 @@ public class MessageBusParserTests { context.getBean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME); DirectFieldAccessor accessor = new DirectFieldAccessor(multicaster); Object taskExecutor = accessor.getPropertyValue("taskExecutor"); - assertEquals(ThreadPoolTaskExecutor.class, taskExecutor.getClass()); + assertThat(taskExecutor.getClass()).isEqualTo(ThreadPoolTaskExecutor.class); context.close(); } @@ -111,7 +110,7 @@ public class MessageBusParserTests { AbstractApplicationContext context = new ClassPathXmlApplicationContext( "messageBusWithTaskScheduler.xml", this.getClass()); TaskScheduler scheduler = (TaskScheduler) context.getBean("taskScheduler"); - assertEquals(StubTaskScheduler.class, scheduler.getClass()); + assertThat(scheduler.getClass()).isEqualTo(StubTaskScheduler.class); context.close(); } @@ -120,7 +119,7 @@ public class MessageBusParserTests { AbstractApplicationContext context = new ClassPathXmlApplicationContext( "messageBusWithTaskScheduler.xml", this.getClass()); TaskScheduler scheduler = (TaskScheduler) context.getBean("taskScheduler"); - assertEquals(scheduler, IntegrationContextUtils.getTaskScheduler(context)); + assertThat(IntegrationContextUtils.getTaskScheduler(context)).isEqualTo(scheduler); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java index 6e61f391c7..4eaf95036d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.assertj.core.api.Assertions.assertThat; import java.util.concurrent.Executor; @@ -60,11 +55,11 @@ public class PublishSubscribeChannelParserTests { dispatcher.addHandler(message -> { }); dispatcher.dispatch(new GenericMessage<>("foo")); DirectFieldAccessor dispatcherAccessor = new DirectFieldAccessor(dispatcher); - assertNull(dispatcherAccessor.getPropertyValue("executor")); - assertFalse((Boolean) dispatcherAccessor.getPropertyValue("ignoreFailures")); - assertTrue((Boolean) dispatcherAccessor.getPropertyValue("applySequence")); + assertThat(dispatcherAccessor.getPropertyValue("executor")).isNull(); + assertThat((Boolean) dispatcherAccessor.getPropertyValue("ignoreFailures")).isFalse(); + assertThat((Boolean) dispatcherAccessor.getPropertyValue("applySequence")).isTrue(); Object mbf = this.context.getBean(IntegrationUtils.INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME); - assertSame(mbf, dispatcherAccessor.getPropertyValue("messageBuilderFactory")); + assertThat(dispatcherAccessor.getPropertyValue("messageBuilderFactory")).isSameAs(mbf); } @Test @@ -74,7 +69,7 @@ public class PublishSubscribeChannelParserTests { DirectFieldAccessor accessor = new DirectFieldAccessor(channel); BroadcastingDispatcher dispatcher = (BroadcastingDispatcher) accessor.getPropertyValue("dispatcher"); - assertTrue((Boolean) new DirectFieldAccessor(dispatcher).getPropertyValue("ignoreFailures")); + assertThat((Boolean) new DirectFieldAccessor(dispatcher).getPropertyValue("ignoreFailures")).isTrue(); } @Test @@ -84,7 +79,7 @@ public class PublishSubscribeChannelParserTests { DirectFieldAccessor accessor = new DirectFieldAccessor(channel); BroadcastingDispatcher dispatcher = (BroadcastingDispatcher) accessor.getPropertyValue("dispatcher"); - assertTrue((Boolean) new DirectFieldAccessor(dispatcher).getPropertyValue("applySequence")); + assertThat((Boolean) new DirectFieldAccessor(dispatcher).getPropertyValue("applySequence")).isTrue(); } @Test @@ -96,11 +91,11 @@ public class PublishSubscribeChannelParserTests { accessor.getPropertyValue("dispatcher"); DirectFieldAccessor dispatcherAccessor = new DirectFieldAccessor(dispatcher); Executor executor = (Executor) dispatcherAccessor.getPropertyValue("executor"); - assertNotNull(executor); - assertEquals(ErrorHandlingTaskExecutor.class, executor.getClass()); + assertThat(executor).isNotNull(); + assertThat(executor.getClass()).isEqualTo(ErrorHandlingTaskExecutor.class); DirectFieldAccessor executorAccessor = new DirectFieldAccessor(executor); Executor innerExecutor = (Executor) executorAccessor.getPropertyValue("executor"); - assertEquals(context.getBean("pool"), innerExecutor); + assertThat(innerExecutor).isEqualTo(context.getBean("pool")); } @Test @@ -111,13 +106,13 @@ public class PublishSubscribeChannelParserTests { BroadcastingDispatcher dispatcher = (BroadcastingDispatcher) accessor.getPropertyValue("dispatcher"); DirectFieldAccessor dispatcherAccessor = new DirectFieldAccessor(dispatcher); - assertTrue((Boolean) dispatcherAccessor.getPropertyValue("ignoreFailures")); + assertThat((Boolean) dispatcherAccessor.getPropertyValue("ignoreFailures")).isTrue(); Executor executor = (Executor) dispatcherAccessor.getPropertyValue("executor"); - assertNotNull(executor); - assertEquals(ErrorHandlingTaskExecutor.class, executor.getClass()); + assertThat(executor).isNotNull(); + assertThat(executor.getClass()).isEqualTo(ErrorHandlingTaskExecutor.class); DirectFieldAccessor executorAccessor = new DirectFieldAccessor(executor); Executor innerExecutor = (Executor) executorAccessor.getPropertyValue("executor"); - assertEquals(this.context.getBean("pool"), innerExecutor); + assertThat(innerExecutor).isEqualTo(this.context.getBean("pool")); } @Test @@ -128,13 +123,13 @@ public class PublishSubscribeChannelParserTests { BroadcastingDispatcher dispatcher = (BroadcastingDispatcher) accessor.getPropertyValue("dispatcher"); DirectFieldAccessor dispatcherAccessor = new DirectFieldAccessor(dispatcher); - assertTrue((Boolean) dispatcherAccessor.getPropertyValue("applySequence")); + assertThat((Boolean) dispatcherAccessor.getPropertyValue("applySequence")).isTrue(); Executor executor = (Executor) dispatcherAccessor.getPropertyValue("executor"); - assertNotNull(executor); - assertEquals(ErrorHandlingTaskExecutor.class, executor.getClass()); + assertThat(executor).isNotNull(); + assertThat(executor.getClass()).isEqualTo(ErrorHandlingTaskExecutor.class); DirectFieldAccessor executorAccessor = new DirectFieldAccessor(executor); Executor innerExecutor = (Executor) executorAccessor.getPropertyValue("executor"); - assertEquals(this.context.getBean("pool"), innerExecutor); + assertThat(innerExecutor).isEqualTo(this.context.getBean("pool")); } @Test @@ -143,8 +138,8 @@ public class PublishSubscribeChannelParserTests { this.context.getBean("channelWithErrorHandler", PublishSubscribeChannel.class); DirectFieldAccessor accessor = new DirectFieldAccessor(channel); ErrorHandler errorHandler = (ErrorHandler) accessor.getPropertyValue("errorHandler"); - assertNotNull(errorHandler); - assertEquals(this.context.getBean("testErrorHandler"), errorHandler); + assertThat(errorHandler).isNotNull(); + assertThat(errorHandler).isEqualTo(this.context.getBean("testErrorHandler")); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java index 25fccd7baf..64a3fc90f6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,12 +16,8 @@ package org.springframework.integration.config; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Collection; @@ -52,10 +48,10 @@ public class ReleaseStrategyFactoryBeanTests { fail("IllegalStateException expected"); } catch (Exception e) { - assertThat(e, instanceOf(IllegalStateException.class)); - assertThat(e.getMessage(), containsString("Target object of type " + + assertThat(e).isInstanceOf(IllegalStateException.class); + assertThat(e.getMessage()).contains("Target object of type " + "[class org.springframework.integration.config.ReleaseStrategyFactoryBeanTests$Foo] " + - "has no eligible methods for handling Messages.")); + "has no eligible methods for handling Messages."); } } @@ -67,10 +63,10 @@ public class ReleaseStrategyFactoryBeanTests { factory.setMethodName("doRelease2"); factory.afterPropertiesSet(); ReleaseStrategy delegate = factory.getObject(); - assertThat(delegate, instanceOf(MethodInvokingReleaseStrategy.class)); - assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.targetObject", Bar.class), is(bar)); - assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.handlerMethod.expressionString"), - equalTo("#target.doRelease2(messages)")); + assertThat(delegate).isInstanceOf(MethodInvokingReleaseStrategy.class); + assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.targetObject", Bar.class)).isEqualTo(bar); + assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.handlerMethod.expressionString")) + .isEqualTo("#target.doRelease2(messages)"); } @Test @@ -80,8 +76,8 @@ public class ReleaseStrategyFactoryBeanTests { factory.setTarget(bar); factory.afterPropertiesSet(); ReleaseStrategy delegate = factory.getObject(); - assertThat(delegate, instanceOf(MethodInvokingReleaseStrategy.class)); - assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.targetObject", Bar.class), is(bar)); + assertThat(delegate).isInstanceOf(MethodInvokingReleaseStrategy.class); + assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.targetObject", Bar.class)).isEqualTo(bar); } @Test @@ -89,7 +85,7 @@ public class ReleaseStrategyFactoryBeanTests { ReleaseStrategyFactoryBean factory = new ReleaseStrategyFactoryBean(); factory.afterPropertiesSet(); ReleaseStrategy delegate = factory.getObject(); - assertThat(delegate, instanceOf(SimpleSequenceSizeReleaseStrategy.class)); + assertThat(delegate).isInstanceOf(SimpleSequenceSizeReleaseStrategy.class); } @Test @@ -99,7 +95,7 @@ public class ReleaseStrategyFactoryBeanTests { factory.setTarget(foo); factory.afterPropertiesSet(); ReleaseStrategy delegate = factory.getObject(); - assertThat(delegate, instanceOf(SimpleSequenceSizeReleaseStrategy.class)); + assertThat(delegate).isInstanceOf(SimpleSequenceSizeReleaseStrategy.class); } @Test @@ -109,7 +105,7 @@ public class ReleaseStrategyFactoryBeanTests { factory.setTarget(baz); factory.afterPropertiesSet(); ReleaseStrategy delegate = factory.getObject(); - assertThat(delegate, is(baz)); + assertThat(delegate).isEqualTo(baz); } @Test @@ -120,10 +116,10 @@ public class ReleaseStrategyFactoryBeanTests { factory.setMethodName("doRelease2"); factory.afterPropertiesSet(); ReleaseStrategy delegate = factory.getObject(); - assertThat(delegate, instanceOf(MethodInvokingReleaseStrategy.class)); - assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.targetObject", Baz.class), is(baz)); - assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.handlerMethod.expressionString"), - equalTo("#target.doRelease2(messages)")); + assertThat(delegate).isInstanceOf(MethodInvokingReleaseStrategy.class); + assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.targetObject", Baz.class)).isEqualTo(baz); + assertThat(TestUtils.getPropertyValue(delegate, "adapter.delegate.handlerMethod.expressionString")) + .isEqualTo("#target.doRelease2(messages)"); } public class Foo { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerParserTests.java index 61659ed61e..44052c8423 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.integration.test.util.TestUtils.getPropertyValue; import java.util.List; @@ -66,15 +63,18 @@ public class ResequencerParserTests { EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("defaultResequencer"); ResequencingMessageHandler resequencer = TestUtils.getPropertyValue(endpoint, "handler", ResequencingMessageHandler.class); - assertNull(getPropertyValue(resequencer, "outputChannel")); - assertTrue(getPropertyValue(resequencer, "discardChannel") instanceof NullChannel); - assertEquals("The ResequencerEndpoint is not set with the appropriate timeout value", -1L, getPropertyValue( - resequencer, "messagingTemplate.sendTimeout")); - assertEquals( - "The ResequencerEndpoint is not configured with the appropriate 'send partial results on timeout' flag", - false, getPropertyValue(resequencer, "sendPartialResultOnExpiry")); - assertEquals("The ResequencerEndpoint is not configured with the appropriate 'release partial sequences' flag", - false, getPropertyValue(resequencer, "releasePartialSequences")); + assertThat(getPropertyValue(resequencer, "outputChannel")).isNull(); + assertThat(getPropertyValue(resequencer, "discardChannel") instanceof NullChannel).isTrue(); + assertThat(getPropertyValue( + resequencer, "messagingTemplate.sendTimeout")) + .as("The ResequencerEndpoint is not set with the appropriate timeout value").isEqualTo(-1L); + assertThat(getPropertyValue(resequencer, "sendPartialResultOnExpiry")) + .as("The ResequencerEndpoint is not configured with the appropriate 'send partial results on timeout' " + + "flag") + .isEqualTo(false); + assertThat(getPropertyValue(resequencer, "releasePartialSequences")) + .as("The ResequencerEndpoint is not configured with the appropriate 'release partial sequences' flag") + .isEqualTo(false); } @Test @@ -84,18 +84,23 @@ public class ResequencerParserTests { MessageChannel discardChannel = (MessageChannel) context.getBean("discardChannel"); ResequencingMessageHandler resequencer = TestUtils.getPropertyValue(endpoint, "handler", ResequencingMessageHandler.class); - assertEquals("The ResequencerEndpoint is not injected with the appropriate output channel", outputChannel, - getPropertyValue(resequencer, "outputChannel")); - assertEquals("The ResequencerEndpoint is not injected with the appropriate discard channel", discardChannel, - getPropertyValue(resequencer, "discardChannel")); - assertEquals("The ResequencerEndpoint is not set with the appropriate timeout value", 86420000L, - getPropertyValue(resequencer, "messagingTemplate.sendTimeout")); - assertEquals( - "The ResequencerEndpoint is not configured with the appropriate 'send partial results on timeout' flag", - true, getPropertyValue(resequencer, "sendPartialResultOnExpiry")); - assertEquals("The ResequencerEndpoint is not configured with the appropriate 'release partial sequences' flag", - true, getPropertyValue(getPropertyValue(resequencer, "releaseStrategy"), "releasePartialSequences")); - assertEquals(60000L, getPropertyValue(resequencer, "minimumTimeoutForEmptyGroups", Long.class).longValue()); + assertThat(getPropertyValue(resequencer, "outputChannel")) + .as("The ResequencerEndpoint is not injected with the appropriate output channel") + .isEqualTo(outputChannel); + assertThat(getPropertyValue(resequencer, "discardChannel")) + .as("The ResequencerEndpoint is not injected with the appropriate discard channel") + .isEqualTo(discardChannel); + assertThat(getPropertyValue(resequencer, "messagingTemplate.sendTimeout")) + .as("The ResequencerEndpoint is not set with the appropriate timeout value").isEqualTo(86420000L); + assertThat(getPropertyValue(resequencer, "sendPartialResultOnExpiry")) + .as("The ResequencerEndpoint is not configured with the appropriate 'send partial results on timeout' " + + "flag") + .isEqualTo(true); + assertThat(getPropertyValue(getPropertyValue(resequencer, "releaseStrategy"), "releasePartialSequences")) + .as("The ResequencerEndpoint is not configured with the appropriate 'release partial sequences' flag") + .isEqualTo(true); + assertThat(getPropertyValue(resequencer, "minimumTimeoutForEmptyGroups", Long.class).longValue()) + .isEqualTo(60000L); } @Test @@ -104,38 +109,44 @@ public class ResequencerParserTests { .getBean("resequencerWithCorrelationStrategyRefOnly"); ResequencingMessageHandler resequencer = TestUtils.getPropertyValue(endpoint, "handler", ResequencingMessageHandler.class); - assertEquals("The ResequencerEndpoint is not configured with the appropriate CorrelationStrategy", context - .getBean("testCorrelationStrategy"), getPropertyValue(resequencer, "correlationStrategy")); + assertThat(getPropertyValue(resequencer, "correlationStrategy")) + .as("The ResequencerEndpoint is not configured with the appropriate CorrelationStrategy") + .isEqualTo(context + .getBean("testCorrelationStrategy")); } @Test public void testReleaseStrategyRefOnly() throws Exception { EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("resequencerWithReleaseStrategyRefOnly"); - ResequencingMessageHandler resequencer = getPropertyValue(endpoint, "handler", ResequencingMessageHandler.class); - assertEquals("The ResequencerEndpoint is not configured with the appropriate ReleaseStrategy", - context.getBean("testReleaseStrategy"), getPropertyValue(resequencer, "releaseStrategy")); - assertFalse(TestUtils.getPropertyValue(resequencer, "expireGroupsUponTimeout", Boolean.class)); + ResequencingMessageHandler resequencer = getPropertyValue(endpoint, "handler", + ResequencingMessageHandler.class); + assertThat(getPropertyValue(resequencer, "releaseStrategy")) + .as("The ResequencerEndpoint is not configured with the appropriate ReleaseStrategy") + .isEqualTo(context.getBean("testReleaseStrategy")); + assertThat(TestUtils.getPropertyValue(resequencer, "expireGroupsUponTimeout", Boolean.class)).isFalse(); } @Test public void testReleaseStrategyRefAndMethod() throws Exception { EventDrivenConsumer endpoint = (EventDrivenConsumer) context .getBean("resequencerWithReleaseStrategyRefAndMethod"); - ResequencingMessageHandler resequencer = getPropertyValue(endpoint, "handler", ResequencingMessageHandler.class); + ResequencingMessageHandler resequencer = getPropertyValue(endpoint, "handler", + ResequencingMessageHandler.class); Object releaseStrategyBean = context.getBean("testReleaseStrategyPojo"); - assertTrue("Release strategy is not of the expected type", - releaseStrategyBean instanceof TestReleaseStrategyPojo); + assertThat(releaseStrategyBean instanceof TestReleaseStrategyPojo) + .as("Release strategy is not of the expected type").isTrue(); TestReleaseStrategyPojo expectedReleaseStrategy = (TestReleaseStrategyPojo) releaseStrategyBean; int currentInvocationCount = expectedReleaseStrategy.invocationCount; ReleaseStrategy effectiveReleaseStrategy = (ReleaseStrategy) getPropertyValue(resequencer, "releaseStrategy"); - assertTrue("The release strategy is expected to be a MethodInvokingReleaseStrategy", - effectiveReleaseStrategy instanceof MethodInvokingReleaseStrategy); + assertThat(effectiveReleaseStrategy instanceof MethodInvokingReleaseStrategy) + .as("The release strategy is expected to be a MethodInvokingReleaseStrategy").isTrue(); effectiveReleaseStrategy.canRelease(new SimpleMessageGroup("test")); - assertEquals("The ResequencerEndpoint was not invoked the expected number of times;", - currentInvocationCount + 1, expectedReleaseStrategy.invocationCount); - assertTrue(TestUtils.getPropertyValue(resequencer, "expireGroupsUponTimeout", Boolean.class)); + assertThat(expectedReleaseStrategy.invocationCount) + .as("The ResequencerEndpoint was not invoked the expected number of times;") + .isEqualTo(currentInvocationCount + 1); + assertThat(TestUtils.getPropertyValue(resequencer, "expireGroupsUponTimeout", Boolean.class)).isTrue(); } @Test @@ -143,8 +154,9 @@ public class ResequencerParserTests { EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("completelyDefinedResequencer"); ResequencingMessageHandler resequencer = TestUtils.getPropertyValue(endpoint, "handler", ResequencingMessageHandler.class); - assertEquals("The ResequencerEndpoint is not configured with the appropriate 'release partial sequences' flag", - true, getPropertyValue(getPropertyValue(resequencer, "releaseStrategy"), "releasePartialSequences")); + assertThat(getPropertyValue(getPropertyValue(resequencer, "releaseStrategy"), "releasePartialSequences")) + .as("The ResequencerEndpoint is not configured with the appropriate 'release partial sequences' flag") + .isEqualTo(true); } @Test @@ -154,10 +166,11 @@ public class ResequencerParserTests { ResequencingMessageHandler resequencer = TestUtils.getPropertyValue(endpoint, "handler", ResequencingMessageHandler.class); Object correlationStrategy = getPropertyValue(resequencer, "correlationStrategy"); - assertEquals("The ResequencerEndpoint is not configured with a CorrelationStrategy adapter", - MethodInvokingCorrelationStrategy.class, correlationStrategy.getClass()); + assertThat(correlationStrategy.getClass()) + .as("The ResequencerEndpoint is not configured with a CorrelationStrategy adapter") + .isEqualTo(MethodInvokingCorrelationStrategy.class); MethodInvokingCorrelationStrategy adapter = (MethodInvokingCorrelationStrategy) correlationStrategy; - assertEquals("foo", adapter.getCorrelationKey(MessageBuilder.withPayload("not important").build())); + assertThat(adapter.getCorrelationKey(MessageBuilder.withPayload("not important").build())).isEqualTo("foo"); } @SuppressWarnings("unused") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java index f17dde6384..9ac71a0f59 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -56,21 +55,21 @@ public class ResequencerWithMessageStoreParserTests { public void testResequence() { input.send(createMessage("123", "id1", 3, 1, null)); - assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); + assertThat(messageGroupStore.getMessageGroup("id1").size()).isEqualTo(1); input.send(createMessage("789", "id1", 3, 3, null)); - assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); + assertThat(messageGroupStore.getMessageGroup("id1").size()).isEqualTo(2); input.send(createMessage("456", "id1", 3, 2, null)); Message message1 = output.receive(500); Message message2 = output.receive(500); Message message3 = output.receive(500); - assertNotNull(message1); - assertEquals(1, new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()); - assertNotNull(message2); - assertEquals(2, new IntegrationMessageHeaderAccessor(message2).getSequenceNumber()); - assertNotNull(message3); - assertEquals(3, new IntegrationMessageHeaderAccessor(message3).getSequenceNumber()); + assertThat(message1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()).isEqualTo(1); + assertThat(message2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(message2).getSequenceNumber()).isEqualTo(2); + assertThat(message3).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(message3).getSequenceNumber()).isEqualTo(3); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/RouterFactoryBeanDelegationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/RouterFactoryBeanDelegationTests.java index 4a043db884..a7934dce66 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/RouterFactoryBeanDelegationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/RouterFactoryBeanDelegationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -62,21 +60,21 @@ public class RouterFactoryBeanDelegationTests { public void checkResolutionRequiredConfiguredOnTargetRouter() { @SuppressWarnings("unchecked") boolean resolutionRequired = (Boolean) new DirectFieldAccessor(router).getPropertyValue("resolutionRequired"); - assertTrue("The 'resolutionRequired' property should be 'true'", resolutionRequired); + assertThat(resolutionRequired).as("The 'resolutionRequired' property should be 'true'").isTrue(); } @Test public void routeWithMappedType() { input.send(new GenericMessage<>("test")); - assertNull(discard.receive(0)); - assertNotNull(strings.receive(0)); + assertThat(discard.receive(0)).isNull(); + assertThat(strings.receive(0)).isNotNull(); } @Test public void routeWithUnmappedType() { input.send(new GenericMessage<>(123)); - assertNull(strings.receive(0)); - assertNotNull(discard.receive(0)); + assertThat(strings.receive(0)).isNull(); + assertThat(discard.receive(0)).isNotNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/SelectorChainParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/SelectorChainParserTests.java index 6ef9a533ca..4404eeece3 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/SelectorChainParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/SelectorChainParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -53,11 +52,11 @@ public class SelectorChainParserTests { MessageSelector selector2 = (MessageSelector) context.getBean("selector2"); MessageSelectorChain chain = (MessageSelectorChain) context.getBean("selectorChain"); List selectors = this.getSelectors(chain); - assertEquals(VotingStrategy.ALL, this.getStrategy(chain)); - assertEquals(selector1, selectors.get(0)); - assertEquals(selector2, selectors.get(1)); - assertTrue(chain.accept(new GenericMessage<>("test"))); - assertTrue(this.context.containsBean("pojoSelector")); + assertThat(this.getStrategy(chain)).isEqualTo(VotingStrategy.ALL); + assertThat(selectors.get(0)).isEqualTo(selector1); + assertThat(selectors.get(1)).isEqualTo(selector2); + assertThat(chain.accept(new GenericMessage<>("test"))).isTrue(); + assertThat(this.context.containsBean("pojoSelector")).isTrue(); } @Test @@ -69,30 +68,30 @@ public class SelectorChainParserTests { MessageSelector selector5 = (MessageSelector) context.getBean("selector5"); MessageSelector selector6 = (MessageSelector) context.getBean("selector6"); MessageSelectorChain chain1 = (MessageSelectorChain) context.getBean("nestedSelectorChain"); - assertEquals(VotingStrategy.MAJORITY, this.getStrategy(chain1)); + assertThat(this.getStrategy(chain1)).isEqualTo(VotingStrategy.MAJORITY); List selectorList1 = this.getSelectors(chain1); - assertEquals(selector1, selectorList1.get(0)); - assertTrue(selectorList1.get(1) instanceof MessageSelectorChain); + assertThat(selectorList1.get(0)).isEqualTo(selector1); + assertThat(selectorList1.get(1) instanceof MessageSelectorChain).isTrue(); MessageSelectorChain chain2 = (MessageSelectorChain) selectorList1.get(1); - assertEquals(VotingStrategy.ALL, this.getStrategy(chain2)); + assertThat(this.getStrategy(chain2)).isEqualTo(VotingStrategy.ALL); List selectorList2 = this.getSelectors(chain2); - assertEquals(selector2, selectorList2.get(0)); - assertTrue(selectorList2.get(1) instanceof MessageSelectorChain); + assertThat(selectorList2.get(0)).isEqualTo(selector2); + assertThat(selectorList2.get(1) instanceof MessageSelectorChain).isTrue(); MessageSelectorChain chain3 = (MessageSelectorChain) selectorList2.get(1); - assertEquals(VotingStrategy.ANY, this.getStrategy(chain3)); + assertThat(this.getStrategy(chain3)).isEqualTo(VotingStrategy.ANY); List selectorList3 = this.getSelectors(chain3); - assertEquals(selector3, selectorList3.get(0)); - assertEquals(selector4, selectorList3.get(1)); - assertEquals(selector5, selectorList2.get(2)); - assertTrue(selectorList1.get(2) instanceof MessageSelectorChain); + assertThat(selectorList3.get(0)).isEqualTo(selector3); + assertThat(selectorList3.get(1)).isEqualTo(selector4); + assertThat(selectorList2.get(2)).isEqualTo(selector5); + assertThat(selectorList1.get(2) instanceof MessageSelectorChain).isTrue(); MessageSelectorChain chain4 = (MessageSelectorChain) selectorList1.get(2); - assertEquals(VotingStrategy.MAJORITY_OR_TIE, this.getStrategy(chain4)); + assertThat(this.getStrategy(chain4)).isEqualTo(VotingStrategy.MAJORITY_OR_TIE); List selectorList4 = this.getSelectors(chain4); - assertEquals(selector6, selectorList4.get(0)); - assertTrue(chain1.accept(new GenericMessage<>("test1"))); - assertTrue(chain2.accept(new GenericMessage<>("test2"))); - assertTrue(chain3.accept(new GenericMessage<>("test3"))); - assertTrue(chain4.accept(new GenericMessage<>("test4"))); + assertThat(selectorList4.get(0)).isEqualTo(selector6); + assertThat(chain1.accept(new GenericMessage<>("test1"))).isTrue(); + assertThat(chain2.accept(new GenericMessage<>("test2"))).isTrue(); + assertThat(chain3.accept(new GenericMessage<>("test3"))).isTrue(); + assertThat(chain4.accept(new GenericMessage<>("test4"))).isTrue(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ServiceActivatorAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ServiceActivatorAnnotationPostProcessorTests.java index ced53628bc..9a65717fbe 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ServiceActivatorAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ServiceActivatorAnnotationPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -53,13 +52,13 @@ public class ServiceActivatorAnnotationPostProcessorTests { context.refresh(); SimpleServiceActivatorAnnotationTestBean testBean = context.getBean("testBean", SimpleServiceActivatorAnnotationTestBean.class); - assertEquals(1, latch.getCount()); - assertNull(testBean.getMessageText()); + assertThat(latch.getCount()).isEqualTo(1); + assertThat(testBean.getMessageText()).isNull(); MessageChannel testChannel = (MessageChannel) context.getBean("testChannel"); testChannel.send(new GenericMessage<>("test-123")); latch.await(1000, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); - assertEquals("test-123", testBean.getMessageText()); + assertThat(latch.getCount()).isEqualTo(0); + assertThat(testBean.getMessageText()).isEqualTo("test-123"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java index dc79eb9db0..bbe3f8450c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.BDDMockito.willAnswer; @@ -92,8 +90,8 @@ public class SourcePollingChannelAdapterFactoryBeanTests { context.registerEndpoint("testPollingEndpoint", factoryBean.getObject()); context.refresh(); Message message = outputChannel.receive(5000); - assertEquals("test", message.getPayload()); - assertTrue("adviceChain was not applied", adviceApplied.get()); + assertThat(message.getPayload()).isEqualTo("test"); + assertThat(adviceApplied.get()).as("adviceChain was not applied").isTrue(); context.close(); } @@ -133,9 +131,9 @@ public class SourcePollingChannelAdapterFactoryBeanTests { context.registerEndpoint("testPollingEndpoint", factoryBean.getObject()); context.refresh(); Message message = outputChannel.receive(5000); - assertEquals("test", message.getPayload()); - assertEquals(1, count.get()); - assertTrue("adviceChain was not applied", adviceApplied.get()); + assertThat(message.getPayload()).isEqualTo("test"); + assertThat(count.get()).isEqualTo(1); + assertThat(adviceApplied.get()).as("adviceChain was not applied").isTrue(); context.close(); } @@ -183,7 +181,7 @@ public class SourcePollingChannelAdapterFactoryBeanTests { pollingChannelAdapter.start(); - assertTrue(startLatch.await(10, TimeUnit.SECONDS)); + assertThat(startLatch.await(10, TimeUnit.SECONDS)).isTrue(); pollingChannelAdapter.stop(); taskScheduler.shutdown(); @@ -215,8 +213,8 @@ public class SourcePollingChannelAdapterFactoryBeanTests { pollingChannelAdapter.start(); Message receive = outputChannel.receive(10_000); - assertNotNull(receive); - assertEquals(true, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(true); pollingChannelAdapter.stop(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/TopLevelSelectorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/TopLevelSelectorParserTests.java index aa1772e26b..da22ce50a5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/TopLevelSelectorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/TopLevelSelectorParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -41,7 +41,7 @@ public class TopLevelSelectorParserTests { @Test public void topLevelSelector() { MessageSelector selector = (MessageSelector) context.getBean("selector"); - assertTrue(selector.accept(new GenericMessage("test"))); + assertThat(selector.accept(new GenericMessage("test"))).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/WireTapParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/WireTapParserTests.java index 64271b0a9f..ab84ac2fbe 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/WireTapParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/WireTapParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.config; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -71,41 +67,41 @@ public class WireTapParserTests { @Test public void simpleWireTap() { - assertNull(wireTapChannel.receive(0)); + assertThat(wireTapChannel.receive(0)).isNull(); Message original = new GenericMessage("test"); noSelectors.send(original); Message intercepted = wireTapChannel.receive(0); - assertNotNull(intercepted); - assertEquals(original, intercepted); + assertThat(intercepted).isNotNull(); + assertThat(intercepted).isEqualTo(original); } @Test public void simpleWireTapWithIdAndSelectorExpression() { - assertThat(TestUtils.getPropertyValue(wireTap, "selector"), instanceOf(ExpressionEvaluatingSelector.class)); + assertThat(TestUtils.getPropertyValue(wireTap, "selector")).isInstanceOf(ExpressionEvaluatingSelector.class); Message original = new GenericMessage("test"); withId.send(original); Message intercepted = wireTapChannel.receive(0); - assertNotNull(intercepted); - assertEquals(original, intercepted); + assertThat(intercepted).isNotNull(); + assertThat(intercepted).isEqualTo(original); } @Test public void wireTapWithAcceptingSelector() { - assertNull(wireTapChannel.receive(0)); + assertThat(wireTapChannel.receive(0)).isNull(); Message original = new GenericMessage("test"); accepting.send(original); Message intercepted = wireTapChannel.receive(0); - assertNotNull(intercepted); - assertEquals(original, intercepted); + assertThat(intercepted).isNotNull(); + assertThat(intercepted).isEqualTo(original); } @Test public void wireTapWithRejectingSelector() { - assertNull(wireTapChannel.receive(0)); + assertThat(wireTapChannel.receive(0)).isNull(); Message original = new GenericMessage("test"); rejecting.send(original); Message intercepted = wireTapChannel.receive(0); - assertNull(intercepted); + assertThat(intercepted).isNull(); } @Test @@ -125,9 +121,9 @@ public class WireTapParserTests { otherTimeoutCount++; } } - assertEquals(4, defaultTimeoutCount); - assertEquals(1, expectedTimeoutCount); - assertEquals(0, otherTimeoutCount); + assertThat(defaultTimeoutCount).isEqualTo(4); + assertThat(expectedTimeoutCount).isEqualTo(1); + assertThat(otherTimeoutCount).isEqualTo(0); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AggregatorAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AggregatorAnnotationTests.java index 36e5dc147a..aa714fcf2c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AggregatorAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AggregatorAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 @@ package org.springframework.integration.config.annotation; -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.assertj.core.api.Assertions.assertThat; import static org.springframework.integration.test.util.TestUtils.getPropertyValue; import java.lang.reflect.Method; -import org.junit.Assert; import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; @@ -53,11 +48,12 @@ public class AggregatorAnnotationTests { new String[] { "classpath:/org/springframework/integration/config/annotation/testAnnotatedAggregator.xml" }); final String endpointName = "endpointWithDefaultAnnotation"; MessageHandler aggregator = this.getAggregator(context, endpointName); - assertTrue(getPropertyValue(aggregator, "releaseStrategy") instanceof SimpleSequenceSizeReleaseStrategy); - assertNull(getPropertyValue(aggregator, "outputChannel")); - assertTrue(getPropertyValue(aggregator, "discardChannel") instanceof NullChannel); - assertEquals(-1L, getPropertyValue(aggregator, "messagingTemplate.sendTimeout")); - assertEquals(false, getPropertyValue(aggregator, "sendPartialResultOnExpiry")); + assertThat(getPropertyValue(aggregator, "releaseStrategy") instanceof SimpleSequenceSizeReleaseStrategy) + .isTrue(); + assertThat(getPropertyValue(aggregator, "outputChannel")).isNull(); + assertThat(getPropertyValue(aggregator, "discardChannel") instanceof NullChannel).isTrue(); + assertThat(getPropertyValue(aggregator, "messagingTemplate.sendTimeout")).isEqualTo(-1L); + assertThat(getPropertyValue(aggregator, "sendPartialResultOnExpiry")).isEqualTo(false); context.close(); } @@ -67,11 +63,12 @@ public class AggregatorAnnotationTests { new String[] { "classpath:/org/springframework/integration/config/annotation/testAnnotatedAggregator.xml" }); final String endpointName = "endpointWithCustomizedAnnotation"; MessageHandler aggregator = this.getAggregator(context, endpointName); - assertTrue(getPropertyValue(aggregator, "releaseStrategy") instanceof SimpleSequenceSizeReleaseStrategy); - assertEquals("outputChannel", getPropertyValue(aggregator, "outputChannelName")); - assertEquals("discardChannel", getPropertyValue(aggregator, "discardChannelName")); - assertEquals(98765432L, getPropertyValue(aggregator, "messagingTemplate.sendTimeout")); - assertEquals(true, getPropertyValue(aggregator, "sendPartialResultOnExpiry")); + assertThat(getPropertyValue(aggregator, "releaseStrategy") instanceof SimpleSequenceSizeReleaseStrategy) + .isTrue(); + assertThat(getPropertyValue(aggregator, "outputChannelName")).isEqualTo("outputChannel"); + assertThat(getPropertyValue(aggregator, "discardChannelName")).isEqualTo("discardChannel"); + assertThat(getPropertyValue(aggregator, "messagingTemplate.sendTimeout")).isEqualTo(98765432L); + assertThat(getPropertyValue(aggregator, "sendPartialResultOnExpiry")).isEqualTo(true); context.close(); } @@ -82,14 +79,14 @@ public class AggregatorAnnotationTests { final String endpointName = "endpointWithDefaultAnnotationAndCustomReleaseStrategy"; MessageHandler aggregator = this.getAggregator(context, endpointName); Object releaseStrategy = getPropertyValue(aggregator, "releaseStrategy"); - Assert.assertTrue(releaseStrategy instanceof MethodInvokingReleaseStrategy); + assertThat(releaseStrategy instanceof MethodInvokingReleaseStrategy).isTrue(); MethodInvokingReleaseStrategy releaseStrategyAdapter = (MethodInvokingReleaseStrategy) releaseStrategy; Object handlerMethods = new DirectFieldAccessor(releaseStrategyAdapter) .getPropertyValue("adapter.delegate.handlerMethods"); - assertNull(handlerMethods); + assertThat(handlerMethods).isNull(); Object handlerMethod = new DirectFieldAccessor(releaseStrategyAdapter) .getPropertyValue("adapter.delegate.handlerMethod"); - assertTrue(handlerMethod.toString().contains("completionChecker")); + assertThat(handlerMethod.toString().contains("completionChecker")).isTrue(); context.close(); } @@ -100,18 +97,19 @@ public class AggregatorAnnotationTests { final String endpointName = "endpointWithCorrelationStrategy"; MessageHandler aggregator = this.getAggregator(context, endpointName); Object correlationStrategy = getPropertyValue(aggregator, "correlationStrategy"); - Assert.assertTrue(correlationStrategy instanceof MethodInvokingCorrelationStrategy); + assertThat(correlationStrategy instanceof MethodInvokingCorrelationStrategy).isTrue(); MethodInvokingCorrelationStrategy releaseStrategyAdapter = (MethodInvokingCorrelationStrategy) correlationStrategy; DirectFieldAccessor processorAccessor = new DirectFieldAccessor(new DirectFieldAccessor(new DirectFieldAccessor(releaseStrategyAdapter) .getPropertyValue("processor")).getPropertyValue("delegate")); Object targetObject = processorAccessor.getPropertyValue("targetObject"); - assertSame(context.getBean(endpointName), targetObject); - assertNull(processorAccessor.getPropertyValue("handlerMethods")); + assertThat(targetObject).isSameAs(context.getBean(endpointName)); + assertThat(processorAccessor.getPropertyValue("handlerMethods")).isNull(); Object handlerMethod = processorAccessor.getPropertyValue("handlerMethod"); - assertNotNull(handlerMethod); + assertThat(handlerMethod).isNotNull(); DirectFieldAccessor handlerMethodAccessor = new DirectFieldAccessor(handlerMethod); - Method completionCheckerMethod = (Method) handlerMethodAccessor.getPropertyValue("invocableHandlerMethod.method"); - assertEquals("correlate", completionCheckerMethod.getName()); + Method completionCheckerMethod = (Method) handlerMethodAccessor.getPropertyValue( + "invocableHandlerMethod.method"); + assertThat(completionCheckerMethod.getName()).isEqualTo("correlate"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AnnotatedEndpointActivationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AnnotatedEndpointActivationTests.java index 42b4e5e084..2b68041a23 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AnnotatedEndpointActivationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/AnnotatedEndpointActivationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; @@ -83,21 +81,21 @@ public class AnnotatedEndpointActivationTests { public void sendAndReceive() { this.input.send(new GenericMessage<>("foo")); Message message = this.output.receive(100); - assertNotNull(message); - assertEquals("foo: 1", message.getPayload()); - assertEquals(1, count); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo: 1"); + assertThat(count).isEqualTo(1); - assertTrue(this.applicationContext.containsBean("annotatedEndpoint.process.serviceActivator")); - assertTrue(this.applicationContext.containsBean("annotatedEndpoint2.process.serviceActivator")); + assertThat(this.applicationContext.containsBean("annotatedEndpoint.process.serviceActivator")).isTrue(); + assertThat(this.applicationContext.containsBean("annotatedEndpoint2.process.serviceActivator")).isTrue(); } @Test public void sendAndReceiveAsync() { this.inputAsync.send(new GenericMessage<>("foo")); Message message = this.outputAsync.receive(100); - assertNotNull(message); - assertEquals("foo", message.getPayload()); - assertTrue(this.applicationContext.containsBean("annotatedEndpoint3.process.serviceActivator")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); + assertThat(this.applicationContext.containsBean("annotatedEndpoint3.process.serviceActivator")).isTrue(); } @Test @@ -105,9 +103,9 @@ public class AnnotatedEndpointActivationTests { MessageChannel input = this.applicationContext.getBean("inputImplicit", MessageChannel.class); input.send(new GenericMessage<>("foo")); Message message = this.output.receive(100); - assertNotNull(message); - assertEquals("foo: 1", message.getPayload()); - assertEquals(1, count); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo: 1"); + assertThat(count).isEqualTo(1); } @Test(expected = MessageDeliveryException.class) @@ -124,9 +122,9 @@ public class AnnotatedEndpointActivationTests { applicationContext.start(); this.input.send(new GenericMessage<>("foo")); Message message = this.output.receive(100); - assertNotNull(message); - assertEquals("foo: 1", message.getPayload()); - assertEquals(1, count); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo: 1"); + assertThat(count).isEqualTo(1); } @MessageEndpoint diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/BridgeFromIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/BridgeFromIntegrationTests.java index e1e5e0cb04..18ee116d8e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/BridgeFromIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/BridgeFromIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 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,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -59,8 +58,8 @@ public class BridgeFromIntegrationTests { Message receive = this.outputChannel.receive(10_000); - assertNotNull(receive); - assertEquals("hello world", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("hello world"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java index 01cbef3e5b..9f4bf15dd6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -73,7 +72,7 @@ public class CustomMessagingAnnotationTests { @Test public void testLogAnnotation() { - assertNotNull(this.loggingHandler); + assertThat(this.loggingHandler).isNotNull(); Log log = spy(TestUtils.getPropertyValue(this.loggingHandler, "messageLogger", Log.class)); @@ -92,7 +91,7 @@ public class CustomMessagingAnnotationTests { verify(log) .warn(argumentCaptor.capture()); - assertEquals("foo for baz", argumentCaptor.getValue()); + assertThat(argumentCaptor.getValue()).isEqualTo("foo for baz"); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java index d1d2964d02..60efe670d6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java @@ -16,12 +16,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.List; @@ -82,8 +77,8 @@ public class FilterAnnotationPostProcessorTests { context.registerBean("adviceChain", advice); testValidFilter(new TestFilterWithAdviceDiscardWithin()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); - assertSame(advice, TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)); - assertTrue(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)).isSameAs(advice); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)).isTrue(); } @Test @@ -95,10 +90,10 @@ public class FilterAnnotationPostProcessorTests { testValidFilter(new TestFilterWithAdviceDiscardWithinTwice()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); List adviceList = TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class); - assertEquals(2, adviceList.size()); - assertSame(advice1, adviceList.get(0)); - assertSame(advice2, adviceList.get(1)); - assertTrue(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)); + assertThat(adviceList.size()).isEqualTo(2); + assertThat(adviceList.get(0)).isSameAs(advice1); + assertThat(adviceList.get(1)).isSameAs(advice2); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)).isTrue(); } @Test @@ -107,8 +102,8 @@ public class FilterAnnotationPostProcessorTests { context.registerBean("adviceChain", advice); testValidFilter(new TestFilterWithAdviceDiscardWithout()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); - assertSame(advice, TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)); - assertFalse(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)).isSameAs(advice); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)).isFalse(); } @Test @@ -117,8 +112,8 @@ public class FilterAnnotationPostProcessorTests { context.registerBean("adviceChain", new TestAdvice[] { advice }); testValidFilter(new TestFilterWithAdviceDiscardWithin()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); - assertSame(advice, TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)); - assertTrue(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)).isSameAs(advice); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)).isTrue(); } @Test @@ -132,12 +127,12 @@ public class FilterAnnotationPostProcessorTests { testValidFilter(new TestFilterWithAdviceDiscardWithinTwice()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); List adviceList = TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class); - assertEquals(4, adviceList.size()); - assertSame(advice1, adviceList.get(0)); - assertSame(advice2, adviceList.get(1)); - assertSame(advice3, adviceList.get(2)); - assertSame(advice4, adviceList.get(3)); - assertTrue(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)); + assertThat(adviceList.size()).isEqualTo(4); + assertThat(adviceList.get(0)).isSameAs(advice1); + assertThat(adviceList.get(1)).isSameAs(advice2); + assertThat(adviceList.get(2)).isSameAs(advice3); + assertThat(adviceList.get(3)).isSameAs(advice4); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)).isTrue(); } @Test @@ -146,8 +141,8 @@ public class FilterAnnotationPostProcessorTests { context.registerBean("adviceChain", Collections.singletonList(advice)); testValidFilter(new TestFilterWithAdviceDiscardWithin()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); - assertSame(advice, TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)); - assertTrue(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)).isSameAs(advice); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)).isTrue(); } @Test @@ -161,12 +156,12 @@ public class FilterAnnotationPostProcessorTests { testValidFilter(new TestFilterWithAdviceDiscardWithinTwice()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); List adviceList = TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class); - assertEquals(4, adviceList.size()); - assertSame(advice1, adviceList.get(0)); - assertSame(advice2, adviceList.get(1)); - assertSame(advice3, adviceList.get(2)); - assertSame(advice4, adviceList.get(3)); - assertTrue(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)); + assertThat(adviceList.size()).isEqualTo(4); + assertThat(adviceList.get(0)).isSameAs(advice1); + assertThat(adviceList.get(1)).isSameAs(advice2); + assertThat(adviceList.get(2)).isSameAs(advice3); + assertThat(adviceList.get(3)).isSameAs(advice4); + assertThat(TestUtils.getPropertyValue(endpoint, "handler.postProcessWithinAdvice", Boolean.class)).isTrue(); } @Test @@ -192,9 +187,9 @@ public class FilterAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("good")); Message passed = outputChannel.receive(0); - assertNotNull(passed); + assertThat(passed).isNotNull(); inputChannel.send(new GenericMessage<>("bad")); - assertNull(outputChannel.receive(0)); + assertThat(outputChannel.receive(0)).isNull(); context.stop(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorAopIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorAopIntegrationTests.java index b86f3e9526..86b45d47ce 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorAopIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorAopIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.annotation; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.atomic.AtomicInteger; @@ -58,14 +56,14 @@ public class MessagingAnnotationPostProcessorAopIntegrationTests { @Test public void parseConfig() { - assertThat(this.input, notNullValue()); + assertThat(this.input).isNotNull(); } @Test public void sendMessage() { input.send(MessageBuilder.withPayload(new AtomicInteger(0)).build()); Message reply = output.receive(1000); - assertEquals(111, ((Integer) reply.getPayload()).intValue()); + assertThat(((Integer) reply.getPayload()).intValue()).isEqualTo(111); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorChannelCreationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorChannelCreationTests.java index d3e71dbb04..46ee14376d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorChannelCreationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorChannelCreationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-2019 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,8 @@ package org.springframework.integration.config.annotation; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; @@ -79,8 +78,8 @@ public class MessagingAnnotationPostProcessorChannelCreationTests { fail("Expected a DestinationResolutionException"); } catch (DestinationResolutionException e) { - assertThat(e.getMessage(), - containsString("A bean definition with name 'channel' exists, but failed to be created")); + assertThat(e.getMessage()) + .contains("A bean definition with name 'channel' exists, but failed to be created"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java index 94320ee95a..f9233659ab 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java @@ -16,9 +16,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -69,9 +67,9 @@ public class MessagingAnnotationPostProcessorTests { postProcessor.afterPropertiesSet(); ServiceActivatorAnnotatedBean bean = new ServiceActivatorAnnotatedBean(); postProcessor.postProcessAfterInitialization(bean, "testBean"); - assertTrue(context.containsBean("testBean.test.serviceActivator")); + assertThat(context.containsBean("testBean.test.serviceActivator")).isTrue(); Object endpoint = context.getBean("testBean.test.serviceActivator"); - assertTrue(endpoint instanceof AbstractEndpoint); + assertThat(endpoint instanceof AbstractEndpoint).isTrue(); context.close(); } @@ -83,7 +81,7 @@ public class MessagingAnnotationPostProcessorTests { PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); inputChannel.send(new GenericMessage("world")); Message reply = outputChannel.receive(0); - assertEquals("hello world", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("hello world"); context.close(); } @@ -98,13 +96,13 @@ public class MessagingAnnotationPostProcessorTests { GenericMessage messageToSend = new GenericMessage("world"); inputChannel.send(messageToSend); Message message = outputChannel.receive(1000); - assertEquals("hello world", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello world"); inputChannel = context.getBean("advisedIn", MessageChannel.class); outputChannel = context.getBean("advisedOut", PollableChannel.class); inputChannel.send(messageToSend); message = outputChannel.receive(1000); - assertEquals("hello world advised", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello world advised"); context.close(); } @@ -117,7 +115,7 @@ public class MessagingAnnotationPostProcessorTests { PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); - assertEquals("hello world", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello world"); context.close(); } @@ -130,7 +128,7 @@ public class MessagingAnnotationPostProcessorTests { PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); inputChannel.send(new GenericMessage<>("123")); Message message = outputChannel.receive(1000); - assertEquals(246, message.getPayload()); + assertThat(message.getPayload()).isEqualTo(246); context.close(); } @@ -149,8 +147,8 @@ public class MessagingAnnotationPostProcessorTests { MessageChannel testChannel = channelResolver.resolveDestination("testChannel"); testChannel.send(new GenericMessage("foo")); latch.await(1000, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); - assertEquals("foo", testBean.getMessageText()); + assertThat(latch.getCount()).isEqualTo(0); + assertThat(testBean.getMessageText()).isEqualTo("foo"); context.close(); } @@ -180,10 +178,10 @@ public class MessagingAnnotationPostProcessorTests { .setReplyChannelName("outputChannel").build(); inputChannel.send(message); Message reply = outputChannel.receive(0); - assertNotNull(reply); + assertThat(reply).isNotNull(); eventBus.send(new GenericMessage<>("foo")); - assertTrue(bean.getInvoked()); + assertThat(bean.getInvoked()).isTrue(); context.close(); } @@ -204,7 +202,7 @@ public class MessagingAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); - assertEquals("hello world", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello world"); context.close(); } @@ -222,7 +220,7 @@ public class MessagingAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); - assertEquals("hello world", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello world"); context.close(); } @@ -242,7 +240,7 @@ public class MessagingAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); - assertEquals("hello world", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello world"); context.close(); } @@ -260,7 +258,7 @@ public class MessagingAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("ABC")); Message message = outputChannel.receive(1000); - assertEquals("test-ABC", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("test-ABC"); context.close(); } @@ -278,7 +276,7 @@ public class MessagingAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("ABC")); Message message = outputChannel.receive(1000); - assertEquals("test-ABC", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("test-ABC"); context.close(); } @@ -298,7 +296,7 @@ public class MessagingAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("ABC")); Message message = outputChannel.receive(1000); - assertEquals("test-ABC", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("test-ABC"); context.close(); } @@ -317,7 +315,7 @@ public class MessagingAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("foo")); Message reply = outputChannel.receive(0); - assertEquals("FOO", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("FOO"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java index a89a51f11f..ec7f3b7713 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,15 +16,8 @@ package org.springframework.integration.config.annotation; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.ArrayList; import java.util.List; @@ -36,7 +29,6 @@ import java.util.stream.Stream; import javax.annotation.Resource; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -153,38 +145,37 @@ public class MessagingAnnotationsWithBeanAnnotationTests { //this.sourcePollingChannelAdapter.start(); for (int i = 0; i < 10; i++) { Message receive = this.discardChannel.receive(10000); - assertNotNull(receive); - assertEquals(0, ((Integer) receive.getPayload()) % 2); + assertThat(receive).isNotNull(); + assertThat(((Integer) receive.getPayload()) % 2).isEqualTo(0); receive = this.counterErrorChannel.receive(10000); - assertNotNull(receive); - assertThat(receive, instanceOf(ErrorMessage.class)); - assertThat(receive.getPayload(), instanceOf(MessageRejectedException.class)); + assertThat(receive).isNotNull(); + assertThat(receive).isInstanceOf(ErrorMessage.class); + assertThat(receive.getPayload()).isInstanceOf(MessageRejectedException.class); MessageRejectedException exception = (MessageRejectedException) receive.getPayload(); - assertThat(exception.getMessage(), - containsString("MessageFilter " + - "'messagingAnnotationsWithBeanAnnotationTests.ContextConfiguration.filter.filter.handler'" + - " rejected Message")); + assertThat(exception.getMessage()).contains("MessageFilter " + + "'messagingAnnotationsWithBeanAnnotationTests.ContextConfiguration.filter.filter.handler'" + + " rejected Message"); } for (Message message : this.collector) { - assertNotEquals(0, ((Integer) message.getPayload()) % 2); + assertThat(((Integer) message.getPayload()) % 2).isNotEqualTo(0); MessageHistory messageHistory = MessageHistory.read(message); - assertNotNull(messageHistory); + assertThat(messageHistory).isNotNull(); String messageHistoryString = messageHistory.toString(); - assertThat(messageHistoryString, Matchers.containsString("routerChannel")); - assertThat(messageHistoryString, Matchers.containsString("filterChannel")); - assertThat(messageHistoryString, Matchers.containsString("aggregatorChannel")); - assertThat(messageHistoryString, Matchers.containsString("splitterChannel")); - assertThat(messageHistoryString, Matchers.containsString("serviceChannel")); - assertThat(messageHistoryString, Matchers.not(Matchers.containsString("discardChannel"))); + assertThat(messageHistoryString).contains("routerChannel"); + assertThat(messageHistoryString).contains("filterChannel"); + assertThat(messageHistoryString).contains("aggregatorChannel"); + assertThat(messageHistoryString).contains("splitterChannel"); + assertThat(messageHistoryString).contains("serviceChannel"); + assertThat(messageHistoryString).doesNotContain("discardChannel"); } - assertNull(this.skippedServiceActivator); - assertNull(this.skippedMessageHandler); - assertNull(this.skippedChannel); - assertNull(this.skippedChannel2); - assertNull(this.skippedMessageSource); + assertThat(this.skippedServiceActivator).isNull(); + assertThat(this.skippedMessageHandler).isNull(); + assertThat(this.skippedChannel).isNull(); + assertThat(this.skippedChannel2).isNull(); + assertThat(this.skippedMessageSource).isNull(); QueueChannel replyChannel = new QueueChannel(); @@ -196,8 +187,8 @@ public class MessagingAnnotationsWithBeanAnnotationTests { Message receive = replyChannel.receive(10_000); - assertNotNull(receive); - assertEquals("FOO", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("FOO"); message = MessageBuilder.withPayload("BAR") .setReplyChannel(replyChannel) @@ -207,21 +198,21 @@ public class MessagingAnnotationsWithBeanAnnotationTests { receive = replyChannel.receive(10_000); - assertNotNull(receive); - assertEquals("bar", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("bar"); this.consumerServiceChannel.send(new GenericMessage<>("baz")); - assertFalse(this.stringCollector.isEmpty()); - assertEquals("baz", this.stringCollector.iterator().next()); + assertThat(this.stringCollector.isEmpty()).isFalse(); + assertThat(this.stringCollector.iterator().next()).isEqualTo("baz"); this.collector.clear(); this.messageConsumerServiceChannel.send(new GenericMessage<>("123")); - assertFalse(this.collector.isEmpty()); + assertThat(this.collector.isEmpty()).isFalse(); Message next = this.collector.iterator().next(); - assertEquals("123", next.getPayload()); + assertThat(next.getPayload()).isEqualTo("123"); } @Test @@ -231,9 +222,9 @@ public class MessagingAnnotationsWithBeanAnnotationTests { fail("BeanCreationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanCreationException.class)); - assertThat(e.getCause(), instanceOf(BeanDefinitionValidationException.class)); - assertThat(e.getMessage(), containsString("The attribute causing the ambiguity is: [applySequence].")); + assertThat(e).isInstanceOf(BeanCreationException.class); + assertThat(e.getCause()).isInstanceOf(BeanDefinitionValidationException.class); + assertThat(e.getMessage()).contains("The attribute causing the ambiguity is: [applySequence]."); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java index 45dc5e1793..c315107773 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java @@ -16,7 +16,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.List; @@ -77,7 +77,7 @@ public class RouterAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("foo")); Message replyMessage = outputChannel.receive(0); - assertEquals("foo", replyMessage.getPayload()); + assertThat(replyMessage.getPayload()).isEqualTo("foo"); context.stop(); } @@ -92,12 +92,12 @@ public class RouterAnnotationPostProcessorTests { routingChannel.send(new GenericMessage<>(Collections.singletonList("foo"))); Message replyMessage = stringChannel.receive(0); - assertEquals(Collections.singletonList("foo"), replyMessage.getPayload()); + assertThat(replyMessage.getPayload()).isEqualTo(Collections.singletonList("foo")); // The SpEL ReflectiveMethodExecutor does a conversion of a single value to a List routingChannel.send(new GenericMessage<>(2)); replyMessage = integerChannel.receive(0); - assertEquals(2, replyMessage.getPayload()); + assertThat(replyMessage.getPayload()).isEqualTo(2); context.stop(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java index 00f7680d92..119e3949b5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java @@ -16,11 +16,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.After; import org.junit.Before; @@ -71,26 +67,26 @@ public class SplitterAnnotationPostProcessorTests { context.refresh(); inputChannel.send(new GenericMessage<>("this.is.a.test")); Message message1 = outputChannel.receive(500); - assertNotNull(message1); - assertEquals("this", message1.getPayload()); + assertThat(message1).isNotNull(); + assertThat(message1.getPayload()).isEqualTo("this"); Message message2 = outputChannel.receive(500); - assertNotNull(message2); - assertEquals("is", message2.getPayload()); + assertThat(message2).isNotNull(); + assertThat(message2.getPayload()).isEqualTo("is"); Message message3 = outputChannel.receive(500); - assertNotNull(message3); - assertEquals("a", message3.getPayload()); + assertThat(message3).isNotNull(); + assertThat(message3.getPayload()).isEqualTo("a"); Message message4 = outputChannel.receive(500); - assertNotNull(message4); - assertEquals("test", message4.getPayload()); - assertNull(outputChannel.receive(0)); + assertThat(message4).isNotNull(); + assertThat(message4.getPayload()).isEqualTo("test"); + assertThat(outputChannel.receive(0)).isNull(); AbstractEndpoint endpoint = context.getBean(AbstractEndpoint.class); - assertTrue(splitter.isRunning()); + assertThat(splitter.isRunning()).isTrue(); endpoint.stop(); - assertFalse(splitter.isRunning()); + assertThat(splitter.isRunning()).isFalse(); endpoint.start(); - assertTrue(splitter.isRunning()); + assertThat(splitter.isRunning()).isTrue(); context.stop(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SubscriberOrderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SubscriberOrderTests.java index 765f818e34..27cc685fd9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SubscriberOrderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SubscriberOrderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.annotation; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -61,12 +61,12 @@ public class SubscriberOrderTests { channel.send(new GenericMessage("test-4")); channel.send(new GenericMessage("test-5")); List calls = testBean.calls; - assertEquals(5, calls.size()); - assertEquals(1, calls.get(0).intValue()); - assertEquals(2, calls.get(1).intValue()); - assertEquals(3, calls.get(2).intValue()); - assertEquals(4, calls.get(3).intValue()); - assertEquals(5, calls.get(4).intValue()); + assertThat(calls.size()).isEqualTo(5); + assertThat(calls.get(0).intValue()).isEqualTo(1); + assertThat(calls.get(1).intValue()).isEqualTo(2); + assertThat(calls.get(2).intValue()).isEqualTo(3); + assertThat(calls.get(3).intValue()).isEqualTo(4); + assertThat(calls.get(4).intValue()).isEqualTo(5); context.close(); } @@ -94,21 +94,21 @@ public class SubscriberOrderTests { channel.send(new GenericMessage("test-8")); channel.send(new GenericMessage("test-9")); channel.send(new GenericMessage("test-10")); - assertEquals(10, testBean.calls.size()); - assertEquals(1, testBean.calls.get(0).intValue()); - assertEquals(1, testBean.calls.get(1).intValue()); - assertEquals(2, testBean.calls.get(2).intValue()); - assertEquals(2, testBean.calls.get(3).intValue()); - assertEquals(3, testBean.calls.get(4).intValue()); - assertEquals(3, testBean.calls.get(5).intValue()); - assertEquals(4, testBean.calls.get(6).intValue()); - assertEquals(4, testBean.calls.get(7).intValue()); - assertEquals(5, testBean.calls.get(8).intValue()); - assertEquals(5, testBean.calls.get(9).intValue()); + assertThat(testBean.calls.size()).isEqualTo(10); + assertThat(testBean.calls.get(0).intValue()).isEqualTo(1); + assertThat(testBean.calls.get(1).intValue()).isEqualTo(1); + assertThat(testBean.calls.get(2).intValue()).isEqualTo(2); + assertThat(testBean.calls.get(3).intValue()).isEqualTo(2); + assertThat(testBean.calls.get(4).intValue()).isEqualTo(3); + assertThat(testBean.calls.get(5).intValue()).isEqualTo(3); + assertThat(testBean.calls.get(6).intValue()).isEqualTo(4); + assertThat(testBean.calls.get(7).intValue()).isEqualTo(4); + assertThat(testBean.calls.get(8).intValue()).isEqualTo(5); + assertThat(testBean.calls.get(9).intValue()).isEqualTo(5); testBean.reset(); channel.send(new GenericMessage("test-11")); - assertEquals(1, testBean.calls.size()); - assertEquals(1, testBean.calls.get(0).intValue()); + assertThat(testBean.calls.size()).isEqualTo(1); + assertThat(testBean.calls.get(0).intValue()).isEqualTo(1); context.close(); } @@ -131,12 +131,12 @@ public class SubscriberOrderTests { channel.send(new GenericMessage("test-4")); channel.send(new GenericMessage("test-5")); List calls = testBean.calls; - assertEquals(5, calls.size()); - assertEquals(1, calls.get(0).intValue()); - assertEquals(2, calls.get(1).intValue()); - assertEquals(3, calls.get(2).intValue()); - assertEquals(4, calls.get(3).intValue()); - assertEquals(5, calls.get(4).intValue()); + assertThat(calls.size()).isEqualTo(5); + assertThat(calls.get(0).intValue()).isEqualTo(1); + assertThat(calls.get(1).intValue()).isEqualTo(2); + assertThat(calls.get(2).intValue()).isEqualTo(3); + assertThat(calls.get(3).intValue()).isEqualTo(4); + assertThat(calls.get(4).intValue()).isEqualTo(5); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BarrierParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BarrierParserTests.java index 0749d33d27..f512c1d854 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BarrierParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BarrierParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2019 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,12 +16,7 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -79,7 +74,7 @@ public class BarrierParserTests { this.in.send(new GenericMessage("foo")); this.release.send(new GenericMessage("bar")); Message received = out.receive(10000); - assertNotNull(received); + assertThat(received).isNotNull(); this.barrier1.stop(); } @@ -87,15 +82,14 @@ public class BarrierParserTests { public void parserFieldPopulationTests() { BarrierMessageHandler handler = TestUtils.getPropertyValue(this.barrier1, "handler", BarrierMessageHandler.class); - assertEquals(10000L, TestUtils.getPropertyValue(handler, "timeout")); - assertTrue(TestUtils.getPropertyValue(handler, "requiresReply", Boolean.class)); - assertThat(TestUtils.getPropertyValue(this.barrier2, "handler.correlationStrategy"), - instanceOf(HeaderAttributeCorrelationStrategy.class)); - assertThat(TestUtils.getPropertyValue(this.barrier3, "handler.messageGroupProcessor"), - instanceOf(TestMGP.class)); - assertThat(TestUtils.getPropertyValue(this.barrier3, "handler.correlationStrategy"), - instanceOf(TestCS.class)); - assertSame(handler.getDiscardChannel(), this.discards); + assertThat(TestUtils.getPropertyValue(handler, "timeout")).isEqualTo(10000L); + assertThat(TestUtils.getPropertyValue(handler, "requiresReply", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(this.barrier2, "handler.correlationStrategy")) + .isInstanceOf(HeaderAttributeCorrelationStrategy.class); + assertThat(TestUtils.getPropertyValue(this.barrier3, "handler.messageGroupProcessor")) + .isInstanceOf(TestMGP.class); + assertThat(TestUtils.getPropertyValue(this.barrier3, "handler.correlationStrategy")).isInstanceOf(TestCS.class); + assertThat(this.discards).isSameAs(handler.getDiscardChannel()); } public static class TestMGP implements MessageGroupProcessor { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java index e76ad2a0cc..e769a3ad83 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; -import org.hamcrest.Factory; -import org.hamcrest.Matcher; import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; @@ -30,8 +27,8 @@ import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.handler.BridgeHandler; -import org.springframework.integration.message.MessageMatcher; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.predicate.MessagePredicate; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessagingException; @@ -71,25 +68,22 @@ public class BridgeParserTests extends AbstractJUnit4SpringContextTests { private EventDrivenConsumer bridgeWithSendTimeout; - @Factory - public static Matcher> sameExceptImmutableHeaders(Message expected) { - return new MessageMatcher(expected); - } - @Test public void pollableChannel() { - Message message = new GenericMessage("test1"); + Message message = new GenericMessage<>("test1"); this.pollableChannel.send(message); Message reply = this.output1.receive(6000); - assertThat(message, sameExceptImmutableHeaders(reply)); + assertThat(reply).isNotNull(); + assertThat(message).matches(new MessagePredicate(reply)); } @Test public void subscribableChannel() { - Message message = new GenericMessage("test2"); + Message message = new GenericMessage<>("test2"); this.subscribableChannel.send(message); Message reply = this.output2.receive(0); - assertThat(message, sameExceptImmutableHeaders(reply)); + assertThat(reply).isNotNull(); + assertThat(message).matches(new MessagePredicate(reply)); } @Test @@ -98,7 +92,8 @@ public class BridgeParserTests extends AbstractJUnit4SpringContextTests { Message message = MessageBuilder.withPayload("test3").setReplyChannel(replyChannel).build(); this.stopperChannel.send(message); Message reply = replyChannel.receive(0); - assertThat(message, sameExceptImmutableHeaders(reply)); + assertThat(reply).isNotNull(); + assertThat(message).matches(new MessagePredicate(reply)); } @Test(expected = MessagingException.class) @@ -109,9 +104,11 @@ public class BridgeParserTests extends AbstractJUnit4SpringContextTests { @Test public void bridgeWithSendTimeout() { - BridgeHandler handler = (BridgeHandler) new DirectFieldAccessor(bridgeWithSendTimeout).getPropertyValue("handler"); - MessagingTemplate template = (MessagingTemplate) new DirectFieldAccessor(handler).getPropertyValue("messagingTemplate"); - assertEquals(new Long(1234), new DirectFieldAccessor(template).getPropertyValue("sendTimeout")); + BridgeHandler handler = + (BridgeHandler) new DirectFieldAccessor(bridgeWithSendTimeout).getPropertyValue("handler"); + MessagingTemplate template = + (MessagingTemplate) new DirectFieldAccessor(handler).getPropertyValue("messagingTemplate"); + assertThat(new DirectFieldAccessor(template).getPropertyValue("sendTimeout")).isEqualTo(1234L); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ChainElementsFailureTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ChainElementsFailureTests.java index a363447668..f228667bd6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ChainElementsFailureTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ChainElementsFailureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.util.Properties; @@ -51,8 +50,9 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:service-activator'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int:service-activator'."); } } @@ -65,8 +65,9 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:aggregator'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int:aggregator'."); } } @@ -79,8 +80,9 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:chain'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int:chain'."); } } @@ -92,8 +94,9 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:delayer'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int:delayer'."); } } @@ -105,8 +108,9 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:filter'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int:filter'."); } } @@ -118,8 +122,9 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:gateway'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int:gateway'."); } } @@ -131,8 +136,8 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:header-enricher'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + + " allowed to appear in element 'int:header-enricher'."); } } @@ -144,8 +149,8 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:header-filter'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + + " allowed to appear in element 'int:header-filter'."); } } @@ -157,8 +162,9 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:header-value-router'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int:header-value-router'."); } } @@ -170,8 +176,8 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:transformer'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + + " allowed to appear in element 'int:transformer'."); } } @@ -183,8 +189,8 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:router'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + + " allowed to appear in element 'int:router'."); } } @@ -196,8 +202,8 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:splitter'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + + " allowed to appear in element 'int:splitter'."); } } @@ -209,8 +215,8 @@ public class ChainElementsFailureTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int:resequencer'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + + " allowed to appear in element 'int:resequencer'."); } } @@ -226,8 +232,9 @@ public class ChainElementsFailureTests { "'int:resequencer' must not define a 'poller' sub-element " + "when used within a chain."; final String actualMessage = e.getMessage(); - assertTrue("Error message did not start with '" + expectedMessage + - "' but instead returned: '" + actualMessage + "'", actualMessage.startsWith(expectedMessage)); + assertThat(actualMessage.startsWith(expectedMessage)) + .as("Error message did not start with '" + expectedMessage + + "' but instead returned: '" + actualMessage + "'").isTrue(); } } @@ -239,8 +246,8 @@ public class ChainElementsFailureTests { fail("Expected a BeanDefinitionParsingException to be thrown."); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().contains("A bean definition is already registered for " + - "beanName: 'foo$child.bar.handler' within the current .")); + assertThat(e.getMessage().contains("A bean definition is already registered for " + + "beanName: 'foo$child.bar.handler' within the current .")).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ClaimCheckParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ClaimCheckParserTests.java index b0ab5d7fae..762bee4889 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ClaimCheckParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ClaimCheckParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; @@ -80,7 +78,7 @@ public class ClaimCheckParserTests { new DirectFieldAccessor(checkin).getPropertyValue("handler")).getPropertyValue("transformer"); MessageStore messageStore = (MessageStore) new DirectFieldAccessor(transformer).getPropertyValue("messageStore"); - assertEquals(context.getBean("testMessageStore"), messageStore); + assertThat(messageStore).isEqualTo(context.getBean("testMessageStore")); } @Test @@ -89,7 +87,7 @@ public class ClaimCheckParserTests { new DirectFieldAccessor(checkout).getPropertyValue("handler")).getPropertyValue("transformer"); MessageStore messageStore = (MessageStore) new DirectFieldAccessor(transformer).getPropertyValue("messageStore"); - assertEquals(context.getBean("testMessageStore"), messageStore); + assertThat(messageStore).isEqualTo(context.getBean("testMessageStore")); } @Test @@ -98,13 +96,13 @@ public class ClaimCheckParserTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); checkinChannel.send(message); Message wiretapMessage = wiretap.receive(0); - assertNotNull(wiretapMessage); + assertThat(wiretapMessage).isNotNull(); UUID payload = (UUID) wiretapMessage.getPayload(); - assertEquals(message.getHeaders().getId(), payload); + assertThat(payload).isEqualTo(message.getHeaders().getId()); Message resultMessage = replyChannel.receive(0); - assertNotNull(resultMessage); - assertEquals("test", resultMessage.getPayload()); - assertNotNull(this.sampleMessageStore.getMessage(payload)); + assertThat(resultMessage).isNotNull(); + assertThat(resultMessage.getPayload()).isEqualTo("test"); + assertThat(this.sampleMessageStore.getMessage(payload)).isNotNull(); } @Test @@ -113,13 +111,13 @@ public class ClaimCheckParserTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); checkinChannelA.send(message); Message wiretapMessage = wiretap.receive(0); - assertNotNull(wiretapMessage); + assertThat(wiretapMessage).isNotNull(); UUID payload = (UUID) wiretapMessage.getPayload(); - assertEquals(message.getHeaders().getId(), payload); + assertThat(payload).isEqualTo(message.getHeaders().getId()); Message resultMessage = replyChannel.receive(0); - assertNotNull(resultMessage); - assertEquals("test", resultMessage.getPayload()); - assertNull(this.sampleMessageStore.getMessage(payload)); + assertThat(resultMessage).isNotNull(); + assertThat(resultMessage.getPayload()).isEqualTo("test"); + assertThat(this.sampleMessageStore.getMessage(payload)).isNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ContextHierarchyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ContextHierarchyTests.java index 8d664d0bb9..a50beaaecb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ContextHierarchyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ContextHierarchyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; @@ -51,8 +51,8 @@ public class ContextHierarchyTests { Object endpoint = childContext.getBean("chain"); DirectFieldAccessor accessor = new DirectFieldAccessor(endpoint); Object endpointInput = accessor.getPropertyValue("inputChannel"); - assertEquals(parentInput, childInput); - assertEquals(parentInput, endpointInput); + assertThat(childInput).isEqualTo(parentInput); + assertThat(endpointInput).isEqualTo(parentInput); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusChainTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusChainTests.java index cbc651f532..28b1578256 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusChainTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusChainTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; @@ -55,8 +54,8 @@ public class ControlBusChainTests { .setHeader("foo", "bar") .build(); this.input.send(message); - assertEquals("catbar", output.receive(0).getPayload()); - assertNull(output.receive(0)); + assertThat(output.receive(0).getPayload()).isEqualTo("catbar"); + assertThat(output.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusExplicitPollerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusExplicitPollerTests.java index a20ad78a36..b7b9efee99 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusExplicitPollerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusExplicitPollerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -54,8 +53,8 @@ public class ControlBusExplicitPollerTests { .setHeader("foo", "bar") .build(); this.input.send(message); - assertEquals("catbar", output.receive(1000).getPayload()); - assertNull(output.receive(0)); + assertThat(output.receive(1000).getPayload()).isEqualTo("catbar"); + assertThat(output.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusPollerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusPollerTests.java index 45fbcf8c11..23d8cc7bfb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusPollerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusPollerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,8 +52,8 @@ public class ControlBusPollerTests { .setHeader("foo", "bar") .build(); this.input.send(message); - assertEquals("catbar", output.receive(1000).getPayload()); - assertNull(output.receive(0)); + assertThat(output.receive(1000).getPayload()).isEqualTo("catbar"); + assertThat(output.receive(0)).isNull(); } public static class Service { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusRecipientListRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusRecipientListRouterTests.java index 08574fadf4..a30d483e0b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusRecipientListRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusRecipientListRouterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.HashMap; @@ -77,7 +75,7 @@ public class ControlBusRecipientListRouterTests { Message message = new GenericMessage(1); channel.send(message); PollableChannel chanel2 = (PollableChannel) context.getBean("channel2"); - assertTrue(chanel2.receive(0).getPayload().equals(1)); + assertThat(chanel2.receive(0).getPayload().equals(1)).isTrue(); } @Test @@ -89,7 +87,7 @@ public class ControlBusRecipientListRouterTests { Message message = new GenericMessage(1); channel.send(message); PollableChannel chanel3 = (PollableChannel) context.getBean("channel3"); - assertTrue(chanel3.receive(0).getPayload().equals(1)); + assertThat(chanel3.receive(0).getPayload().equals(1)).isTrue(); } @Test @@ -104,8 +102,8 @@ public class ControlBusRecipientListRouterTests { channel.send(message); PollableChannel chanel1 = (PollableChannel) context.getBean("channel1"); PollableChannel chanel4 = (PollableChannel) context.getBean("channel4"); - assertTrue(chanel1.receive(0).getPayload().equals(1)); - assertNull(chanel4.receive(0)); + assertThat(chanel1.receive(0).getPayload().equals(1)).isTrue(); + assertThat(chanel4.receive(0)).isNull(); } @Test @@ -120,8 +118,8 @@ public class ControlBusRecipientListRouterTests { channel.send(message); PollableChannel chanel1 = (PollableChannel) context.getBean("channel1"); PollableChannel chanel5 = (PollableChannel) context.getBean("channel5"); - assertTrue(chanel1.receive(0).getPayload().equals(1)); - assertNull(chanel5.receive(0)); + assertThat(chanel1.receive(0).getPayload().equals(1)).isTrue(); + assertThat(chanel5.receive(0)).isNull(); } @Test @@ -134,7 +132,7 @@ public class ControlBusRecipientListRouterTests { PollableChannel channel1 = (PollableChannel) context.getBean("channel1"); Message result = this.output.receive(0); Collection mappings = (Collection) result.getPayload(); - assertEquals(channel1, mappings.iterator().next().getChannel()); + assertThat(mappings.iterator().next().getChannel()).isEqualTo(channel1); } @Test @@ -149,7 +147,7 @@ public class ControlBusRecipientListRouterTests { message = new GenericMessage(1); channel.send(message); PollableChannel chanel6 = (PollableChannel) context.getBean("channel6"); - assertTrue(chanel6.receive(0).getPayload().equals(1)); + assertThat(chanel6.receive(0).getPayload().equals(1)).isTrue(); } @Test @@ -161,6 +159,6 @@ public class ControlBusRecipientListRouterTests { Message message = new GenericMessage(1); channel.send(message); PollableChannel chanel7 = (PollableChannel) context.getBean("channel7"); - assertTrue(chanel7.receive(0).getPayload().equals(1)); + assertThat(chanel7.receive(0).getPayload().equals(1)).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusTests.java index 1e5db69abd..19e9eeaad1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ControlBusTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; import java.util.Map; @@ -76,15 +73,15 @@ public class ControlBusTests { public void testDefaultEvaluationContext() { Message message = MessageBuilder.withPayload("@service.convert('aardvark')+headers.foo").setHeader("foo", "bar").build(); this.input.send(message); - assertEquals("catbar", output.receive(0).getPayload()); - assertNull(output.receive(0)); + assertThat(output.receive(0).getPayload()).isEqualTo("catbar"); + assertThat(output.receive(0)).isNull(); } @Test public void testvoidOperation() throws Exception { Message message = MessageBuilder.withPayload("@service.voidOp('foo')").build(); this.input.send(message); - assertTrue(this.service.latch.await(10, TimeUnit.SECONDS)); + assertThat(this.service.latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test @@ -93,10 +90,10 @@ public class ControlBusTests { "ControlBusLifecycleTests-context.xml", this.getClass()); MessageChannel inputChannel = context.getBean("inputChannel", MessageChannel.class); PollableChannel outputChannel = context.getBean("outputChannel", PollableChannel.class); - assertNull(outputChannel.receive(10)); + assertThat(outputChannel.receive(10)).isNull(); Message message = MessageBuilder.withPayload("@adapter.start()").build(); inputChannel.send(message); - assertNotNull(outputChannel.receive(1000)); + assertThat(outputChannel.receive(1000)).isNotNull(); context.close(); } @@ -105,16 +102,16 @@ public class ControlBusTests { MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.convertAndSend(input, "@integrationHeaderChannelRegistry.size()"); Message result = this.output.receive(0); - assertNotNull(result); + assertThat(result).isNotNull(); // No channels in the registry - assertEquals(0, result.getPayload()); + assertThat(result.getPayload()).isEqualTo(0); this.registry.channelToChannelName(new DirectChannel()); // Sleep a bit to be sure that we aren't reaped by registry TTL as 60000 Thread.sleep(10); messagingTemplate.convertAndSend(input, "@integrationHeaderChannelRegistry.size()"); result = this.output.receive(0); - assertNotNull(result); - assertEquals(1, result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(1); // Some DirectFieldAccessor magic to modify 'expireAt' to the past to avoid timing issues on high-loaded build Object messageChannelWrapper = TestUtils.getPropertyValue(this.registry, "channels", Map.class).values().iterator().next(); @@ -123,8 +120,8 @@ public class ControlBusTests { messagingTemplate.convertAndSend(input, "@integrationHeaderChannelRegistry.runReaper()"); messagingTemplate.convertAndSend(input, "@integrationHeaderChannelRegistry.size()"); result = this.output.receive(0); - assertNotNull(result); - assertEquals(0, result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(0); } @Test @@ -133,18 +130,18 @@ public class ControlBusTests { messagingTemplate.setReceiveTimeout(1000); messagingTemplate.convertAndSend(input, "@'router.handler'.getChannelMappings()"); Message result = this.output.receive(0); - assertNotNull(result); + assertThat(result).isNotNull(); Map mappings = (Map) result.getPayload(); - assertEquals("bar", mappings.get("foo")); - assertEquals("qux", mappings.get("baz")); + assertThat(mappings.get("foo")).isEqualTo("bar"); + assertThat(mappings.get("baz")).isEqualTo("qux"); messagingTemplate.convertAndSend(input, "@'router.handler'.replaceChannelMappings('foo=qux \n baz=bar')"); messagingTemplate.convertAndSend(input, "@'router.handler'.getChannelMappings()"); result = this.output.receive(0); - assertNotNull(result); + assertThat(result).isNotNull(); mappings = (Map) result.getPayload(); - assertEquals("bar", mappings.get("baz")); - assertEquals("qux", mappings.get("foo")); + assertThat(mappings.get("baz")).isEqualTo("bar"); + assertThat(mappings.get("foo")).isEqualTo("qux"); } public static class Service { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserTests.java index 5a46fa9b51..34d3ba2029 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -74,10 +73,10 @@ public class ConverterParserTests { .setReplyChannel(replyChannel).build(); this.serviceActivatorChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean2.class, result.getPayload().getClass()); - assertEquals("SERVICE-TEST", ((TestBean2) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean2.class); + assertThat(((TestBean2) result.getPayload()).text).isEqualTo("SERVICE-TEST"); } @Test @@ -87,10 +86,10 @@ public class ConverterParserTests { .setReplyChannel(replyChannel).build(); this.serviceActivatorChannel3.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean3.class, result.getPayload().getClass()); - assertEquals("SERVICE-TEST", ((TestBean3) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean3.class); + assertThat(((TestBean3) result.getPayload()).text).isEqualTo("SERVICE-TEST"); } @Test @@ -100,10 +99,10 @@ public class ConverterParserTests { .setReplyChannel(replyChannel).build(); this.transformerChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean2.class, result.getPayload().getClass()); - assertEquals("TRANSFORMER-TEST", ((TestBean2) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean2.class); + assertThat(((TestBean2) result.getPayload()).text).isEqualTo("TRANSFORMER-TEST"); } @Test @@ -113,10 +112,10 @@ public class ConverterParserTests { .setReplyChannel(replyChannel).build(); this.splitterChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean2.class, result.getPayload().getClass()); - assertEquals("SPLITTER-TEST", ((TestBean2) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean2.class); + assertThat(((TestBean2) result.getPayload()).text).isEqualTo("SPLITTER-TEST"); } @Test @@ -126,10 +125,10 @@ public class ConverterParserTests { .setReplyChannel(replyChannel).build(); this.filterChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean1.class, result.getPayload().getClass()); - assertEquals("filter-test", ((TestBean1) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean1.class); + assertThat(((TestBean1) result.getPayload()).text).isEqualTo("filter-test"); } @Test @@ -137,10 +136,10 @@ public class ConverterParserTests { Message message = MessageBuilder.withPayload(new TestBean1("router-test")).build(); this.routerChannel.send(message); Message result = this.routerTargetChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean1.class, result.getPayload().getClass()); - assertEquals("router-test", ((TestBean1) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean1.class); + assertThat(((TestBean1) result.getPayload()).text).isEqualTo("router-test"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java index fbe6b41606..ff69aeafd0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -52,10 +52,10 @@ public class ConverterParserWithExistingConversionServiceTests { @Test public void testConversionServiceAvailability() { - assertTrue(applicationContext.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME) - .equals(conversionService)); - assertTrue(conversionService.canConvert(TestBean1.class, TestBean2.class)); - assertTrue(conversionService.canConvert(TestBean1.class, TestBean3.class)); + assertThat(applicationContext.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME) + .equals(conversionService)).isTrue(); + assertThat(conversionService.canConvert(TestBean1.class, TestBean2.class)).isTrue(); + assertThat(conversionService.canConvert(TestBean1.class, TestBean3.class)).isTrue(); } @Test public void testParentConversionServiceAvailability() { @@ -73,11 +73,11 @@ public class ConverterParserWithExistingConversionServiceTests { GenericConversionService conversionServiceChild = childContext.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, GenericConversionService.class); - assertTrue(conversionServiceParent == conversionServiceChild); // validating that they are pointing to the same object + assertThat(conversionServiceParent == conversionServiceChild).isTrue(); // validating that they are pointing to the same object conversionServiceChild.addConverter(new TestConverter()); conversionServiceChild.addConverter(new TestConverter3()); - assertTrue(conversionServiceChild.canConvert(TestBean1.class, TestBean2.class)); - assertTrue(conversionServiceChild.canConvert(TestBean1.class, TestBean3.class)); + assertThat(conversionServiceChild.canConvert(TestBean1.class, TestBean2.class)).isTrue(); + assertThat(conversionServiceChild.canConvert(TestBean1.class, TestBean3.class)).isTrue(); childContext.close(); parentContext.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java index 73bde8cfab..3c147ffddc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -43,15 +43,15 @@ public class CronTriggerParserTests { @Test public void checkConfigWithAttribute() { Object poller = context.getBean("pollerWithAttribute"); - assertEquals(PollerMetadata.class, poller.getClass()); + assertThat(poller.getClass()).isEqualTo(PollerMetadata.class); PollerMetadata metadata = (PollerMetadata) poller; Trigger trigger = metadata.getTrigger(); - assertEquals(CronTrigger.class, trigger.getClass()); + assertThat(trigger.getClass()).isEqualTo(CronTrigger.class); DirectFieldAccessor accessor = new DirectFieldAccessor(trigger); String expression = (String) new DirectFieldAccessor( accessor.getPropertyValue("sequenceGenerator")) .getPropertyValue("expression"); - assertEquals("*/10 * 9-17 * * MON-FRI", expression); + assertThat(expression).isEqualTo("*/10 * 9-17 * * MON-FRI"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorHierarchyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorHierarchyTests.java index 05ae2cd074..bddf2a7fc8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorHierarchyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorHierarchyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -41,12 +41,12 @@ public class DefaultConfiguringBeanFactoryPostProcessorHierarchyTests { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(child); reader.loadBeanDefinitions(new ClassPathResource("hierarchyTests-child.xml", this.getClass())); child.refresh(); - assertSame(parent.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME), - child.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)); - assertSame(parent.getBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME), - child.getBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)); - assertSame(parent.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME), - child.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)); + assertThat(child.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)) + .isSameAs(parent.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)); + assertThat(child.getBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)) + .isSameAs(parent.getBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)); + assertThat(child.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)) + .isSameAs(parent.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorTests.java index baaae6e915..5022f89e89 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultConfiguringBeanFactoryPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -54,31 +52,31 @@ public class DefaultConfiguringBeanFactoryPostProcessorTests { @Test public void errorChannelRegistered() { Object errorChannel = context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME); - assertNotNull(errorChannel); - assertEquals(PublishSubscribeChannel.class, errorChannel.getClass()); + assertThat(errorChannel).isNotNull(); + assertThat(errorChannel.getClass()).isEqualTo(PublishSubscribeChannel.class); } @Test public void nullChannelRegistered() { Object nullChannel = context.getBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME); - assertNotNull(nullChannel); - assertEquals(NullChannel.class, nullChannel.getClass()); + assertThat(nullChannel).isNotNull(); + assertThat(nullChannel.getClass()).isEqualTo(NullChannel.class); } @Test public void taskSchedulerRegistered() { Object taskScheduler = context.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME); - assertEquals(ThreadPoolTaskScheduler.class, taskScheduler.getClass()); + assertThat(taskScheduler.getClass()).isEqualTo(ThreadPoolTaskScheduler.class); ErrorHandler errorHandler = TestUtils.getPropertyValue(taskScheduler, "errorHandler", ErrorHandler.class); - assertEquals(MessagePublishingErrorHandler.class, errorHandler.getClass()); + assertThat(errorHandler.getClass()).isEqualTo(MessagePublishingErrorHandler.class); MessageChannel defaultErrorChannel = TestUtils.getPropertyValue(errorHandler, "messagingTemplate.defaultDestination", MessageChannel.class); - assertNull(defaultErrorChannel); + assertThat(defaultErrorChannel).isNull(); errorHandler.handleError(new Throwable()); defaultErrorChannel = TestUtils.getPropertyValue(errorHandler, "messagingTemplate.defaultDestination", MessageChannel.class); - assertNotNull(defaultErrorChannel); - assertEquals(context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME), defaultErrorChannel); + assertThat(defaultErrorChannel).isNotNull(); + assertThat(defaultErrorChannel).isEqualTo(context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)); } @Test @@ -95,9 +93,9 @@ public class DefaultConfiguringBeanFactoryPostProcessorTests { TaskScheduler.class); TaskScheduler childScheduler = childApplicationContext.getBean("taskScheduler", TaskScheduler.class); - assertNotNull("Child task scheduler was null", childScheduler); - assertNotNull("Parent task scheduler was null", parentScheduler); - assertEquals("Different schedulers in parent and child", parentScheduler, childScheduler); + assertThat(childScheduler).as("Child task scheduler was null").isNotNull(); + assertThat(parentScheduler).as("Parent task scheduler was null").isNotNull(); + assertThat(childScheduler).as("Different schedulers in parent and child").isEqualTo(parentScheduler); childApplicationContext.close(); parentApplicationContext.close(); superParentApplicationContext.close(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultOutboundChannelAdapterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultOutboundChannelAdapterParserTests.java index 592500bee5..aa9c3d89aa 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultOutboundChannelAdapterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DefaultOutboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -70,38 +65,38 @@ public class DefaultOutboundChannelAdapterParserTests { @Test public void checkConfig() { Object adapter = context.getBean("adapter"); - assertEquals(Boolean.FALSE, TestUtils.getPropertyValue(adapter, "autoStartup")); + assertThat(TestUtils.getPropertyValue(adapter, "autoStartup")).isEqualTo(Boolean.FALSE); Object handler = TestUtils.getPropertyValue(adapter, "handler"); - assertEquals(MethodInvokingMessageHandler.class, handler.getClass()); - assertEquals(99, TestUtils.getPropertyValue(handler, "order")); + assertThat(handler.getClass()).isEqualTo(MethodInvokingMessageHandler.class); + assertThat(TestUtils.getPropertyValue(handler, "order")).isEqualTo(99); } @Test public void checkConfigWithInnerBeanAndPoller() { Object adapter = context.getBean("adapterB"); - assertEquals(Boolean.FALSE, TestUtils.getPropertyValue(adapter, "autoStartup")); + assertThat(TestUtils.getPropertyValue(adapter, "autoStartup")).isEqualTo(Boolean.FALSE); MessageHandler handler = TestUtils.getPropertyValue(adapter, "handler", MessageHandler.class); - assertTrue(AopUtils.isAopProxy(handler)); - assertThat(TestUtils.getPropertyValue(handler, "h.advised.advisors[0].advice"), - Matchers.instanceOf(RequestHandlerRetryAdvice.class)); + assertThat(AopUtils.isAopProxy(handler)).isTrue(); + assertThat(TestUtils.getPropertyValue(handler, "h.advised.advisors[0].advice")) + .isInstanceOf(RequestHandlerRetryAdvice.class); handler.handleMessage(new GenericMessage<>("foo")); QueueChannel recovery = context.getBean("recovery", QueueChannel.class); Message received = recovery.receive(10000); - assertNotNull(received); - assertThat(received, instanceOf(ErrorMessage.class)); - assertThat(received.getPayload(), instanceOf(MessagingException.class)); - assertEquals("foo", ((MessagingException) received.getPayload()).getFailedMessage().getPayload()); + assertThat(received).isNotNull(); + assertThat(received).isInstanceOf(ErrorMessage.class); + assertThat(received.getPayload()).isInstanceOf(MessagingException.class); + assertThat(((MessagingException) received.getPayload()).getFailedMessage().getPayload()).isEqualTo("foo"); } @Test public void checkConfigWithInnerMessageHandler() { Object adapter = context.getBean("adapterC"); Object handler = TestUtils.getPropertyValue(adapter, "handler"); - assertEquals(MethodInvokingMessageHandler.class, handler.getClass()); - assertEquals(99, TestUtils.getPropertyValue(handler, "order")); + assertThat(handler.getClass()).isEqualTo(MethodInvokingMessageHandler.class); + assertThat(TestUtils.getPropertyValue(handler, "order")).isEqualTo(99); Object targetObject = TestUtils.getPropertyValue(handler, "processor.delegate.targetObject"); - assertEquals(TestConsumer.class, targetObject.getClass()); + assertThat(targetObject.getClass()).isEqualTo(TestConsumer.class); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java index 1f45aa680a..1f450eee42 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -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.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.HashMap; @@ -65,42 +60,45 @@ public class DelayerParserTests { @Test public void defaultScheduler() { DelayHandler delayHandler = context.getBean("delayerWithDefaultScheduler.handler", DelayHandler.class); - assertEquals(99, delayHandler.getOrder()); - assertEquals(context.getBean("output"), TestUtils.getPropertyValue(delayHandler, "outputChannel")); - assertEquals(new Long(1234), TestUtils.getPropertyValue(delayHandler, "defaultDelay", Long.class)); + assertThat(delayHandler.getOrder()).isEqualTo(99); + assertThat(TestUtils.getPropertyValue(delayHandler, "outputChannel")).isEqualTo(context.getBean("output")); + assertThat(TestUtils.getPropertyValue(delayHandler, "defaultDelay", Long.class)).isEqualTo(new Long(1234)); //INT-2243 - assertNotNull(TestUtils.getPropertyValue(delayHandler, "delayExpression")); - assertEquals("headers.foo", TestUtils.getPropertyValue(delayHandler, "delayExpression", Expression.class).getExpressionString()); - assertEquals(new Long(987), TestUtils.getPropertyValue(delayHandler, "messagingTemplate.sendTimeout", Long.class)); - assertNull(TestUtils.getPropertyValue(delayHandler, "taskScheduler")); + assertThat(TestUtils.getPropertyValue(delayHandler, "delayExpression")).isNotNull(); + assertThat(TestUtils.getPropertyValue(delayHandler, "delayExpression", Expression.class).getExpressionString()) + .isEqualTo("headers.foo"); + assertThat(TestUtils.getPropertyValue(delayHandler, "messagingTemplate.sendTimeout", Long.class)) + .isEqualTo(new Long(987)); + assertThat(TestUtils.getPropertyValue(delayHandler, "taskScheduler")).isNull(); } @Test public void customScheduler() { Object endpoint = context.getBean("delayerWithCustomScheduler"); - assertEquals(EventDrivenConsumer.class, endpoint.getClass()); + assertThat(endpoint.getClass()).isEqualTo(EventDrivenConsumer.class); Object handler = TestUtils.getPropertyValue(endpoint, "handler"); - assertEquals(DelayHandler.class, handler.getClass()); + assertThat(handler.getClass()).isEqualTo(DelayHandler.class); DelayHandler delayHandler = (DelayHandler) handler; - assertEquals(Ordered.LOWEST_PRECEDENCE, delayHandler.getOrder()); + assertThat(delayHandler.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE); DirectFieldAccessor accessor = new DirectFieldAccessor(delayHandler); - assertEquals(context.getBean("output"), accessor.getPropertyValue("outputChannel")); - assertEquals(new Long(0), accessor.getPropertyValue("defaultDelay")); - assertEquals(context.getBean("testScheduler"), accessor.getPropertyValue("taskScheduler")); - assertNotNull(accessor.getPropertyValue("taskScheduler")); - assertEquals(Boolean.TRUE, new DirectFieldAccessor( - accessor.getPropertyValue("taskScheduler")).getPropertyValue("waitForTasksToCompleteOnShutdown")); + assertThat(accessor.getPropertyValue("outputChannel")).isEqualTo(context.getBean("output")); + assertThat(accessor.getPropertyValue("defaultDelay")).isEqualTo(new Long(0)); + assertThat(accessor.getPropertyValue("taskScheduler")).isEqualTo(context.getBean("testScheduler")); + assertThat(accessor.getPropertyValue("taskScheduler")).isNotNull(); + assertThat(new DirectFieldAccessor( + accessor.getPropertyValue("taskScheduler")).getPropertyValue("waitForTasksToCompleteOnShutdown")) + .isEqualTo(Boolean.TRUE); } @Test public void customMessageStore() { Object endpoint = context.getBean("delayerWithCustomMessageStore"); - assertEquals(EventDrivenConsumer.class, endpoint.getClass()); + assertThat(endpoint.getClass()).isEqualTo(EventDrivenConsumer.class); Object handler = TestUtils.getPropertyValue(endpoint, "handler"); - assertEquals(DelayHandler.class, handler.getClass()); + assertThat(handler.getClass()).isEqualTo(DelayHandler.class); DelayHandler delayHandler = (DelayHandler) handler; DirectFieldAccessor accessor = new DirectFieldAccessor(delayHandler); - assertEquals(context.getBean("testMessageStore"), accessor.getPropertyValue("messageStore")); + assertThat(accessor.getPropertyValue("messageStore")).isEqualTo(context.getBean("testMessageStore")); } @Test //INT-2649 @@ -108,17 +106,17 @@ public class DelayerParserTests { Object endpoint = context.getBean("delayerWithTransactional"); DelayHandler delayHandler = TestUtils.getPropertyValue(endpoint, "handler", DelayHandler.class); List adviceChain = TestUtils.getPropertyValue(delayHandler, "delayedAdviceChain", List.class); - assertEquals(1, adviceChain.size()); + assertThat(adviceChain.size()).isEqualTo(1); Object advice = adviceChain.get(0); - assertTrue(advice instanceof TransactionInterceptor); + assertThat(advice instanceof TransactionInterceptor).isTrue(); TransactionAttributeSource transactionAttributeSource = ((TransactionInterceptor) advice).getTransactionAttributeSource(); - assertTrue(transactionAttributeSource instanceof MatchAlwaysTransactionAttributeSource); + assertThat(transactionAttributeSource instanceof MatchAlwaysTransactionAttributeSource).isTrue(); Method method = MessageHandler.class.getMethod("handleMessage", Message.class); TransactionDefinition definition = transactionAttributeSource.getTransactionAttribute(method, null); - assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, definition.getPropagationBehavior()); - assertEquals(TransactionDefinition.ISOLATION_DEFAULT, definition.getIsolationLevel()); - assertEquals(TransactionDefinition.TIMEOUT_DEFAULT, definition.getTimeout()); - assertFalse(definition.isReadOnly()); + assertThat(definition.getPropagationBehavior()).isEqualTo(TransactionDefinition.PROPAGATION_REQUIRED); + assertThat(definition.getIsolationLevel()).isEqualTo(TransactionDefinition.ISOLATION_DEFAULT); + assertThat(definition.getTimeout()).isEqualTo(TransactionDefinition.TIMEOUT_DEFAULT); + assertThat(definition.isReadOnly()).isFalse(); } @Test //INT-2649 @@ -126,28 +124,30 @@ public class DelayerParserTests { Object endpoint = context.getBean("delayerWithAdviceChain"); DelayHandler delayHandler = TestUtils.getPropertyValue(endpoint, "handler", DelayHandler.class); List adviceChain = TestUtils.getPropertyValue(delayHandler, "delayedAdviceChain", List.class); - assertEquals(2, adviceChain.size()); - assertSame(context.getBean("testAdviceBean"), adviceChain.get(0)); + assertThat(adviceChain.size()).isEqualTo(2); + assertThat(adviceChain.get(0)).isSameAs(context.getBean("testAdviceBean")); Object txAdvice = adviceChain.get(1); - assertEquals(TransactionInterceptor.class, txAdvice.getClass()); + assertThat(txAdvice.getClass()).isEqualTo(TransactionInterceptor.class); TransactionAttributeSource transactionAttributeSource = ((TransactionInterceptor) txAdvice).getTransactionAttributeSource(); - assertEquals(NameMatchTransactionAttributeSource.class, transactionAttributeSource.getClass()); + assertThat(transactionAttributeSource.getClass()).isEqualTo(NameMatchTransactionAttributeSource.class); HashMap nameMap = TestUtils.getPropertyValue(transactionAttributeSource, "nameMap", HashMap.class); - assertEquals("{*=PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT,readOnly}", nameMap.toString()); + assertThat(nameMap.toString()).isEqualTo("{*=PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT,readOnly}"); } @Test public void testInt2243Expression() { DelayHandler delayHandler = context.getBean("delayerWithExpression.handler", DelayHandler.class); - assertEquals("100", TestUtils.getPropertyValue(delayHandler, "delayExpression", Expression.class).getExpressionString()); - assertFalse(TestUtils.getPropertyValue(delayHandler, "ignoreExpressionFailures", Boolean.class)); + assertThat(TestUtils.getPropertyValue(delayHandler, "delayExpression", Expression.class).getExpressionString()) + .isEqualTo("100"); + assertThat(TestUtils.getPropertyValue(delayHandler, "ignoreExpressionFailures", Boolean.class)).isFalse(); } @Test public void testInt2243ExpressionSubElement() { DelayHandler delayHandler = context.getBean("delayerWithExpressionSubElement.handler", DelayHandler.class); - assertEquals("headers.timestamp + 1000", TestUtils.getPropertyValue(delayHandler, "delayExpression", Expression.class).getExpressionString()); + assertThat(TestUtils.getPropertyValue(delayHandler, "delayExpression", Expression.class).getExpressionString()) + .isEqualTo("headers.timestamp + 1000"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerUsageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerUsageTests.java index bf97bb62d2..7e1750d4b8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerUsageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerUsageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Ignore; import org.junit.Test; @@ -73,8 +71,8 @@ public class DelayerUsageTests { public void testDelayWithDefaultScheduler() { long start = System.currentTimeMillis(); inputA.send(new GenericMessage("Hello")); - assertNotNull(outputA.receive(10000)); - assertTrue((System.currentTimeMillis() - start) >= 1000); + assertThat(outputA.receive(10000)).isNotNull(); + assertThat((System.currentTimeMillis() - start) >= 1000).isTrue(); } @Test @@ -84,8 +82,8 @@ public class DelayerUsageTests { builder.setHeader("foo", 2000); long start = System.currentTimeMillis(); inputA.send(builder.build()); - assertNotNull(outputA.receive(10000)); - assertTrue((System.currentTimeMillis() - start) >= 2000); + assertThat(outputA.receive(10000)).isNotNull(); + assertThat((System.currentTimeMillis() - start) >= 2000).isTrue(); } @Test @@ -99,18 +97,19 @@ public class DelayerUsageTests { inputB.send(new GenericMessage("5")); inputB.send(new GenericMessage("6")); inputB.send(new GenericMessage("7")); - assertNotNull(outputB1.receive(10000)); - assertNotNull(outputB1.receive(10000)); - assertNotNull(outputB1.receive(10000)); - assertNotNull(outputB1.receive(10000)); - assertNotNull(outputB1.receive(10000)); - assertNotNull(outputB1.receive(10000)); - assertNotNull(outputB1.receive(10000)); + assertThat(outputB1.receive(10000)).isNotNull(); + assertThat(outputB1.receive(10000)).isNotNull(); + assertThat(outputB1.receive(10000)).isNotNull(); + assertThat(outputB1.receive(10000)).isNotNull(); + assertThat(outputB1.receive(10000)).isNotNull(); + assertThat(outputB1.receive(10000)).isNotNull(); + assertThat(outputB1.receive(10000)).isNotNull(); // must execute under 3 seconds, since threadPool is set too 5. // first batch is 5 concurrent invocations on SA, then 2 more // elapsed time for the whole execution should be a bit over 2 seconds depending on the hardware - assertTrue(((System.currentTimeMillis() - start) >= 1000) && ((System.currentTimeMillis() - start) < 3000)); + assertThat(((System.currentTimeMillis() - start) >= 1000) && ((System.currentTimeMillis() - start) < 3000)) + .isTrue(); } @Test //INT-1132 @@ -118,9 +117,9 @@ public class DelayerUsageTests { long start = System.currentTimeMillis(); delayerInsideChain.send(new GenericMessage("Hello")); Message message = outputA.receive(10000); - assertNotNull(message); - assertTrue((System.currentTimeMillis() - start) >= 1000); - assertEquals("hello", message.getPayload()); + assertThat(message).isNotNull(); + assertThat((System.currentTimeMillis() - start) >= 1000).isTrue(); + assertThat(message.getPayload()).isEqualTo("hello"); } @Test @@ -128,9 +127,9 @@ public class DelayerUsageTests { long start = System.currentTimeMillis(); this.inputC.send(new GenericMessage("test")); Message message = this.outputC.receive(10000); - assertNotNull(message); - assertTrue((System.currentTimeMillis() - start) >= 1000); - assertEquals("test", message.getPayload()); + assertThat(message).isNotNull(); + assertThat((System.currentTimeMillis() - start) >= 1000).isTrue(); + assertThat(message.getPayload()).isEqualTo("test"); } public static class SampleService { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java index 066ff0f98d..9e464dcd49 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 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,11 +16,8 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -143,52 +140,52 @@ public class DelegatingConsumerParserTests { @Test public void testDelegates() { - assertTrue(directFilter instanceof MyFilter); + assertThat(directFilter instanceof MyFilter).isTrue(); testHandler(directFilter); - assertTrue(refFilter instanceof MyFilter); + assertThat(refFilter instanceof MyFilter).isTrue(); testHandler(refFilter); // MessageSelector (wrapped in MessageFilter) wins here - assertTrue(filterWithMessageSelectorThatsAlsoAnARPMH instanceof MessageFilter); + assertThat(filterWithMessageSelectorThatsAlsoAnARPMH instanceof MessageFilter).isTrue(); testHandler(filterWithMessageSelectorThatsAlsoAnARPMH); - assertTrue(directRouter instanceof MyRouter); + assertThat(directRouter instanceof MyRouter).isTrue(); testHandler(directRouter); - assertTrue(refRouter instanceof MyRouter); + assertThat(refRouter instanceof MyRouter).isTrue(); testHandler(refRouter); - assertTrue(directRouterMH instanceof MyRouterMH); + assertThat(directRouterMH instanceof MyRouterMH).isTrue(); testHandler(directRouterMH); - assertTrue(refRouterMH instanceof MyRouterMH); + assertThat(refRouterMH instanceof MyRouterMH).isTrue(); testHandler(refRouterMH); - assertTrue(directRouterARPMH instanceof MyRouterARPMH); + assertThat(directRouterARPMH instanceof MyRouterARPMH).isTrue(); testHandler(directRouterARPMH); - assertTrue(refRouterARPMH instanceof MyRouterARPMH); + assertThat(refRouterARPMH instanceof MyRouterARPMH).isTrue(); testHandler(refRouterARPMH); - assertTrue(directServiceARPMH instanceof MyServiceARPMH); + assertThat(directServiceARPMH instanceof MyServiceARPMH).isTrue(); testHandler(directServiceARPMH); - assertTrue(refServiceARPMH instanceof MyServiceARPMH); + assertThat(refServiceARPMH instanceof MyServiceARPMH).isTrue(); testHandler(refServiceARPMH); - assertTrue(directSplitter instanceof MySplitter); + assertThat(directSplitter instanceof MySplitter).isTrue(); testHandler(directSplitter); - assertTrue(refSplitter instanceof MySplitter); + assertThat(refSplitter instanceof MySplitter).isTrue(); testHandler(refSplitter); - assertTrue(splitterWithARPMH instanceof MySplitterThatsAnARPMH); + assertThat(splitterWithARPMH instanceof MySplitterThatsAnARPMH).isTrue(); testHandler(splitterWithARPMH); - assertTrue(splitterWithARPMHWithAtts instanceof MySplitterThatsAnARPMH); - assertEquals(Long.valueOf(123), - TestUtils.getPropertyValue(splitterWithARPMHWithAtts, "messagingTemplate.sendTimeout", Long.class)); + assertThat(splitterWithARPMHWithAtts instanceof MySplitterThatsAnARPMH).isTrue(); + assertThat(TestUtils.getPropertyValue(splitterWithARPMHWithAtts, "messagingTemplate.sendTimeout", Long.class)) + .isEqualTo(Long.valueOf(123)); testHandler(splitterWithARPMHWithAtts); - assertTrue(directTransformer instanceof MessageTransformingHandler); - assertTrue(TestUtils.getPropertyValue(directTransformer, "transformer") instanceof MyTransformer); + assertThat(directTransformer instanceof MessageTransformingHandler).isTrue(); + assertThat(TestUtils.getPropertyValue(directTransformer, "transformer") instanceof MyTransformer).isTrue(); testHandler(directTransformer); - assertTrue(refTransformer instanceof MessageTransformingHandler); - assertTrue(TestUtils.getPropertyValue(refTransformer, "transformer") instanceof MyTransformer); + assertThat(refTransformer instanceof MessageTransformingHandler).isTrue(); + assertThat(TestUtils.getPropertyValue(refTransformer, "transformer") instanceof MyTransformer).isTrue(); testHandler(refTransformer); - assertTrue(directTransformerARPMH instanceof MyTransformerARPMH); + assertThat(directTransformerARPMH instanceof MyTransformerARPMH).isTrue(); testHandler(directTransformerARPMH); - assertTrue(refTransformerARPMH instanceof MyTransformerARPMH); + assertThat(refTransformerARPMH instanceof MyTransformerARPMH).isTrue(); testHandler(refTransformerARPMH); } @@ -203,7 +200,7 @@ public class DelegatingConsumerParserTests { fb.setTargetObject(service); fb.getObject(); - assertTrue(TestUtils.getPropertyValue(fb, "referencedReplyProducers", Set.class).contains(service)); + assertThat(TestUtils.getPropertyValue(fb, "referencedReplyProducers", Set.class).contains(service)).isTrue(); ServiceActivatorFactoryBean fb2 = new ServiceActivatorFactoryBean(); fb2.setBeanFactory(mock(BeanFactory.class)); @@ -213,13 +210,14 @@ public class DelegatingConsumerParserTests { fail("expected exception"); } catch (Exception e) { - assertEquals("An AbstractMessageProducingMessageHandler may only be referenced once (foo) - " - + "use scope=\"prototype\"", e.getMessage()); + assertThat(e.getMessage()) + .isEqualTo("An AbstractMessageProducingMessageHandler may only be referenced once (foo) - " + + "use scope=\"prototype\""); } fb.destroy(); - assertFalse(TestUtils.getPropertyValue(fb, "referencedReplyProducers", Set.class).contains(service)); + assertThat(TestUtils.getPropertyValue(fb, "referencedReplyProducers", Set.class).contains(service)).isFalse(); } private void testHandler(MessageHandler handler) { @@ -227,7 +225,7 @@ public class DelegatingConsumerParserTests { .setReplyChannel(replyChannel) .build(); handler.handleMessage(message); - assertNotNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNotNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersDontOverrideDefaultTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersDontOverrideDefaultTests.java index d766f9fc60..cd1e56a3e5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersDontOverrideDefaultTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersDontOverrideDefaultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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. diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java index 3bd6d4c622..0ff34f9c33 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,7 +53,7 @@ public class DispatcherMaxSubscribersOverrideDefaultTests extends DispatcherMaxS fail("Expected Exception"); } catch (IllegalArgumentException e) { - assertEquals("Maximum subscribers exceeded", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Maximum subscribers exceeded"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersTests.java index a8442da2ce..8877dd6820 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.test.util.TestUtils; @@ -62,30 +62,30 @@ public abstract class DispatcherMaxSubscribersTests { protected void doTestUnicast(int val1, int val2, int val3, int val4, int val5) { Integer autoCreateMax = TestUtils.getPropertyValue(autoCreateChannel, "dispatcher.maxSubscribers", Integer.class); - assertEquals(val1, autoCreateMax.intValue()); + assertThat(autoCreateMax).isEqualTo(val1); Integer defaultMax = TestUtils.getPropertyValue(defaultChannel, "dispatcher.maxSubscribers", Integer.class); - assertEquals(val1, defaultMax.intValue()); + assertThat(defaultMax.intValue()).isEqualTo(val1); Integer defaultMax2 = TestUtils.getPropertyValue(defaultChannel2, "dispatcher.maxSubscribers", Integer.class); - assertEquals(val2, defaultMax2.intValue()); + assertThat(defaultMax2.intValue()).isEqualTo(val2); Integer explicitMax = TestUtils.getPropertyValue(explicitChannel, "dispatcher.maxSubscribers", Integer.class); - assertEquals(val3, explicitMax.intValue()); + assertThat(explicitMax.intValue()).isEqualTo(val3); Integer execMax = TestUtils.getPropertyValue(executorChannel, "dispatcher.maxSubscribers", Integer.class); - assertEquals(val4, execMax.intValue()); + assertThat(execMax.intValue()).isEqualTo(val4); Integer explicitExecMax = TestUtils.getPropertyValue(explicitExecutorChannel, "dispatcher.maxSubscribers", Integer.class); - assertEquals(val5, explicitExecMax.intValue()); + assertThat(explicitExecMax.intValue()).isEqualTo(val5); } protected void doTestMulticast(int val1, int val2) { Integer defaultMax = TestUtils.getPropertyValue( TestUtils.getPropertyValue(pubSubDefaultChannel, "dispatcher"), "maxSubscribers", Integer.class); - assertEquals(val1, defaultMax.intValue()); + assertThat(defaultMax.intValue()).isEqualTo(val1); Integer explicitMax = TestUtils.getPropertyValue( TestUtils.getPropertyValue(pubSubExplicitChannel, "dispatcher"), "maxSubscribers", Integer.class); - assertEquals(val2, explicitMax.intValue()); + assertThat(explicitMax.intValue()).isEqualTo(val2); Integer explicitMin = TestUtils.getPropertyValue(pubSubExplicitChannel, "dispatcher.minSubscribers", Integer.class); - assertEquals(1, explicitMin.intValue()); + assertThat(explicitMin.intValue()).isEqualTo(1); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EndpointRoleParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EndpointRoleParserTests.java index 6698a821da..7784eab3e7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EndpointRoleParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EndpointRoleParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -65,50 +64,50 @@ public class EndpointRoleParserTests { @Test public void test() { - assertFalse(this.in.isRunning()); - assertFalse(this.out1.isRunning()); - assertFalse(this.out2.isRunning()); - assertFalse(this.out3.isRunning()); - assertFalse(this.out4.isRunning()); - assertFalse(this.bridge.isRunning()); + assertThat(this.in.isRunning()).isFalse(); + assertThat(this.out1.isRunning()).isFalse(); + assertThat(this.out2.isRunning()).isFalse(); + assertThat(this.out3.isRunning()).isFalse(); + assertThat(this.out4.isRunning()).isFalse(); + assertThat(this.bridge.isRunning()).isFalse(); this.controller.startLifecyclesInRole("cluster"); - assertTrue(this.in.isRunning()); - assertTrue(this.out1.isRunning()); - assertTrue(this.out2.isRunning()); - assertTrue(this.out3.isRunning()); - assertFalse(this.out4.isRunning()); - assertTrue(this.bridge.isRunning()); + assertThat(this.in.isRunning()).isTrue(); + assertThat(this.out1.isRunning()).isTrue(); + assertThat(this.out2.isRunning()).isTrue(); + assertThat(this.out3.isRunning()).isTrue(); + assertThat(this.out4.isRunning()).isFalse(); + assertThat(this.bridge.isRunning()).isTrue(); this.controller.stopLifecyclesInRole("cluster"); - assertFalse(this.in.isRunning()); - assertFalse(this.out1.isRunning()); - assertFalse(this.out2.isRunning()); - assertFalse(this.out3.isRunning()); - assertFalse(this.out4.isRunning()); - assertFalse(this.bridge.isRunning()); + assertThat(this.in.isRunning()).isFalse(); + assertThat(this.out1.isRunning()).isFalse(); + assertThat(this.out2.isRunning()).isFalse(); + assertThat(this.out3.isRunning()).isFalse(); + assertThat(this.out4.isRunning()).isFalse(); + assertThat(this.bridge.isRunning()).isFalse(); this.controller.onApplicationEvent(new OnGrantedEvent("foo", null, "cluster")); - assertTrue(this.in.isRunning()); - assertTrue(this.out1.isRunning()); - assertTrue(this.out2.isRunning()); - assertTrue(this.out3.isRunning()); - assertFalse(this.out4.isRunning()); - assertTrue(this.bridge.isRunning()); + assertThat(this.in.isRunning()).isTrue(); + assertThat(this.out1.isRunning()).isTrue(); + assertThat(this.out2.isRunning()).isTrue(); + assertThat(this.out3.isRunning()).isTrue(); + assertThat(this.out4.isRunning()).isFalse(); + assertThat(this.bridge.isRunning()).isTrue(); this.controller.onApplicationEvent(new OnRevokedEvent("foo", null, "cluster")); - assertFalse(this.in.isRunning()); - assertFalse(this.out1.isRunning()); - assertFalse(this.out2.isRunning()); - assertFalse(this.out3.isRunning()); - assertFalse(this.out4.isRunning()); - assertFalse(this.bridge.isRunning()); + assertThat(this.in.isRunning()).isFalse(); + assertThat(this.out1.isRunning()).isFalse(); + assertThat(this.out2.isRunning()).isFalse(); + assertThat(this.out3.isRunning()).isFalse(); + assertThat(this.out4.isRunning()).isFalse(); + assertThat(this.bridge.isRunning()).isFalse(); - assertFalse(this.controller.allEndpointsRunning("cluster")); + assertThat(this.controller.allEndpointsRunning("cluster")).isFalse(); } public static class Sink { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests.java index a3327ffe18..25be4f6e6e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -71,31 +65,31 @@ public class EnricherParserTests { @SuppressWarnings("unchecked") public void configurationCheck() { Object endpoint = context.getBean("enricher"); - assertEquals(EventDrivenConsumer.class, endpoint.getClass()); + assertThat(endpoint.getClass()).isEqualTo(EventDrivenConsumer.class); Object handler = TestUtils.getPropertyValue(endpoint, "handler"); - assertEquals(ContentEnricher.class, handler.getClass()); + assertThat(handler.getClass()).isEqualTo(ContentEnricher.class); ContentEnricher enricher = (ContentEnricher) handler; - assertEquals(99, enricher.getOrder()); + assertThat(enricher.getOrder()).isEqualTo(99); DirectFieldAccessor accessor = new DirectFieldAccessor(enricher); - assertEquals(context.getBean("output"), accessor.getPropertyValue("outputChannel")); - assertEquals(true, accessor.getPropertyValue("shouldClonePayload")); - assertNull(accessor.getPropertyValue("requestPayloadExpression")); - assertNotNull(TestUtils.getPropertyValue(enricher, "gateway.beanFactory")); + assertThat(accessor.getPropertyValue("outputChannel")).isEqualTo(context.getBean("output")); + assertThat(accessor.getPropertyValue("shouldClonePayload")).isEqualTo(true); + assertThat(accessor.getPropertyValue("requestPayloadExpression")).isNull(); + assertThat(TestUtils.getPropertyValue(enricher, "gateway.beanFactory")).isNotNull(); Map propertyExpressions = (Map) accessor.getPropertyValue("propertyExpressions"); for (Map.Entry e : propertyExpressions.entrySet()) { if ("name".equals(e.getKey().getExpressionString())) { - assertEquals("payload.sourceName", e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo("payload.sourceName"); } else if ("age".equals(e.getKey().getExpressionString())) { - assertEquals("42", e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo("42"); } else if ("gender".equals(e.getKey().getExpressionString())) { - assertEquals(Gender.MALE.name(), e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo(Gender.MALE.name()); } else if ("married".equals(e.getKey().getExpressionString())) { - assertEquals(Boolean.TRUE.toString(), e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo(Boolean.TRUE.toString()); } else { throw new IllegalStateException("expected 'name', 'age', 'gender' and married only, not: " @@ -113,8 +107,8 @@ public class EnricherParserTests { Long requestTimeout = TestUtils.getPropertyValue(endpoint, "handler.requestTimeout", Long.class); Long replyTimeout = TestUtils.getPropertyValue(endpoint, "handler.replyTimeout", Long.class); - assertEquals(Long.valueOf(1234L), requestTimeout); - assertEquals(Long.valueOf(9876L), replyTimeout); + assertThat(requestTimeout).isEqualTo(Long.valueOf(1234L)); + assertThat(replyTimeout).isEqualTo(Long.valueOf(9876L)); } @@ -125,7 +119,7 @@ public class EnricherParserTests { boolean requiresReply = TestUtils.getPropertyValue(endpoint, "handler.requiresReply", Boolean.class); - assertTrue("Was expecting requiresReply to be 'false'", requiresReply); + assertThat(requiresReply).as("Was expecting requiresReply to be 'false'").isTrue(); } @@ -156,18 +150,18 @@ public class EnricherParserTests { Message reply = output.receive(0); Target enriched = (Target) reply.getPayload(); - assertEquals("foo", enriched.getName()); - assertEquals(42, enriched.getAge()); - assertEquals(Gender.MALE, enriched.getGender()); - assertTrue(enriched.isMarried()); - assertNotSame(original, enriched); - assertEquals(1, adviceCalled); + assertThat(enriched.getName()).isEqualTo("foo"); + assertThat(enriched.getAge()).isEqualTo(42); + assertThat(enriched.getGender()).isEqualTo(Gender.MALE); + assertThat(enriched.isMarried()).isTrue(); + assertThat(enriched).isNotSameAs(original); + assertThat(adviceCalled).isEqualTo(1); MessageHeaders headers = reply.getHeaders(); - assertEquals("bar", headers.get("foo")); - assertEquals(Gender.MALE, headers.get("testBean")); - assertEquals("foo", headers.get("sourceName")); - assertEquals("test", headers.get("notOverwrite")); + assertThat(headers.get("foo")).isEqualTo("bar"); + assertThat(headers.get("testBean")).isEqualTo(Gender.MALE); + assertThat(headers.get("sourceName")).isEqualTo("foo"); + assertThat(headers.get("notOverwrite")).isEqualTo("test"); requests.unsubscribe(foo); adviceCalled--; } @@ -179,10 +173,10 @@ public class EnricherParserTests { input.send(new GenericMessage("test")); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(MessageHandlingException.class)); - assertThat(e.getCause(), Matchers.instanceOf(TypeMismatchException.class)); - assertThat(e.getCause().getMessage(), - Matchers.startsWith("Failed to convert value of type 'java.util.Date' to required type 'int'")); + assertThat(e).isInstanceOf(MessageHandlingException.class); + assertThat(e.getCause()).isInstanceOf(TypeMismatchException.class); + assertThat(e.getCause().getMessage()) + .startsWith("Failed to convert value of type 'java.util.Date' to required type 'int'"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests2.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests2.java index 1d9807d6af..8b31437c29 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests2.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests2.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -48,7 +48,7 @@ public class EnricherParserTests2 { boolean requiresReply = TestUtils.getPropertyValue(endpoint, "handler.requiresReply", Boolean.class); - assertFalse("Was expecting requiresReply to be 'false'", requiresReply); + assertThat(requiresReply).as("Was expecting requiresReply to be 'false'").isFalse(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests3.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests3.java index ec2f89dbf0..be609b3f20 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests3.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests3.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,8 @@ package org.springframework.integration.config.xml; -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.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.Test; @@ -45,12 +43,12 @@ public class EnricherParserTests3 { MessageChannel beanResolveIn = context.getBean("beanResolveIn", MessageChannel.class); PollableChannel beanResolveOut = context.getBean("beanResolveOut", PollableChannel.class); SomeBean payload = new SomeBean("foo"); - assertEquals("foo", payload.getNested().getValue()); + assertThat(payload.getNested().getValue()).isEqualTo("foo"); beanResolveIn.send(new GenericMessage(payload)); @SuppressWarnings("unchecked") Message out = (Message) beanResolveOut.receive(); - assertSame(payload, out.getPayload()); - assertEquals("bar", out.getPayload().getNested().getValue()); + assertThat(out.getPayload()).isSameAs(payload); + assertThat(out.getPayload().getNested().getValue()).isEqualTo("bar"); context.close(); } @@ -60,13 +58,13 @@ public class EnricherParserTests3 { this.getClass().getSimpleName() + "-fail-context.xml", this.getClass()); MessageChannel beanResolveIn = context.getBean("beanResolveIn", MessageChannel.class); SomeBean payload = new SomeBean("foo"); - assertEquals("foo", payload.getNested().getValue()); + assertThat(payload.getNested().getValue()).isEqualTo("foo"); try { beanResolveIn.send(new GenericMessage(payload)); fail("Expected SpEL Exception"); } catch (MessageHandlingException e) { - assertTrue(e.getCause() instanceof SpelEvaluationException); + assertThat(e.getCause() instanceof SpelEvaluationException).isTrue(); } context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests4.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests4.java index 553e90390c..df94526855 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests4.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests4.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -71,18 +69,18 @@ public class EnricherParserTests4 { context.getBean("input", MessageChannel.class).send(request); Message reply = context.getBean("output", PollableChannel.class).receive(0); Target enriched = (Target) reply.getPayload(); - assertEquals("Could not determine the name", enriched.getName()); - assertEquals(11, enriched.getAge()); - assertEquals(null, enriched.getGender()); - assertTrue(enriched.isMarried()); - assertNotSame(original, enriched); - assertEquals(1, adviceCalled); + assertThat(enriched.getName()).isEqualTo("Could not determine the name"); + assertThat(enriched.getAge()).isEqualTo(11); + assertThat(enriched.getGender()).isEqualTo(null); + assertThat(enriched.isMarried()).isTrue(); + assertThat(enriched).isNotSameAs(original); + assertThat(adviceCalled).isEqualTo(1); MessageHeaders headers = reply.getHeaders(); - assertEquals("Could not determine the foo", headers.get("foo")); - assertEquals("Could not determine the testBean", headers.get("testBean")); - assertEquals("Could not determine the sourceName", headers.get("sourceName")); - assertEquals("test", headers.get("notOverwrite")); + assertThat(headers.get("foo")).isEqualTo("Could not determine the foo"); + assertThat(headers.get("testBean")).isEqualTo("Could not determine the testBean"); + assertThat(headers.get("sourceName")).isEqualTo("Could not determine the sourceName"); + assertThat(headers.get("notOverwrite")).isEqualTo("test"); adviceCalled--; requests.unsubscribe(foo); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests5.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests5.java index ad0f17ab1f..696e98ffb4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests5.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTests5.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -76,7 +76,7 @@ public class EnricherParserTests5 { Message reply = context.getBean("outputChannel", PollableChannel.class).receive(10000); Target enriched = (Target) reply.getPayload(); - assertEquals("Mr. Default", enriched.getName()); + assertThat(enriched.getName()).isEqualTo("Mr. Default"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTestsWithoutRequestChannel.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTestsWithoutRequestChannel.java index ce7734899b..ce9500b87c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTestsWithoutRequestChannel.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserTestsWithoutRequestChannel.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; @@ -57,27 +55,27 @@ public class EnricherParserTestsWithoutRequestChannel { @SuppressWarnings("unchecked") public void configurationCheck() { Object endpoint = context.getBean("enricher"); - assertEquals(EventDrivenConsumer.class, endpoint.getClass()); + assertThat(endpoint.getClass()).isEqualTo(EventDrivenConsumer.class); Object handler = TestUtils.getPropertyValue(endpoint, "handler"); - assertEquals(ContentEnricher.class, handler.getClass()); + assertThat(handler.getClass()).isEqualTo(ContentEnricher.class); ContentEnricher enricher = (ContentEnricher) handler; - assertEquals(99, enricher.getOrder()); + assertThat(enricher.getOrder()).isEqualTo(99); DirectFieldAccessor accessor = new DirectFieldAccessor(enricher); - assertNull(accessor.getPropertyValue("gateway")); - assertEquals(context.getBean("output"), accessor.getPropertyValue("outputChannel")); - assertEquals(false, accessor.getPropertyValue("shouldClonePayload")); - assertNull(accessor.getPropertyValue("requestPayloadExpression")); + assertThat(accessor.getPropertyValue("gateway")).isNull(); + assertThat(accessor.getPropertyValue("outputChannel")).isEqualTo(context.getBean("output")); + assertThat(accessor.getPropertyValue("shouldClonePayload")).isEqualTo(false); + assertThat(accessor.getPropertyValue("requestPayloadExpression")).isNull(); Map propertyExpressions = (Map) accessor.getPropertyValue("propertyExpressions"); for (Map.Entry e : propertyExpressions.entrySet()) { if ("name".equals(e.getKey().getExpressionString())) { - assertEquals("payload.name", e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo("payload.name"); } else if ("age".equals(e.getKey().getExpressionString())) { - assertEquals("42", e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo("42"); } else { throw new IllegalStateException( @@ -98,9 +96,9 @@ public class EnricherParserTestsWithoutRequestChannel { context.getBean("input", MessageChannel.class).send(request); Message reply = context.getBean("output", PollableChannel.class).receive(0); Target enriched = (Target) reply.getPayload(); - assertEquals("original name", enriched.getName()); - assertEquals(42, enriched.getAge()); - assertSame(original, enriched); + assertThat(enriched.getName()).isEqualTo("original name"); + assertThat(enriched.getAge()).isEqualTo(42); + assertThat(enriched).isSameAs(original); } public static class Target implements Cloneable { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserWithRequestPayloadExpressionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserWithRequestPayloadExpressionTests.java index c3a5e2070d..e9d73cb7d1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserWithRequestPayloadExpressionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/EnricherParserWithRequestPayloadExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; @@ -58,26 +56,26 @@ public class EnricherParserWithRequestPayloadExpressionTests { @SuppressWarnings("unchecked") public void configurationCheck() { Object endpoint = context.getBean("enricher"); - assertEquals(EventDrivenConsumer.class, endpoint.getClass()); + assertThat(endpoint.getClass()).isEqualTo(EventDrivenConsumer.class); Object handler = TestUtils.getPropertyValue(endpoint, "handler"); - assertEquals(ContentEnricher.class, handler.getClass()); + assertThat(handler.getClass()).isEqualTo(ContentEnricher.class); ContentEnricher enricher = (ContentEnricher) handler; - assertEquals(99, enricher.getOrder()); + assertThat(enricher.getOrder()).isEqualTo(99); DirectFieldAccessor accessor = new DirectFieldAccessor(enricher); - assertEquals(context.getBean("output"), accessor.getPropertyValue("outputChannel")); - assertEquals(false, accessor.getPropertyValue("shouldClonePayload")); + assertThat(accessor.getPropertyValue("outputChannel")).isEqualTo(context.getBean("output")); + assertThat(accessor.getPropertyValue("shouldClonePayload")).isEqualTo(false); Expression requestPayloadExpression = (Expression) accessor.getPropertyValue("requestPayloadExpression"); - assertEquals("payload.age", requestPayloadExpression.getExpressionString()); + assertThat(requestPayloadExpression.getExpressionString()).isEqualTo("payload.age"); Map propertyExpressions = (Map) accessor.getPropertyValue("propertyExpressions"); for (Map.Entry e : propertyExpressions.entrySet()) { if ("name".equals(e.getKey().getExpressionString())) { - assertEquals("'Name as SpEL'", e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo("'Name as SpEL'"); } else if ("age".equals(e.getKey().getExpressionString())) { - assertEquals("payload.sourceName", e.getValue().getExpressionString()); + assertThat(e.getValue().getExpressionString()).isEqualTo("payload.sourceName"); } else { throw new IllegalStateException( @@ -94,11 +92,11 @@ public class EnricherParserWithRequestPayloadExpressionTests { @Override protected Object handleRequestMessage(Message requestMessage) { - assertTrue("Expected the payload of the requestMessage to be a String", - requestMessage.getPayload() instanceof Integer); + assertThat(requestMessage.getPayload() instanceof Integer) + .as("Expected the payload of the requestMessage to be a String").isTrue(); Integer payload = (Integer) requestMessage.getPayload(); - assertEquals("Expected value: 99", Integer.valueOf(99), payload); + assertThat(payload).as("Expected value: 99").isEqualTo(Integer.valueOf(99)); return new Source(String.valueOf(payload)); } @@ -111,9 +109,9 @@ public class EnricherParserWithRequestPayloadExpressionTests { context.getBean("input", MessageChannel.class).send(request); Message reply = context.getBean("output", PollableChannel.class).receive(0); Target enriched = (Target) reply.getPayload(); - assertEquals("Name as SpEL", enriched.getName()); - assertEquals(99, enriched.getAge()); - assertSame(original, enriched); + assertThat(enriched.getName()).isEqualTo("Name as SpEL"); + assertThat(enriched.getAge()).isEqualTo(99); + assertThat(enriched).isSameAs(original); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorChannelAutoCreationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorChannelAutoCreationTests.java index 77cb468dfa..cc37bfe983 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorChannelAutoCreationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorChannelAutoCreationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -41,7 +41,7 @@ public class ErrorChannelAutoCreationTests { // see INT-1899 @Test public void testErrorChannelIsPubSub() { - assertEquals(PublishSubscribeChannel.class, errorChannel.getClass()); + assertThat(errorChannel.getClass()).isEqualTo(PublishSubscribeChannel.class); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorMessageExceptionTypeRouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorMessageExceptionTypeRouterParserTests.java index 45117a5111..d5f622702f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorMessageExceptionTypeRouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ErrorMessageExceptionTypeRouterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -54,13 +53,13 @@ public class ErrorMessageExceptionTypeRouterParserTests { public void validateExceptionTypeRouterConfig() { inputChannel.send(new ErrorMessage(new NullPointerException())); - assertThat(npeChannel.receive(1000).getPayload(), instanceOf(NullPointerException.class)); + assertThat(npeChannel.receive(1000).getPayload()).isInstanceOf(NullPointerException.class); inputChannel.send(new ErrorMessage(new IllegalArgumentException())); - assertThat(illegalChannel.receive(1000).getPayload(), instanceOf(IllegalArgumentException.class)); + assertThat(illegalChannel.receive(1000).getPayload()).isInstanceOf(IllegalArgumentException.class); inputChannel.send(new ErrorMessage(new RuntimeException())); - assertThat(defaultChannel.receive(1000).getPayload(), instanceOf(RuntimeException.class)); + assertThat(defaultChannel.receive(1000).getPayload()).isInstanceOf(RuntimeException.class); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java index 2186f1c7b9..321dbab7af 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -87,7 +83,7 @@ public class GatewayParserTests { service.oneWay("foo"); PollableChannel channel = (PollableChannel) context.getBean("requestChannel"); Message result = channel.receive(10000); - assertEquals("foo", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo"); } @Test @@ -96,26 +92,27 @@ public class GatewayParserTests { service.oneWay("foo"); PollableChannel channel = (PollableChannel) context.getBean("otherRequestChannel"); Message result = channel.receive(10000); - assertNotNull(result); - assertEquals("fiz", result.getPayload()); - assertEquals("bar", result.getHeaders().get("foo")); - assertEquals("qux", result.getHeaders().get("baz")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("fiz"); + assertThat(result.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(result.getHeaders().get("baz")).isEqualTo("qux"); GatewayProxyFactoryBean fb = context.getBean("&methodOverride", GatewayProxyFactoryBean.class); - assertEquals(1000L, TestUtils.getPropertyValue(fb, "defaultRequestTimeout", Expression.class).getValue()); - assertEquals(2000L, TestUtils.getPropertyValue(fb, "defaultReplyTimeout", Expression.class).getValue()); + assertThat(TestUtils.getPropertyValue(fb, "defaultRequestTimeout", Expression.class).getValue()) + .isEqualTo(1000L); + assertThat(TestUtils.getPropertyValue(fb, "defaultReplyTimeout", Expression.class).getValue()).isEqualTo(2000L); Map methods = TestUtils.getPropertyValue(fb, "methodMetadataMap", Map.class); GatewayMethodMetadata meta = (GatewayMethodMetadata) methods.get("oneWay"); - assertNotNull(meta); - assertEquals("456", meta.getRequestTimeout()); - assertEquals("123", meta.getReplyTimeout()); - assertEquals("foo", meta.getReplyChannelName()); + assertThat(meta).isNotNull(); + assertThat(meta.getRequestTimeout()).isEqualTo("456"); + assertThat(meta.getReplyTimeout()).isEqualTo("123"); + assertThat(meta.getReplyChannelName()).isEqualTo("foo"); meta = (GatewayMethodMetadata) methods.get("oneWayWithTimeouts"); - assertNotNull(meta); - assertEquals("#args[1]", meta.getRequestTimeout()); - assertEquals("#args[2]", meta.getReplyTimeout()); + assertThat(meta).isNotNull(); + assertThat(meta.getRequestTimeout()).isEqualTo("#args[1]"); + assertThat(meta.getReplyTimeout()).isEqualTo("#args[2]"); service.oneWayWithTimeouts("foo", 100L, 200L); result = channel.receive(10000); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test @@ -124,7 +121,7 @@ public class GatewayParserTests { channel.send(new GenericMessage("foo")); TestService service = (TestService) context.getBean("solicitResponse"); String result = service.solicitResponse(); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test @@ -134,7 +131,7 @@ public class GatewayParserTests { this.startResponder(requestChannel, replyChannel); TestService service = (TestService) context.getBean("requestReply"); String result = service.requestReply("foo"); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test @@ -145,9 +142,9 @@ public class GatewayParserTests { TestService service = context.getBean("async", TestService.class); Future> result = service.async("foo"); Message reply = result.get(10, TimeUnit.SECONDS); - assertEquals("foo", reply.getPayload()); - assertEquals("testExecutor", reply.getHeaders().get("executor")); - assertNotNull(TestUtils.getPropertyValue(context.getBean("&async"), "asyncExecutor")); + assertThat(reply.getPayload()).isEqualTo("foo"); + assertThat(reply.getHeaders().get("executor")).isEqualTo("testExecutor"); + assertThat(TestUtils.getPropertyValue(context.getBean("&async"), "asyncExecutor")).isNotNull(); } @Test @@ -158,9 +155,9 @@ public class GatewayParserTests { TestService service = context.getBean("asyncOff", TestService.class); Future> result = service.async("futureSync"); Message reply = result.get(10, TimeUnit.SECONDS); - assertEquals("futureSync", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("futureSync"); Object serviceBean = context.getBean("&asyncOff"); - assertNull(TestUtils.getPropertyValue(serviceBean, "asyncExecutor")); + assertThat(TestUtils.getPropertyValue(serviceBean, "asyncExecutor")).isNull(); } @Test @@ -168,7 +165,7 @@ public class GatewayParserTests { ConfigurableListableBeanFactory beanFactory = ((GenericApplicationContext) context).getBeanFactory(); Object attribute = beanFactory.getMergedBeanDefinition("&oneWay").getAttribute( IntegrationConfigUtils.FACTORY_BEAN_OBJECT_TYPE); - assertEquals(TestService.class.getName(), attribute); + assertThat(attribute).isEqualTo(TestService.class.getName()); } @Test @@ -176,7 +173,7 @@ public class GatewayParserTests { ConfigurableListableBeanFactory beanFactory = ((GenericApplicationContext) context).getBeanFactory(); Object attribute = beanFactory.getMergedBeanDefinition("&defaultConfig").getAttribute( IntegrationConfigUtils.FACTORY_BEAN_OBJECT_TYPE); - assertEquals(RequestReplyExchanger.class.getName(), attribute); + assertThat(attribute).isEqualTo(RequestReplyExchanger.class.getName()); } @Test @@ -187,8 +184,8 @@ public class GatewayParserTests { TestService service = context.getBean("promise", TestService.class); Mono> result = service.promise("foo"); Message reply = result.block(Duration.ofSeconds(1)); - assertEquals("foo", reply.getPayload()); - assertNotNull(TestUtils.getPropertyValue(context.getBean("&promise"), "asyncExecutor")); + assertThat(reply.getPayload()).isEqualTo("foo"); + assertThat(TestUtils.getPropertyValue(context.getBean("&promise"), "asyncExecutor")).isNotNull(); } @Test @@ -209,9 +206,9 @@ public class GatewayParserTests { TestService service = context.getBean("asyncCompletable", TestService.class); CompletableFuture result = service.completable("foo").thenApply(String::toUpperCase); String reply = result.get(10, TimeUnit.SECONDS); - assertEquals("FOO", reply); - assertThat(thread.get().getName(), startsWith("testExec-")); - assertNotNull(TestUtils.getPropertyValue(context.getBean("&asyncCompletable"), "asyncExecutor")); + assertThat(reply).isEqualTo("FOO"); + assertThat(thread.get().getName()).startsWith("testExec-"); + assertThat(TestUtils.getPropertyValue(context.getBean("&asyncCompletable"), "asyncExecutor")).isNotNull(); } @Test @@ -232,9 +229,9 @@ public class GatewayParserTests { TestService service = context.getBean("completableNoAsync", TestService.class); CompletableFuture result = service.completable("flowCompletable"); String reply = result.get(10, TimeUnit.SECONDS); - assertEquals("SYNC_COMPLETABLE", reply); - assertEquals(Thread.currentThread(), thread.get()); - assertNull(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")); + assertThat(reply).isEqualTo("SYNC_COMPLETABLE"); + assertThat(thread.get()).isEqualTo(Thread.currentThread()); + assertThat(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")).isNull(); } @Test @@ -255,9 +252,9 @@ public class GatewayParserTests { TestService service = context.getBean("completableNoAsync", TestService.class); MyCompletableFuture result = service.customCompletable("flowCustomCompletable"); String reply = result.get(10, TimeUnit.SECONDS); - assertEquals("SYNC_CUSTOM_COMPLETABLE", reply); - assertEquals(Thread.currentThread(), thread.get()); - assertNull(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")); + assertThat(reply).isEqualTo("SYNC_CUSTOM_COMPLETABLE"); + assertThat(thread.get()).isEqualTo(Thread.currentThread()); + assertThat(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")).isNull(); } @Test @@ -282,9 +279,9 @@ public class GatewayParserTests { TestService service = context.getBean("customCompletableAttemptAsync", TestService.class); MyCompletableFuture result = service.customCompletable("flowCustomCompletable"); String reply = result.get(10, TimeUnit.SECONDS); - assertEquals("SYNC_CUSTOM_COMPLETABLE", reply); - assertEquals(Thread.currentThread(), thread.get()); - assertNotNull(TestUtils.getPropertyValue(gateway, "asyncExecutor")); + assertThat(reply).isEqualTo("SYNC_CUSTOM_COMPLETABLE"); + assertThat(thread.get()).isEqualTo(Thread.currentThread()); + assertThat(TestUtils.getPropertyValue(gateway, "asyncExecutor")).isNotNull(); verify(logger).debug("AsyncTaskExecutor submit*() return types are incompatible with the method return type; " + "running on calling thread; the downstream flow must return the required Future: " + "MyCompletableFuture"); @@ -308,9 +305,9 @@ public class GatewayParserTests { TestService service = context.getBean("asyncCompletable", TestService.class); CompletableFuture> result = service.completableReturnsMessage("foo"); Message reply = result.get(10, TimeUnit.SECONDS); - assertEquals("foo", reply.getPayload()); - assertThat(thread.get().getName(), startsWith("testExec-")); - assertNotNull(TestUtils.getPropertyValue(context.getBean("&asyncCompletable"), "asyncExecutor")); + assertThat(reply.getPayload()).isEqualTo("foo"); + assertThat(thread.get().getName()).startsWith("testExec-"); + assertThat(TestUtils.getPropertyValue(context.getBean("&asyncCompletable"), "asyncExecutor")).isNotNull(); } @Test @@ -331,9 +328,9 @@ public class GatewayParserTests { TestService service = context.getBean("completableNoAsync", TestService.class); CompletableFuture> result = service.completableReturnsMessage("flowCompletableM"); Message reply = result.get(10, TimeUnit.SECONDS); - assertEquals("flowCompletableM", reply.getPayload()); - assertEquals(Thread.currentThread(), thread.get()); - assertNull(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")); + assertThat(reply.getPayload()).isEqualTo("flowCompletableM"); + assertThat(thread.get()).isEqualTo(Thread.currentThread()); + assertThat(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")).isNull(); } @Test @@ -354,15 +351,15 @@ public class GatewayParserTests { TestService service = context.getBean("completableNoAsync", TestService.class); MyCompletableMessageFuture result = service.customCompletableReturnsMessage("flowCustomCompletableM"); Message reply = result.get(10, TimeUnit.SECONDS); - assertEquals("flowCustomCompletableM", reply.getPayload()); - assertEquals(Thread.currentThread(), thread.get()); - assertNull(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")); + assertThat(reply.getPayload()).isEqualTo("flowCustomCompletableM"); + assertThat(thread.get()).isEqualTo(Thread.currentThread()); + assertThat(TestUtils.getPropertyValue(context.getBean("&completableNoAsync"), "asyncExecutor")).isNull(); } private void startResponder(final PollableChannel requestChannel, final MessageChannel replyChannel) { Executors.newSingleThreadExecutor().execute(() -> { Message request = requestChannel.receive(60000); - assertNotNull("Request not received", request); + assertThat(request).as("Request not received").isNotNull(); Message reply = MessageBuilder.fromMessage(request) .setCorrelationId(request.getHeaders().getId()).build(); Object payload = null; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherMethodInvokingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherMethodInvokingTests.java index 57ec9aad83..899559e91f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherMethodInvokingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherMethodInvokingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; @@ -55,12 +54,12 @@ public class HeaderEnricherMethodInvokingTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); - assertEquals(123, result.getHeaders().get("foo")); - assertEquals("ABC", result.getHeaders().get("bar")); - assertEquals("zzz", result.getHeaders().get("other")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); + assertThat(result.getHeaders().get("foo")).isEqualTo(123); + assertThat(result.getHeaders().get("bar")).isEqualTo("ABC"); + assertThat(result.getHeaders().get("other")).isEqualTo("zzz"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java index 9002ac7860..1853274896 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -60,10 +58,10 @@ public class HeaderEnricherOverwriteTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannelToOverwrite).build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); - assertNull(replyChannelToOverwrite.receive(0)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); + assertThat(replyChannelToOverwrite.receive(0)).isNull(); } @Test @@ -74,9 +72,9 @@ public class HeaderEnricherOverwriteTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test @@ -90,9 +88,9 @@ public class HeaderEnricherOverwriteTests { Message message = MessageBuilder.withPayload("test").build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test @@ -105,10 +103,10 @@ public class HeaderEnricherOverwriteTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannelToOverwrite).build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); - assertNull(replyChannelToOverwrite.receive(0)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); + assertThat(replyChannelToOverwrite.receive(0)).isNull(); } @Test @@ -119,9 +117,9 @@ public class HeaderEnricherOverwriteTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test @@ -133,9 +131,9 @@ public class HeaderEnricherOverwriteTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test @@ -149,9 +147,9 @@ public class HeaderEnricherOverwriteTests { Message message = MessageBuilder.withPayload("test").build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test @@ -160,8 +158,8 @@ public class HeaderEnricherOverwriteTests { MessagingTemplate template = new MessagingTemplate(); template.setDefaultDestination(channel); Message result = template.sendAndReceive(new GenericMessage("test")); - assertNotNull(result); - assertEquals(new Integer(42), new IntegrationMessageHeaderAccessor(result).getPriority()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(42)); } @Test @@ -174,8 +172,8 @@ public class HeaderEnricherOverwriteTests { .build(); input.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals(new Integer(77), new IntegrationMessageHeaderAccessor(result).getPriority()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(77)); } @Test @@ -188,9 +186,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("zzz", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("zzz"); } @Test @@ -203,9 +201,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("bar", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -218,9 +216,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("zzz", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("zzz"); } @Test @@ -234,9 +232,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("123", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("123"); } @Test @@ -250,9 +248,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("bar", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -265,9 +263,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("123", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("123"); } @Test @@ -280,9 +278,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("ABC", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("ABC"); } @Test @@ -295,9 +293,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("bar", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -310,9 +308,9 @@ public class HeaderEnricherOverwriteTests { .build(); inputChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("ABC", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().get("foo")).isEqualTo("ABC"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java index 684709864e..f1a2513440 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -51,35 +49,35 @@ public class HeaderEnricherParserTests { public void sendTimeoutDefault() { Object endpoint = context.getBean("headerEnricherWithDefaults"); long sendTimeout = TestUtils.getPropertyValue(endpoint, "handler.messagingTemplate.sendTimeout", Long.class); - assertEquals(-1L, sendTimeout); + assertThat(sendTimeout).isEqualTo(-1L); } @Test // INT-1154 public void sendTimeoutConfigured() { Object endpoint = context.getBean("headerEnricherWithSendTimeout"); long sendTimeout = TestUtils.getPropertyValue(endpoint, "handler.messagingTemplate.sendTimeout", Long.class); - assertEquals(1234L, sendTimeout); + assertThat(sendTimeout).isEqualTo(1234L); } @Test // INT-1167 public void shouldSkipNullsDefault() { Object endpoint = context.getBean("headerEnricherWithDefaults"); Boolean shouldSkipNulls = TestUtils.getPropertyValue(endpoint, "handler.transformer.shouldSkipNulls", Boolean.class); - assertEquals(Boolean.TRUE, shouldSkipNulls); + assertThat(shouldSkipNulls).isEqualTo(Boolean.TRUE); } @Test // INT-1167 public void shouldSkipNullsFalseConfigured() { Object endpoint = context.getBean("headerEnricherWithShouldSkipNullsFalse"); Boolean shouldSkipNulls = TestUtils.getPropertyValue(endpoint, "handler.transformer.shouldSkipNulls", Boolean.class); - assertEquals(Boolean.FALSE, shouldSkipNulls); + assertThat(shouldSkipNulls).isEqualTo(Boolean.FALSE); } @Test // INT-1167 public void shouldSkipNullsTrueConfigured() { Object endpoint = context.getBean("headerEnricherWithShouldSkipNullsTrue"); Boolean shouldSkipNulls = TestUtils.getPropertyValue(endpoint, "handler.transformer.shouldSkipNulls", Boolean.class); - assertEquals(Boolean.TRUE, shouldSkipNulls); + assertThat(shouldSkipNulls).isEqualTo(Boolean.TRUE); } @Test(expected = MessageTransformationException.class) @@ -98,10 +96,10 @@ public class HeaderEnricherParserTests { Message message = MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build(); messageHandler.handleMessage(message); Message transformed = replyChannel.receive(1000); - assertNotNull(transformed); + assertThat(transformed).isNotNull(); Object priority = transformed.getHeaders().get("priority"); - assertNotNull(priority); - assertTrue(priority instanceof Integer); + assertThat(priority).isNotNull(); + assertThat(priority instanceof Integer).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java index 01fbfdd7e8..9f0928241a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Date; @@ -66,9 +61,9 @@ public class HeaderEnricherTests { MessageChannel inputChannel = context.getBean("replyChannelInput", MessageChannel.class); inputChannel.send(new GenericMessage<>("test")); Message result = replyChannel.receive(10000); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test //INT-2316 @@ -77,9 +72,9 @@ public class HeaderEnricherTests { MessageChannel inputChannel = context.getBean("replyChannelNameInput", MessageChannel.class); inputChannel.send(new GenericMessage<>("test")); Message result = replyChannel.receive(10000); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals("testReplyChannel", result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo("testReplyChannel"); } @Test //INT-2316 @@ -88,9 +83,9 @@ public class HeaderEnricherTests { MessageChannel inputChannel = context.getBean("replyChannelExpressionInput", MessageChannel.class); inputChannel.send(new GenericMessage<>("test")); Message result = replyChannel.receive(10000); - assertNotNull(result); - assertEquals("TEST", result.getPayload()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("TEST"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test @@ -99,12 +94,12 @@ public class HeaderEnricherTests { MessageChannel inputChannel = context.getBean("errorChannelInput", MessageChannel.class); inputChannel.send(new GenericMessage<>("test")); Message errorMessage = errorChannel.receive(10000); - assertNotNull(errorMessage); + assertThat(errorMessage).isNotNull(); Object errorPayload = errorMessage.getPayload(); - assertEquals(MessageTransformationException.class, errorPayload.getClass()); + assertThat(errorPayload.getClass()).isEqualTo(MessageTransformationException.class); Message failedMessage = ((MessageTransformationException) errorPayload).getFailedMessage(); - assertEquals("test", failedMessage.getPayload()); - assertEquals(errorChannel, failedMessage.getHeaders().getErrorChannel()); + assertThat(failedMessage.getPayload()).isEqualTo("test"); + assertThat(failedMessage.getHeaders().getErrorChannel()).isEqualTo(errorChannel); } @Test @@ -112,8 +107,8 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("correlationIdValueInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals("ABC", new IntegrationMessageHeaderAccessor(result).getCorrelationId()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getCorrelationId()).isEqualTo("ABC"); } @Test @@ -121,10 +116,10 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("correlationIdValueWithTypeInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); + assertThat(result).isNotNull(); Object correlationId = new IntegrationMessageHeaderAccessor(result).getCorrelationId(); - assertEquals(Long.class, correlationId.getClass()); - assertEquals(123L, correlationId); + assertThat(correlationId.getClass()).isEqualTo(Long.class); + assertThat(correlationId).isEqualTo(123L); } @Test @@ -132,8 +127,8 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("correlationIdRefInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(123, new IntegrationMessageHeaderAccessor(result).getCorrelationId()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getCorrelationId()).isEqualTo(123); } @Test @@ -141,8 +136,8 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("expirationDateValueInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(new Long(1111), new IntegrationMessageHeaderAccessor(result).getExpirationDate()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getExpirationDate()).isEqualTo(new Long(1111)); } @Test @@ -150,8 +145,8 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("expirationDateRefInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(new Long(9999), new IntegrationMessageHeaderAccessor(result).getExpirationDate()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getExpirationDate()).isEqualTo(new Long(9999)); } @Test @@ -159,8 +154,8 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("priorityInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(new Integer(42), new IntegrationMessageHeaderAccessor(result).getPriority()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(42)); } @Test @@ -169,8 +164,8 @@ public class HeaderEnricherTests { MessageChannel channel = context.getBean("priorityExpressionInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>(Collections.singletonMap("priority", "-10"))); - assertNotNull(result); - assertEquals(new Integer(-10), new IntegrationMessageHeaderAccessor(result).getPriority()); + assertThat(result).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(-10)); } @Test @@ -178,8 +173,8 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("payloadExpressionInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>(new TestBean("foo"))); - assertNotNull(result); - assertEquals("foobar", result.getHeaders().get("testHeader")); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("testHeader")).isEqualTo("foobar"); } @Test @@ -188,8 +183,8 @@ public class HeaderEnricherTests { MessageChannel channel = context.getBean("headerExpressionInput", MessageChannel.class); Message message = MessageBuilder.withPayload("test").setHeader("testHeader1", "foo").build(); Message result = template.sendAndReceive(channel, message); - assertNotNull(result); - assertEquals("foobar", result.getHeaders().get("testHeader2")); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("testHeader2")).isEqualTo("foobar"); } @Test @@ -197,11 +192,11 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("expressionWithDateTypeInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); + assertThat(result).isNotNull(); Object headerValue = result.getHeaders().get("currentDate"); - assertEquals(Date.class, headerValue.getClass()); + assertThat(headerValue.getClass()).isEqualTo(Date.class); Date date = (Date) headerValue; - assertTrue(new Date().getTime() - date.getTime() < 1000); + assertThat(new Date().getTime() - date.getTime() < 1000).isTrue(); } @Test @@ -209,9 +204,9 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("expressionWithLongTypeInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(Long.class, result.getHeaders().get("number").getClass()); - assertEquals(12345L, result.getHeaders().get("number")); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("number").getClass()).isEqualTo(Long.class); + assertThat(result.getHeaders().get("number")).isEqualTo(12345L); } @Test @@ -219,9 +214,9 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("refWithMethod", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(String.class, result.getHeaders().get("testHeader").getClass()); - assertEquals("testBeanForMethodInvoker", result.getHeaders().get("testHeader")); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("testHeader").getClass()).isEqualTo(String.class); + assertThat(result.getHeaders().get("testHeader")).isEqualTo("testBeanForMethodInvoker"); } @Test @@ -229,10 +224,10 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("ref", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(TestBean.class, result.getHeaders().get("testHeader").getClass()); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("testHeader").getClass()).isEqualTo(TestBean.class); TestBean testBeanForRef = context.getBean("testBean1", TestBean.class); - assertSame(testBeanForRef, result.getHeaders().get("testHeader")); + assertThat(result.getHeaders().get("testHeader")).isSameAs(testBeanForRef); } @Test @@ -240,10 +235,10 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("innerBean", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(TestBean.class, result.getHeaders().get("testHeader").getClass()); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("testHeader").getClass()).isEqualTo(TestBean.class); TestBean testBeanForInnerBean = new TestBean("testBeanForInnerBean"); - assertEquals(testBeanForInnerBean, result.getHeaders().get("testHeader")); + assertThat(result.getHeaders().get("testHeader")).isEqualTo(testBeanForInnerBean); } @Test @@ -251,9 +246,9 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("innerBeanWithMethod", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); - assertEquals(String.class, result.getHeaders().get("testHeader").getClass()); - assertEquals("testBeanForInnerBeanWithMethod", result.getHeaders().get("testHeader")); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("testHeader").getClass()).isEqualTo(String.class); + assertThat(result.getHeaders().get("testHeader")).isEqualTo("testBeanForInnerBeanWithMethod"); } @Test(expected = BeanDefinitionParsingException.class) @@ -267,17 +262,17 @@ public class HeaderEnricherTests { MessagingTemplate template = new MessagingTemplate(); MessageChannel channel = context.getBean("routingSlipInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); - assertNotNull(result); + assertThat(result).isNotNull(); Object routingSlip = new IntegrationMessageHeaderAccessor(result) .getHeader(IntegrationMessageHeaderAccessor.ROUTING_SLIP); - assertNotNull(routingSlip); - assertThat(routingSlip, instanceOf(Map.class)); + assertThat(routingSlip).isNotNull(); + assertThat(routingSlip).isInstanceOf(Map.class); @SuppressWarnings("unchecked") List routingSlipPath = (List) ((Map) routingSlip).keySet().iterator().next(); - assertEquals("fooChannel", routingSlipPath.get(0)); - assertThat(routingSlipPath.get(1), instanceOf(ExpressionEvaluatingRoutingSlipRouteStrategy.class)); - assertEquals("bazRoutingSlip", routingSlipPath.get(2)); + assertThat(routingSlipPath.get(0)).isEqualTo("fooChannel"); + assertThat(routingSlipPath.get(1)).isInstanceOf(ExpressionEvaluatingRoutingSlipRouteStrategy.class); + assertThat(routingSlipPath.get(2)).isEqualTo("bazRoutingSlip"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderFilterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderFilterParserTests.java index 0de456702d..352677525b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderFilterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderFilterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -70,13 +68,13 @@ public class HeaderFilterParserTests { .build(); inputA.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); - assertNull(result.getHeaders().get("a")); - assertNull(result.getHeaders().get("c")); - assertNull(result.getHeaders().get("d")); - assertNotNull(result.getHeaders().get("b")); - assertNotNull(result.getHeaders().get("e")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get("a")).isNull(); + assertThat(result.getHeaders().get("c")).isNull(); + assertThat(result.getHeaders().get("d")).isNull(); + assertThat(result.getHeaders().get("b")).isNotNull(); + assertThat(result.getHeaders().get("e")).isNotNull(); } @Test @@ -92,13 +90,13 @@ public class HeaderFilterParserTests { .build(); inputB.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); - assertNull(result.getHeaders().get("a")); - assertNull(result.getHeaders().get("c")); - assertNull(result.getHeaders().get("d")); - assertNull(result.getHeaders().get("b")); - assertNull(result.getHeaders().get("e")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get("a")).isNull(); + assertThat(result.getHeaders().get("c")).isNull(); + assertThat(result.getHeaders().get("d")).isNull(); + assertThat(result.getHeaders().get("b")).isNull(); + assertThat(result.getHeaders().get("e")).isNull(); } @Test @@ -114,13 +112,13 @@ public class HeaderFilterParserTests { .build(); inputC.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); - assertNull(result.getHeaders().get("bar")); - assertNull(result.getHeaders().get("baz")); - assertNull(result.getHeaders().get("foo")); - assertNull(result.getHeaders().get("goo")); - assertNotNull(result.getHeaders().get("e")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get("bar")).isNull(); + assertThat(result.getHeaders().get("baz")).isNull(); + assertThat(result.getHeaders().get("foo")).isNull(); + assertThat(result.getHeaders().get("goo")).isNull(); + assertThat(result.getHeaders().get("e")).isNotNull(); } @Test @@ -136,13 +134,13 @@ public class HeaderFilterParserTests { .build(); inputD.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); - assertNull(result.getHeaders().get("bar*")); - assertNull(result.getHeaders().get("bart")); - assertNull(result.getHeaders().get("foo")); - assertNull(result.getHeaders().get("goo")); - assertNotNull(result.getHeaders().get("e")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get("bar*")).isNull(); + assertThat(result.getHeaders().get("bart")).isNull(); + assertThat(result.getHeaders().get("foo")).isNull(); + assertThat(result.getHeaders().get("goo")).isNull(); + assertThat(result.getHeaders().get("e")).isNotNull(); } @Test @@ -158,13 +156,13 @@ public class HeaderFilterParserTests { .build(); inputE.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); - assertNull(result.getHeaders().get("bar*")); - assertNotNull(result.getHeaders().get("bart")); - assertNull(result.getHeaders().get("foo")); - assertNotNull(result.getHeaders().get("goo")); - assertNotNull(result.getHeaders().get("e")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get("bar*")).isNull(); + assertThat(result.getHeaders().get("bart")).isNotNull(); + assertThat(result.getHeaders().get("foo")).isNull(); + assertThat(result.getHeaders().get("goo")).isNotNull(); + assertThat(result.getHeaders().get("e")).isNotNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IdempotentReceiverParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IdempotentReceiverParserTests.java index c4aa8cccb6..be222a348e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IdempotentReceiverParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IdempotentReceiverParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2015 the original author or authors. + * Copyright 2014-2019 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,15 +16,8 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.springframework.integration.test.util.TestUtils.getPropertyValue; import java.io.ByteArrayInputStream; @@ -96,54 +89,54 @@ public class IdempotentReceiverParserTests { @Test public void testSelectorInterceptor() { - assertSame(this.selector, getPropertyValue(this.selectorInterceptor, "messageSelector")); - assertNull(getPropertyValue(this.selectorInterceptor, "discardChannel")); - assertFalse(getPropertyValue(this.selectorInterceptor, "throwExceptionOnRejection", Boolean.class)); + assertThat(getPropertyValue(this.selectorInterceptor, "messageSelector")).isSameAs(this.selector); + assertThat(getPropertyValue(this.selectorInterceptor, "discardChannel")).isNull(); + assertThat(getPropertyValue(this.selectorInterceptor, "throwExceptionOnRejection", Boolean.class)).isFalse(); @SuppressWarnings("unchecked") Map> idempotentEndpoints = (Map>) getPropertyValue(this.idempotentReceiverAutoProxyCreator, "idempotentEndpoints", Map.class); List endpoints = idempotentEndpoints.get("selectorInterceptor"); - assertNotNull(endpoints); - assertFalse(endpoints.isEmpty()); - assertTrue(endpoints.contains("foo.handler")); + assertThat(endpoints).isNotNull(); + assertThat(endpoints.isEmpty()).isFalse(); + assertThat(endpoints.contains("foo.handler")).isTrue(); } @Test public void testStrategyInterceptor() { - assertSame(this.nullChannel, getPropertyValue(this.strategyInterceptor, "discardChannel")); - assertTrue(getPropertyValue(this.strategyInterceptor, "throwExceptionOnRejection", Boolean.class)); + assertThat(getPropertyValue(this.strategyInterceptor, "discardChannel")).isSameAs(this.nullChannel); + assertThat(getPropertyValue(this.strategyInterceptor, "throwExceptionOnRejection", Boolean.class)).isTrue(); Object messageSelector = getPropertyValue(this.strategyInterceptor, "messageSelector"); - assertThat(messageSelector, instanceOf(MetadataStoreSelector.class)); - assertSame(this.keyStrategy, getPropertyValue(messageSelector, "keyStrategy")); - assertSame(this.valueStrategy, getPropertyValue(messageSelector, "valueStrategy")); + assertThat(messageSelector).isInstanceOf(MetadataStoreSelector.class); + assertThat(getPropertyValue(messageSelector, "keyStrategy")).isSameAs(this.keyStrategy); + assertThat(getPropertyValue(messageSelector, "valueStrategy")).isSameAs(this.valueStrategy); @SuppressWarnings("unchecked") Map> idempotentEndpoints = (Map>) getPropertyValue(this.idempotentReceiverAutoProxyCreator, "idempotentEndpoints", Map.class); List endpoints = idempotentEndpoints.get("strategyInterceptor"); - assertNotNull(endpoints); - assertFalse(endpoints.isEmpty()); - assertTrue(endpoints.contains("foo.handler")); + assertThat(endpoints).isNotNull(); + assertThat(endpoints.isEmpty()).isFalse(); + assertThat(endpoints.contains("foo.handler")).isTrue(); } @Test public void testExpressionInterceptor() { Object messageSelector = getPropertyValue(this.expressionInterceptor, "messageSelector"); - assertThat(messageSelector, instanceOf(MetadataStoreSelector.class)); - assertSame(this.store, getPropertyValue(messageSelector, "metadataStore")); + assertThat(messageSelector).isInstanceOf(MetadataStoreSelector.class); + assertThat(getPropertyValue(messageSelector, "metadataStore")).isSameAs(this.store); Object keyStrategy = getPropertyValue(messageSelector, "keyStrategy"); - assertThat(keyStrategy, instanceOf(ExpressionEvaluatingMessageProcessor.class)); - assertThat(keyStrategy.toString(), containsString("headers.foo")); + assertThat(keyStrategy).isInstanceOf(ExpressionEvaluatingMessageProcessor.class); + assertThat(keyStrategy.toString()).contains("headers.foo"); @SuppressWarnings("unchecked") Map> idempotentEndpoints = (Map>) getPropertyValue(this.idempotentReceiverAutoProxyCreator, "idempotentEndpoints", Map.class); List endpoints = idempotentEndpoints.get("expressionInterceptor"); - assertNotNull(endpoints); - assertFalse(endpoints.isEmpty()); - assertTrue(endpoints.contains("foo.handler")); - assertTrue(endpoints.contains("bar*.handler")); + assertThat(endpoints).isNotNull(); + assertThat(endpoints.isEmpty()).isFalse(); + assertThat(endpoints.contains("foo.handler")).isTrue(); + assertThat(endpoints.contains("bar*.handler")).isTrue(); } @Test @@ -153,9 +146,9 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("One of the 'selector', 'key-strategy' or 'key-expression' attributes " + - "must be provided")); + assertThat(e.getMessage()) + .contains("One of the 'selector', 'key-strategy' or 'key-expression' attributes " + + "must be provided"); } } @@ -166,8 +159,7 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("he 'endpoint' attribute is required")); + assertThat(e.getMessage()).contains("he 'endpoint' attribute is required"); } } @@ -178,9 +170,9 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("The 'selector' attribute is mutually exclusive with 'metadata-store', " + - "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'")); + assertThat(e.getMessage()) + .contains("The 'selector' attribute is mutually exclusive with 'metadata-store', " + + "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'"); } } @@ -191,9 +183,9 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("The 'selector' attribute is mutually exclusive with 'metadata-store', " + - "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'")); + assertThat(e.getMessage()) + .contains("The 'selector' attribute is mutually exclusive with 'metadata-store', " + + "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'"); } } @@ -204,9 +196,9 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("The 'selector' attribute is mutually exclusive with 'metadata-store', " + - "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'")); + assertThat(e.getMessage()) + .contains("The 'selector' attribute is mutually exclusive with 'metadata-store', " + + "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'"); } } @@ -217,9 +209,9 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("The 'selector' attribute is mutually exclusive with 'metadata-store', " + - "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'")); + assertThat(e.getMessage()) + .contains("The 'selector' attribute is mutually exclusive with 'metadata-store', " + + "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'"); } } @@ -230,9 +222,9 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("The 'selector' attribute is mutually exclusive with 'metadata-store', " + - "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'")); + assertThat(e.getMessage()) + .contains("The 'selector' attribute is mutually exclusive with 'metadata-store', " + + "'key-strategy', 'key-expression', 'value-strategy' or 'value-expression'"); } } @@ -243,8 +235,8 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("The 'key-strategy' and 'key-expression' attributes are mutually exclusive")); + assertThat(e.getMessage()) + .contains("The 'key-strategy' and 'key-expression' attributes are mutually exclusive"); } } @@ -255,8 +247,8 @@ public class IdempotentReceiverParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeanDefinitionParsingException e) { - assertThat(e.getMessage(), - containsString("The 'value-strategy' and 'value-expression' attributes are mutually exclusive")); + assertThat(e.getMessage()) + .contains("The 'value-strategy' and 'value-expression' attributes are mutually exclusive"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterExpressionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterExpressionTests.java index e551f831af..0561934b7c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterExpressionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; @@ -55,60 +53,64 @@ public class InboundChannelAdapterExpressionTests { public void fixedDelay() { SourcePollingChannelAdapter adapter = this.context.getBean("fixedDelayProducer", SourcePollingChannelAdapter.class); - assertFalse(adapter.isAutoStartup()); + assertThat(adapter.isAutoStartup()).isFalse(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); Trigger trigger = TestUtils.getPropertyValue(adapter, "trigger", Trigger.class); - assertEquals(PeriodicTrigger.class, trigger.getClass()); + assertThat(trigger.getClass()).isEqualTo(PeriodicTrigger.class); DirectFieldAccessor triggerAccessor = new DirectFieldAccessor(trigger); - assertEquals(1234L, triggerAccessor.getPropertyValue("period")); - assertEquals(Boolean.FALSE, triggerAccessor.getPropertyValue("fixedRate")); - assertEquals(this.context.getBean("fixedDelayChannel"), adapterAccessor.getPropertyValue("outputChannel")); + assertThat(triggerAccessor.getPropertyValue("period")).isEqualTo(1234L); + assertThat(triggerAccessor.getPropertyValue("fixedRate")).isEqualTo(Boolean.FALSE); + assertThat(adapterAccessor.getPropertyValue("outputChannel")) + .isEqualTo(this.context.getBean("fixedDelayChannel")); Expression expression = TestUtils.getPropertyValue(adapter, "source.expression", Expression.class); - assertEquals("'fixedDelayTest'", expression.getExpressionString()); + assertThat(expression.getExpressionString()).isEqualTo("'fixedDelayTest'"); } @Test public void fixedRate() { SourcePollingChannelAdapter adapter = this.context.getBean("fixedRateProducer", SourcePollingChannelAdapter.class); - assertFalse(adapter.isAutoStartup()); + assertThat(adapter.isAutoStartup()).isFalse(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); Trigger trigger = TestUtils.getPropertyValue(adapter, "trigger", Trigger.class); - assertEquals(PeriodicTrigger.class, trigger.getClass()); + assertThat(trigger.getClass()).isEqualTo(PeriodicTrigger.class); DirectFieldAccessor triggerAccessor = new DirectFieldAccessor(trigger); - assertEquals(5678L, triggerAccessor.getPropertyValue("period")); - assertEquals(Boolean.TRUE, triggerAccessor.getPropertyValue("fixedRate")); - assertEquals(this.context.getBean("fixedRateChannel"), adapterAccessor.getPropertyValue("outputChannel")); + assertThat(triggerAccessor.getPropertyValue("period")).isEqualTo(5678L); + assertThat(triggerAccessor.getPropertyValue("fixedRate")).isEqualTo(Boolean.TRUE); + assertThat(adapterAccessor.getPropertyValue("outputChannel")) + .isEqualTo(this.context.getBean("fixedRateChannel")); Expression expression = TestUtils.getPropertyValue(adapter, "source.expression", Expression.class); - assertEquals("'fixedRateTest'", expression.getExpressionString()); + assertThat(expression.getExpressionString()).isEqualTo("'fixedRateTest'"); } @Test public void cron() { SourcePollingChannelAdapter adapter = this.context.getBean("cronProducer", SourcePollingChannelAdapter.class); - assertFalse(adapter.isAutoStartup()); + assertThat(adapter.isAutoStartup()).isFalse(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); Trigger trigger = TestUtils.getPropertyValue(adapter, "trigger", Trigger.class); - assertEquals(CronTrigger.class, trigger.getClass()); - assertEquals("7 6 5 4 3 ?", new DirectFieldAccessor(new DirectFieldAccessor( - trigger).getPropertyValue("sequenceGenerator")).getPropertyValue("expression")); - assertEquals(this.context.getBean("cronChannel"), adapterAccessor.getPropertyValue("outputChannel")); + assertThat(trigger.getClass()).isEqualTo(CronTrigger.class); + assertThat(new DirectFieldAccessor(new DirectFieldAccessor( + trigger).getPropertyValue("sequenceGenerator")).getPropertyValue("expression")) + .isEqualTo("7 6 5 4 3 ?"); + assertThat(adapterAccessor.getPropertyValue("outputChannel")).isEqualTo(this.context.getBean("cronChannel")); Expression expression = TestUtils.getPropertyValue(adapter, "source.expression", Expression.class); - assertEquals("'cronTest'", expression.getExpressionString()); + assertThat(expression.getExpressionString()).isEqualTo("'cronTest'"); } @Test public void triggerRef() { SourcePollingChannelAdapter adapter = this.context.getBean("triggerRefProducer", SourcePollingChannelAdapter.class); - assertTrue(adapter.isAutoStartup()); + assertThat(adapter.isAutoStartup()).isTrue(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); Trigger trigger = TestUtils.getPropertyValue(adapter, "trigger", Trigger.class); - assertEquals(this.context.getBean("customTrigger"), trigger); - assertEquals(this.context.getBean("triggerRefChannel"), adapterAccessor.getPropertyValue("outputChannel")); + assertThat(trigger).isEqualTo(this.context.getBean("customTrigger")); + assertThat(adapterAccessor.getPropertyValue("outputChannel")) + .isEqualTo(this.context.getBean("triggerRefChannel")); Expression expression = TestUtils.getPropertyValue(adapter, "source.expression", Expression.class); - assertEquals("'triggerRefTest'", expression.getExpressionString()); + assertThat(expression.getExpressionString()).isEqualTo("'triggerRefTest'"); } @Test @@ -116,14 +118,14 @@ public class InboundChannelAdapterExpressionTests { public void headerExpressions() { SourcePollingChannelAdapter adapter = this.context.getBean("headerExpressionsProducer", SourcePollingChannelAdapter.class); - assertFalse(adapter.isAutoStartup()); + assertThat(adapter.isAutoStartup()).isFalse(); Map headerExpressions = TestUtils.getPropertyValue(adapter, "source.headerExpressions", Map.class); - assertEquals(2, headerExpressions.size()); - assertEquals("6 * 7", headerExpressions.get("foo").getExpressionString()); - assertEquals("x", headerExpressions.get("bar").getExpressionString()); - assertEquals(42, headerExpressions.get("foo").getValue()); - assertEquals("x", headerExpressions.get("bar").getValue()); + assertThat(headerExpressions.size()).isEqualTo(2); + assertThat(headerExpressions.get("foo").getExpressionString()).isEqualTo("6 * 7"); + assertThat(headerExpressions.get("bar").getExpressionString()).isEqualTo("x"); + assertThat(headerExpressions.get("foo").getValue()).isEqualTo(42); + assertThat(headerExpressions.get("bar").getValue()).isEqualTo("x"); } @Test @@ -131,7 +133,7 @@ public class InboundChannelAdapterExpressionTests { SourcePollingChannelAdapter adapter = this.context.getBean("expressionElement", SourcePollingChannelAdapter.class); Expression expression = TestUtils.getPropertyValue(adapter, "source.expression", Expression.class); - assertEquals("'Hello World!'", expression.getExpressionString()); + assertThat(expression.getExpressionString()).isEqualTo("'Hello World!'"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterWithDefaultPollerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterWithDefaultPollerTests.java index 40ed69f42f..f87de1d08e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterWithDefaultPollerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InboundChannelAdapterWithDefaultPollerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -44,10 +44,10 @@ public class InboundChannelAdapterWithDefaultPollerTests { @Test public void verifyDefaultPollerInUse() { Trigger trigger = TestUtils.getPropertyValue(adapter, "trigger", Trigger.class); - assertEquals(PeriodicTrigger.class, trigger.getClass()); + assertThat(trigger.getClass()).isEqualTo(PeriodicTrigger.class); DirectFieldAccessor triggerAccessor = new DirectFieldAccessor(trigger); - assertEquals(12345L, triggerAccessor.getPropertyValue("period")); - assertEquals(Boolean.TRUE, triggerAccessor.getPropertyValue("fixedRate")); + assertThat(triggerAccessor.getPropertyValue("period")).isEqualTo(12345L); + assertThat(triggerAccessor.getPropertyValue("fixedRate")).isEqualTo(Boolean.TRUE); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerBeanConfigTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerBeanConfigTests.java index 0e4c925cc1..b8854fe18c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerBeanConfigTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerBeanConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -47,7 +47,7 @@ public class InnerBeanConfigTests { @Test(expected = NoSuchBeanDefinitionException.class) public void checkInnerBean() { Object innerBean = TestUtils.getPropertyValue(testEndpoint, "handler.processor.delegate.targetObject"); - assertNotNull(innerBean); + assertThat(innerBean).isNotNull(); context.getBean(TestBean.class); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerDefinitionHandlerAwareEndpointParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerDefinitionHandlerAwareEndpointParserTests.java index e211cb3959..709efa3e1c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerDefinitionHandlerAwareEndpointParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/InnerDefinitionHandlerAwareEndpointParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.util.Collection; @@ -26,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -196,57 +194,57 @@ public class InnerDefinitionHandlerAwareEndpointParserTests { private void testSplitterDefinitionSuccess(String configProperty) { ApplicationContext ac = this.bootStrap(configProperty); EventDrivenConsumer splitter = (EventDrivenConsumer) ac.getBean("testSplitter"); - Assert.assertNotNull(splitter); + assertThat(splitter).isNotNull(); MessageBuilder inChannelMessageBuilder = MessageBuilder.withPayload(new String[]{"One", "Two"}); Message inMessage = inChannelMessageBuilder.build(); MessageChannel inChannel = (MessageChannel) ac.getBean("inChannel"); inChannel.send(inMessage); PollableChannel outChannel = (PollableChannel) ac.getBean("outChannel"); - Assert.assertTrue(outChannel.receive().getPayload() instanceof String); + assertThat(outChannel.receive().getPayload() instanceof String).isTrue(); outChannel = (PollableChannel) ac.getBean("outChannel"); - Assert.assertTrue(outChannel.receive().getPayload() instanceof String); + assertThat(outChannel.receive().getPayload() instanceof String).isTrue(); } private void testTransformerDefinitionSuccess(String configProperty) { ApplicationContext ac = this.bootStrap(configProperty); EventDrivenConsumer transformer = (EventDrivenConsumer) ac.getBean("testTransformer"); - Assert.assertNotNull(transformer); + assertThat(transformer).isNotNull(); MessageBuilder inChannelMessageBuilder = MessageBuilder.withPayload(new String[]{"One", "Two"}); Message inMessage = inChannelMessageBuilder.build(); DirectChannel inChannel = (DirectChannel) ac.getBean("inChannel"); inChannel.send(inMessage); PollableChannel outChannel = (PollableChannel) ac.getBean("outChannel"); String payload = (String) outChannel.receive().getPayload(); - Assert.assertTrue(payload.equals("One,Two")); + assertThat(payload.equals("One,Two")).isTrue(); } private void testRouterDefinitionSuccess(String configProperty) { ApplicationContext ac = this.bootStrap(configProperty); EventDrivenConsumer splitter = (EventDrivenConsumer) ac.getBean("testRouter"); - Assert.assertNotNull(splitter); + assertThat(splitter).isNotNull(); MessageBuilder inChannelMessageBuilder = MessageBuilder.withPayload("1"); Message inMessage = inChannelMessageBuilder.build(); DirectChannel inChannel = (DirectChannel) ac.getBean("inChannel"); inChannel.send(inMessage); PollableChannel channel1 = (PollableChannel) ac.getBean("channel1"); - Assert.assertTrue(channel1.receive().getPayload().equals("1")); + assertThat(channel1.receive().getPayload().equals("1")).isTrue(); inChannelMessageBuilder = MessageBuilder.withPayload("2"); inMessage = inChannelMessageBuilder.build(); inChannel.send(inMessage); PollableChannel channel2 = (PollableChannel) ac.getBean("channel2"); - Assert.assertTrue(channel2.receive().getPayload().equals("2")); + assertThat(channel2.receive().getPayload().equals("2")).isTrue(); } private void testSADefinitionSuccess(String configProperty) { ApplicationContext ac = this.bootStrap(configProperty); EventDrivenConsumer splitter = (EventDrivenConsumer) ac.getBean("testServiceActivator"); - Assert.assertNotNull(splitter); + assertThat(splitter).isNotNull(); MessageBuilder inChannelMessageBuilder = MessageBuilder.withPayload("1"); Message inMessage = inChannelMessageBuilder.build(); DirectChannel inChannel = (DirectChannel) ac.getBean("inChannel"); inChannel.send(inMessage); PollableChannel channel1 = (PollableChannel) ac.getBean("outChannel"); - Assert.assertTrue(channel1.receive().getPayload().equals("1")); + assertThat(channel1.receive().getPayload().equals("1")).isTrue(); } private void testAggregatorDefinitionSuccess(String configProperty) { @@ -259,8 +257,8 @@ public class InnerDefinitionHandlerAwareEndpointParserTests { } PollableChannel output = (PollableChannel) ac.getBean("outChannel"); Message receivedMessage = output.receive(10000); - assertNotNull(receivedMessage); - assertEquals(0 + 1 + 2 + 3 + 4, receivedMessage.getPayload()); + assertThat(receivedMessage).isNotNull(); + assertThat(receivedMessage.getPayload()).isEqualTo(0 + 1 + 2 + 3 + 4); } private void testFilterDefinitionSuccess(String configProperty) { @@ -269,7 +267,7 @@ public class InnerDefinitionHandlerAwareEndpointParserTests { PollableChannel output = (PollableChannel) ac.getBean("outChannel"); input.send(new GenericMessage("foo")); Message reply = output.receive(0); - assertEquals("foo", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("foo"); } private ApplicationContext bootStrap(String configProperty) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java index 8b2eda98af..ff73844df0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -43,28 +43,28 @@ public class IntervalTriggerParserTests { @Test public void testFixedRateTrigger() { Object poller = context.getBean("pollerWithFixedRateAttribute"); - assertEquals(PollerMetadata.class, poller.getClass()); + assertThat(poller.getClass()).isEqualTo(PollerMetadata.class); PollerMetadata metadata = (PollerMetadata) poller; Trigger trigger = metadata.getTrigger(); - assertEquals(PeriodicTrigger.class, trigger.getClass()); + assertThat(trigger.getClass()).isEqualTo(PeriodicTrigger.class); DirectFieldAccessor accessor = new DirectFieldAccessor(trigger); Boolean fixedRate = (Boolean) accessor.getPropertyValue("fixedRate"); Long period = (Long) accessor.getPropertyValue("period"); - assertEquals(fixedRate, true); - assertEquals(36L, period.longValue()); + assertThat(true).isEqualTo(fixedRate); + assertThat(period.longValue()).isEqualTo(36L); } @Test public void testFixedDelayTrigger() { Object poller = context.getBean("pollerWithFixedDelayAttribute"); - assertEquals(PollerMetadata.class, poller.getClass()); + assertThat(poller.getClass()).isEqualTo(PollerMetadata.class); PollerMetadata metadata = (PollerMetadata) poller; Trigger trigger = metadata.getTrigger(); - assertEquals(PeriodicTrigger.class, trigger.getClass()); + assertThat(trigger.getClass()).isEqualTo(PeriodicTrigger.class); DirectFieldAccessor accessor = new DirectFieldAccessor(trigger); Boolean fixedRate = (Boolean) accessor.getPropertyValue("fixedRate"); Long period = (Long) accessor.getPropertyValue("period"); - assertEquals(fixedRate, false); - assertEquals(37L, period.longValue()); + assertThat(false).isEqualTo(fixedRate); + assertThat(period.longValue()).isEqualTo(37L); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/LoggingChannelAdapterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/LoggingChannelAdapterParserTests.java index 4968db6acd..2cbc9ed8ff 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/LoggingChannelAdapterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/LoggingChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,8 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,22 +55,22 @@ public class LoggingChannelAdapterParserTests { @Test public void verifyConfig() { LoggingHandler loggingHandler = TestUtils.getPropertyValue(loggerConsumer, "handler", LoggingHandler.class); - assertEquals("org.springframework.integration.test.logger", - TestUtils.getPropertyValue(loggingHandler, "messageLogger.logger.name")); - assertEquals(1, TestUtils.getPropertyValue(loggingHandler, "order")); - assertEquals("WARN", TestUtils.getPropertyValue(loggingHandler, "level").toString()); - assertEquals("#root", TestUtils.getPropertyValue(loggingHandler, "expression.expression")); + assertThat(TestUtils.getPropertyValue(loggingHandler, "messageLogger.logger.name")) + .isEqualTo("org.springframework.integration.test.logger"); + assertThat(TestUtils.getPropertyValue(loggingHandler, "order")).isEqualTo(1); + assertThat(TestUtils.getPropertyValue(loggingHandler, "level").toString()).isEqualTo("WARN"); + assertThat(TestUtils.getPropertyValue(loggingHandler, "expression.expression")).isEqualTo("#root"); } @Test public void verifyExpressionAndOtherDefaultConfig() { LoggingHandler loggingHandler = TestUtils.getPropertyValue(loggerWithExpression, "handler", LoggingHandler.class); - assertEquals("org.springframework.integration.handler.LoggingHandler", - TestUtils.getPropertyValue(loggingHandler, "messageLogger.logger.name")); - assertEquals(Ordered.LOWEST_PRECEDENCE, TestUtils.getPropertyValue(loggingHandler, "order")); - assertEquals("INFO", TestUtils.getPropertyValue(loggingHandler, "level").toString()); - assertEquals("payload.foo", TestUtils.getPropertyValue(loggingHandler, "expression.expression")); - assertNotNull(TestUtils.getPropertyValue(loggingHandler, "evaluationContext.beanResolver")); + assertThat(TestUtils.getPropertyValue(loggingHandler, "messageLogger.logger.name")) + .isEqualTo("org.springframework.integration.handler.LoggingHandler"); + assertThat(TestUtils.getPropertyValue(loggingHandler, "order")).isEqualTo(Ordered.LOWEST_PRECEDENCE); + assertThat(TestUtils.getPropertyValue(loggingHandler, "level").toString()).isEqualTo("INFO"); + assertThat(TestUtils.getPropertyValue(loggingHandler, "expression.expression")).isEqualTo("payload.foo"); + assertThat(TestUtils.getPropertyValue(loggingHandler, "evaluationContext.beanResolver")).isNotNull(); } @Test @@ -83,8 +81,9 @@ public class LoggingChannelAdapterParserTests { fail("BeanDefinitionParsingException expected"); } catch (BeansException e) { - assertTrue(e instanceof BeanDefinitionParsingException); - assertTrue(e.getMessage().contains("The 'expression' and 'log-full-message' attributes are mutually exclusive.")); + assertThat(e instanceof BeanDefinitionParsingException).isTrue(); + assertThat(e.getMessage() + .contains("The 'expression' and 'log-full-message' attributes are mutually exclusive.")).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MapToObjectTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MapToObjectTransformerParserTests.java index 6681c3cadd..b615efa080 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MapToObjectTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MapToObjectTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; @@ -76,12 +74,12 @@ public class MapToObjectTransformerParserTests { Message outMessage = output.receive(); Person person = (Person) outMessage.getPayload(); - assertNotNull(person); - assertEquals("Justin", person.getFname()); - assertEquals("Case", person.getLname()); - assertNull(person.getSsn()); - assertNotNull(person.getAddress()); - assertEquals("1123 Main st", person.getAddress().getStreet()); + assertThat(person).isNotNull(); + assertThat(person.getFname()).isEqualTo("Justin"); + assertThat(person.getLname()).isEqualTo("Case"); + assertThat(person.getSsn()).isNull(); + assertThat(person.getAddress()).isNotNull(); + assertThat(person.getAddress().getStreet()).isEqualTo("1123 Main st"); } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -98,12 +96,12 @@ public class MapToObjectTransformerParserTests { inputA.send(message); Message newMessage = outputA.receive(); Person person = (Person) newMessage.getPayload(); - assertNotNull(person); - assertEquals("Justin", person.getFname()); - assertEquals("Case", person.getLname()); - assertNull(person.getSsn()); - assertNotNull(person.getAddress()); - assertEquals("1123 Main st", person.getAddress().getStreet()); + assertThat(person).isNotNull(); + assertThat(person.getFname()).isEqualTo("Justin"); + assertThat(person.getLname()).isEqualTo("Case"); + assertThat(person.getSsn()).isNull(); + assertThat(person.getAddress()).isNotNull(); + assertThat(person.getAddress().getStreet()).isEqualTo("1123 Main st"); } @@ -120,11 +118,11 @@ public class MapToObjectTransformerParserTests { Message newMessage = outputA.receive(); Person person = (Person) newMessage.getPayload(); - assertNotNull(person); - assertEquals("Justin", person.getFname()); - assertEquals("Case", person.getLname()); - assertNotNull(person.getAddress()); - assertEquals("1123 Main st", person.getAddress().getStreet()); + assertThat(person).isNotNull(); + assertThat(person.getFname()).isEqualTo("Justin"); + assertThat(person.getLname()).isEqualTo("Case"); + assertThat(person.getAddress()).isNotNull(); + assertThat(person.getAddress().getStreet()).isEqualTo("1123 Main st"); } @Test(expected = BeanCreationException.class) public void testNonPrototypeFailure() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MethodInvokingSelectorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MethodInvokingSelectorParserTests.java index eb3263208a..2d017a3bcd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MethodInvokingSelectorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/MethodInvokingSelectorParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -51,7 +50,7 @@ public class MethodInvokingSelectorParserTests { public void configOK() { DirectFieldAccessor accessor = new DirectFieldAccessor(chain); List selectors = (List) accessor.getPropertyValue("selectors"); - assertThat(selectors.get(0), instanceOf(MethodInvokingSelector.class)); + assertThat(selectors.get(0)).isInstanceOf(MethodInvokingSelector.class); } public static class TestFilter { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/NestedChainParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/NestedChainParserTests.java index d1dabf21b4..8bbb2c8346 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/NestedChainParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/NestedChainParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertNotSame; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -48,8 +48,8 @@ public class NestedChainParserTests { public void chainsAreNotSame() { ParentTestBean bean1 = context.getBean("concreteParent1", ParentTestBean.class); ParentTestBean bean2 = context.getBean("concreteParent2", ParentTestBean.class); - assertNotSame(bean1, bean2); - assertNotSame(bean1.chain, bean2.chain); + assertThat(bean2).isNotSameAs(bean1); + assertThat(bean2.chain).isNotSameAs(bean1.chain); } @Test @@ -63,7 +63,7 @@ public class NestedChainParserTests { (List) new DirectFieldAccessor(bean2.chain).getPropertyValue("handlers"); MessageHandler handler1 = handlerList1.get(0); MessageHandler handler2 = handlerList2.get(0); - assertNotSame(handler1, handler2); + assertThat(handler2).isNotSameAs(handler1); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java index 20bf2942ef..b0451e30e5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,13 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -83,12 +80,12 @@ public class ObjectToMapTransformerParserTests { Message> outputMessage = (Message>) output.receive(); Map transformedMap = outputMessage.getPayload(); - assertNotNull(outputMessage.getPayload()); + assertThat(outputMessage.getPayload()).isNotNull(); for (String key : transformedMap.keySet()) { Expression expression = parser.parseExpression(key); Object valueFromTheMap = transformedMap.get(key); Object valueFromExpression = expression.getValue(context); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); } } @@ -113,11 +110,11 @@ public class ObjectToMapTransformerParserTests { @SuppressWarnings("unchecked") Message> outputMessage = (Message>) nestedOutput.receive(1000); Map transformedMap = outputMessage.getPayload(); - assertNotNull(outputMessage.getPayload()); + assertThat(outputMessage.getPayload()).isNotNull(); - assertEquals(employee.getCompanyName(), transformedMap.get("companyName")); - assertThat(transformedMap.get("companyAddress"), Matchers.instanceOf(Map.class)); - assertThat(transformedMap.get("departments"), Matchers.instanceOf(List.class)); + assertThat(transformedMap.get("companyName")).isEqualTo(employee.getCompanyName()); + assertThat(transformedMap.get("companyAddress")).isInstanceOf(Map.class); + assertThat(transformedMap.get("departments")).isInstanceOf(List.class); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java index 4dd90dc5fb..b6d2ac23fe 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -62,37 +61,37 @@ public class ObjectToStringTransformerParserTests { public void directChannelWithStringMessage() { directInput.send(new GenericMessage("foo")); Message result = output.receive(0); - assertNotNull(result); - assertEquals("foo", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("foo"); } @Test public void queueChannelWithStringMessage() { queueInput.send(new GenericMessage("foo")); Message result = output.receive(3000); - assertNotNull(result); - assertEquals("foo", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("foo"); } @Test public void directChannelWithObjectMessage() { directInput.send(new GenericMessage(new TestBean())); Message result = output.receive(0); - assertNotNull(result); - assertEquals("test", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); } @Test public void queueChannelWithObjectMessage() { queueInput.send(new GenericMessage(new TestBean())); Message result = output.receive(3000); - assertNotNull(result); - assertEquals("test", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test"); } @Test public void charset() { - assertEquals("FOO", TestUtils.getPropertyValue(this.withCharset, "handler.transformer.charset")); + assertThat(TestUtils.getPropertyValue(this.withCharset, "handler.transformer.charset")).isEqualTo("FOO"); } private static class TestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/OrderedHandlersTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/OrderedHandlersTests.java index 3bc5880f3c..84bd591b5c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/OrderedHandlersTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/OrderedHandlersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -46,8 +45,8 @@ public class OrderedHandlersTests { for (int i = 1; i < 14; i++) { Object consumer = context.getBean("endpoint" + i); Object handler = new DirectFieldAccessor(consumer).getPropertyValue("handler"); - assertTrue(handler instanceof Ordered); - assertEquals(i, ((Ordered) handler).getOrder()); + assertThat(handler instanceof Ordered).isTrue(); + assertThat(((Ordered) handler).getOrder()).isEqualTo(i); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PNamespaceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PNamespaceTests.java index bea917a44e..74e7f09fb9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PNamespaceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PNamespaceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -65,29 +65,29 @@ public class PNamespaceTests { @Test public void testPNamespaceServiceActivator() { TestBean bean = prepare(serviceActivator); - assertEquals("paris", bean.getFname()); - assertEquals("hilton", bean.getLname()); + assertThat(bean.getFname()).isEqualTo("paris"); + assertThat(bean.getLname()).isEqualTo("hilton"); } @Test public void testPNamespaceSplitter() { TestBean bean = prepare(splitter); - assertEquals("paris", bean.getFname()); - assertEquals("hilton", bean.getLname()); + assertThat(bean.getFname()).isEqualTo("paris"); + assertThat(bean.getLname()).isEqualTo("hilton"); } @Test public void testPNamespaceRouter() { TestBean bean = prepare(router); - assertEquals("paris", bean.getFname()); - assertEquals("hilton", bean.getLname()); + assertThat(bean.getFname()).isEqualTo("paris"); + assertThat(bean.getLname()).isEqualTo("hilton"); } @Test public void testPNamespaceTransformer() { TestBean bean = prepare(transformer); - assertEquals("paris", bean.getFname()); - assertEquals("hilton", bean.getLname()); + assertThat(bean.getFname()).isEqualTo("paris"); + assertThat(bean.getLname()).isEqualTo("hilton"); } @Test @@ -97,7 +97,7 @@ public class PNamespaceTests { SampleAggregator aggregator = (SampleAggregator) TestUtils .getPropertyValue(handler, "outputProcessor.processor.delegate.targetObject"); - assertEquals("Bill", aggregator.getName()); + assertThat(aggregator.getName()).isEqualTo("Bill"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java index 79ac812b96..2c31ecb5af 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.config.xml; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -76,13 +72,13 @@ public class PayloadDeserializingTransformerParserTests { byte[] bytes = serialize("foo"); directInput.send(new GenericMessage(bytes)); Message result = output.receive(10000); - assertNotNull(result); - assertTrue(result.getPayload() instanceof String); - assertEquals("foo", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload() instanceof String).isTrue(); + assertThat(result.getPayload()).isEqualTo("foo"); Set patterns = TestUtils.getPropertyValue(this.handler, "transformer.converter.whiteListPatterns", Set.class); - assertThat(patterns.size(), equalTo(1)); - assertThat(patterns.iterator().next(), equalTo("*")); + assertThat(patterns.size()).isEqualTo(1); + assertThat(patterns.iterator().next()).isEqualTo("*"); } @Test @@ -90,9 +86,9 @@ public class PayloadDeserializingTransformerParserTests { byte[] bytes = serialize("foo"); queueInput.send(new GenericMessage(bytes)); Message result = output.receive(10000); - assertNotNull(result); - assertTrue(result.getPayload() instanceof String); - assertEquals("foo", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload() instanceof String).isTrue(); + assertThat(result.getPayload()).isEqualTo("foo"); } @Test @@ -100,9 +96,9 @@ public class PayloadDeserializingTransformerParserTests { byte[] bytes = serialize(new TestBean()); directInput.send(new GenericMessage(bytes)); Message result = output.receive(10000); - assertNotNull(result); - assertEquals(TestBean.class, result.getPayload().getClass()); - assertEquals("test", ((TestBean) result.getPayload()).name); + assertThat(result).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) result.getPayload()).name).isEqualTo("test"); } @Test @@ -110,9 +106,9 @@ public class PayloadDeserializingTransformerParserTests { byte[] bytes = serialize(new TestBean()); queueInput.send(new GenericMessage(bytes)); Message result = output.receive(10000); - assertNotNull(result); - assertEquals(TestBean.class, result.getPayload().getClass()); - assertEquals("test", ((TestBean) result.getPayload()).name); + assertThat(result).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) result.getPayload()).name).isEqualTo("test"); } @Test(expected = MessageTransformationException.class) @@ -125,9 +121,9 @@ public class PayloadDeserializingTransformerParserTests { public void customDeserializer() throws Exception { customDeserializerInput.send(new GenericMessage("test".getBytes("UTF-8"))); Message result = output.receive(10000); - assertNotNull(result); - assertEquals(String.class, result.getPayload().getClass()); - assertEquals("TEST", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(String.class); + assertThat(result.getPayload()).isEqualTo("TEST"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java index 3cc63e800c..5c8d346e81 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -66,39 +64,39 @@ public class PayloadSerializingTransformerParserTests { public void directChannelWithStringMessage() throws Exception { directInput.send(new GenericMessage("foo")); Message result = output.receive(0); - assertNotNull(result); - assertTrue(result.getPayload() instanceof byte[]); - assertEquals("foo", deserialize((byte[]) result.getPayload())); + assertThat(result).isNotNull(); + assertThat(result.getPayload() instanceof byte[]).isTrue(); + assertThat(deserialize((byte[]) result.getPayload())).isEqualTo("foo"); } @Test public void queueChannelWithStringMessage() throws Exception { queueInput.send(new GenericMessage("foo")); Message result = output.receive(10000); - assertNotNull(result); - assertTrue(result.getPayload() instanceof byte[]); - assertEquals("foo", deserialize((byte[]) result.getPayload())); + assertThat(result).isNotNull(); + assertThat(result.getPayload() instanceof byte[]).isTrue(); + assertThat(deserialize((byte[]) result.getPayload())).isEqualTo("foo"); } @Test public void directChannelWithObjectMessage() throws Exception { directInput.send(new GenericMessage(new TestBean())); Message result = output.receive(0); - assertNotNull(result); - assertTrue(result.getPayload() instanceof byte[]); + assertThat(result).isNotNull(); + assertThat(result.getPayload() instanceof byte[]).isTrue(); Object deserialized = deserialize((byte[]) result.getPayload()); - assertEquals(TestBean.class, deserialized.getClass()); - assertEquals("test", ((TestBean) deserialized).name); + assertThat(deserialized.getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) deserialized).name).isEqualTo("test"); } @Test public void queueChannelWithObjectMessage() throws Exception { queueInput.send(new GenericMessage(new TestBean())); Message result = output.receive(10000); - assertTrue(result.getPayload() instanceof byte[]); + assertThat(result.getPayload() instanceof byte[]).isTrue(); Object deserialized = deserialize((byte[]) result.getPayload()); - assertEquals(TestBean.class, deserialized.getClass()); - assertEquals("test", ((TestBean) deserialized).name); + assertThat(deserialized.getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) deserialized).name).isEqualTo("test"); } @Test(expected = MessageTransformationException.class) @@ -110,9 +108,9 @@ public class PayloadSerializingTransformerParserTests { public void customSerializer() throws Exception { customSerializerInput.send(new GenericMessage("test")); Message result = output.receive(10000); - assertNotNull(result); - assertEquals(byte[].class, result.getPayload().getClass()); - assertEquals("TEST", new String((byte[]) result.getPayload(), "UTF-8")); + assertThat(result).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(byte[].class); + assertThat(new String((byte[]) result.getPayload(), "UTF-8")).isEqualTo("TEST"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java index deef30622d..41a59678a8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.concurrent.TimeUnit; @@ -49,10 +46,10 @@ public class PollerParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "defaultPollerWithId.xml", PollerParserTests.class); Object poller = context.getBean("defaultPollerWithId"); - assertNotNull(poller); + assertThat(poller).isNotNull(); Object defaultPoller = context.getBean(PollerMetadata.DEFAULT_POLLER_METADATA_BEAN_NAME); - assertNotNull(defaultPoller); - assertEquals(defaultPoller, context.getBean("defaultPollerWithId")); + assertThat(defaultPoller).isNotNull(); + assertThat(context.getBean("defaultPollerWithId")).isEqualTo(defaultPoller); context.close(); } @@ -61,7 +58,7 @@ public class PollerParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "defaultPollerWithoutId.xml", PollerParserTests.class); Object defaultPoller = context.getBean(PollerMetadata.DEFAULT_POLLER_METADATA_BEAN_NAME); - assertNotNull(defaultPoller); + assertThat(defaultPoller).isNotNull(); context.close(); } @@ -82,22 +79,22 @@ public class PollerParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "pollerWithAdviceChain.xml", PollerParserTests.class); Object poller = context.getBean("poller"); - assertNotNull(poller); + assertThat(poller).isNotNull(); PollerMetadata metadata = (PollerMetadata) poller; - assertNotNull(metadata.getAdviceChain()); - assertEquals(4, metadata.getAdviceChain().size()); - assertSame(context.getBean("adviceBean1"), metadata.getAdviceChain().get(0)); - assertEquals(TestAdviceBean.class, metadata.getAdviceChain().get(1).getClass()); - assertEquals(2, ((TestAdviceBean) metadata.getAdviceChain().get(1)).getId()); - assertSame(context.getBean("adviceBean3"), metadata.getAdviceChain().get(2)); + assertThat(metadata.getAdviceChain()).isNotNull(); + assertThat(metadata.getAdviceChain().size()).isEqualTo(4); + assertThat(metadata.getAdviceChain().get(0)).isSameAs(context.getBean("adviceBean1")); + assertThat(metadata.getAdviceChain().get(1).getClass()).isEqualTo(TestAdviceBean.class); + assertThat(((TestAdviceBean) metadata.getAdviceChain().get(1)).getId()).isEqualTo(2); + assertThat(metadata.getAdviceChain().get(2)).isSameAs(context.getBean("adviceBean3")); Advice txAdvice = metadata.getAdviceChain().get(3); - assertEquals(TransactionInterceptor.class, txAdvice.getClass()); + assertThat(txAdvice.getClass()).isEqualTo(TransactionInterceptor.class); TransactionAttributeSource transactionAttributeSource = ((TransactionInterceptor) txAdvice).getTransactionAttributeSource(); - assertEquals(NameMatchTransactionAttributeSource.class, transactionAttributeSource.getClass()); + assertThat(transactionAttributeSource.getClass()).isEqualTo(NameMatchTransactionAttributeSource.class); @SuppressWarnings("rawtypes") HashMap nameMap = TestUtils.getPropertyValue(transactionAttributeSource, "nameMap", HashMap.class); - assertEquals(1, nameMap.size()); - assertEquals("{*=PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT,readOnly}", nameMap.toString()); + assertThat(nameMap.size()).isEqualTo(1); + assertThat(nameMap.toString()).isEqualTo("{*=PROPAGATION_REQUIRES_NEW,ISOLATION_DEFAULT,readOnly}"); context.close(); } @@ -107,11 +104,11 @@ public class PollerParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "pollerWithReceiveTimeout.xml", PollerParserTests.class); Object poller = context.getBean("poller"); - assertNotNull(poller); + assertThat(poller).isNotNull(); PollerMetadata metadata = (PollerMetadata) poller; - assertEquals(1234, metadata.getReceiveTimeout()); + assertThat(metadata.getReceiveTimeout()).isEqualTo(1234); PeriodicTrigger trigger = (PeriodicTrigger) metadata.getTrigger(); - assertEquals(TimeUnit.SECONDS.toString(), TestUtils.getPropertyValue(trigger, "timeUnit").toString()); + assertThat(TestUtils.getPropertyValue(trigger, "timeUnit").toString()).isEqualTo(TimeUnit.SECONDS.toString()); context.close(); } @@ -120,9 +117,9 @@ public class PollerParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "pollerWithTriggerReference.xml", PollerParserTests.class); Object poller = context.getBean("poller"); - assertNotNull(poller); + assertThat(poller).isNotNull(); PollerMetadata metadata = (PollerMetadata) poller; - assertTrue(metadata.getTrigger() instanceof TestTrigger); + assertThat(metadata.getTrigger() instanceof TestTrigger).isTrue(); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerWithErrorChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerWithErrorChannelTests.java index c501f4342c..e283188a8a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerWithErrorChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerWithErrorChannelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.mock; @@ -70,7 +69,7 @@ public class PollerWithErrorChannelTests { errorChannel.subscribe(handler); adapter.start(); - assertTrue(handleLatch.await(10, TimeUnit.SECONDS)); + assertThat(handleLatch.await(10, TimeUnit.SECONDS)).isTrue(); adapter.stop(); ac.close(); @@ -83,7 +82,7 @@ public class PollerWithErrorChannelTests { SourcePollingChannelAdapter adapter = ac.getBean("withErrorChannel", SourcePollingChannelAdapter.class); adapter.start(); PollableChannel errorChannel = ac.getBean("eChannel", PollableChannel.class); - assertNotNull(errorChannel.receive(10000)); + assertThat(errorChannel.receive(10000)).isNotNull(); adapter.stop(); ac.close(); } @@ -96,7 +95,7 @@ public class PollerWithErrorChannelTests { SourcePollingChannelAdapter.class); adapter.start(); PollableChannel errorChannel = ac.getBean("eChannel", PollableChannel.class); - assertNotNull(errorChannel.receive(10000)); + assertThat(errorChannel.receive(10000)).isNotNull(); adapter.stop(); ac.close(); } @@ -110,7 +109,7 @@ public class PollerWithErrorChannelTests { SourcePollingChannelAdapter.class); adapter.start(); PollableChannel errorChannel = ac.getBean("errChannel", PollableChannel.class); - assertNotNull(errorChannel.receive(10000)); + assertThat(errorChannel.receive(10000)).isNotNull(); adapter.stop(); ac.close(); } @@ -123,7 +122,7 @@ public class PollerWithErrorChannelTests { MessageChannel serviceWithPollerChannel = ac.getBean("serviceWithPollerChannel", MessageChannel.class); QueueChannel errorChannel = ac.getBean("serviceErrorChannel", QueueChannel.class); serviceWithPollerChannel.send(new GenericMessage<>("")); - assertNotNull(errorChannel.receive(10000)); + assertThat(errorChannel.receive(10000)).isNotNull(); ac.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java index 07e9467ea8..21d05da1cc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.times; @@ -62,7 +62,7 @@ public class PublishingInterceptorParserTests { defaultChannel.subscribe(handler); doAnswer(invocation -> { Message message = invocation.getArgument(0); - assertEquals("hello", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello"); return null; }).when(handler).handleMessage(any(Message.class)); testBean.echoDefaultChannel("hello"); @@ -75,8 +75,8 @@ public class PublishingInterceptorParserTests { echoChannel.subscribe(handler); doAnswer(invocation -> { Message message = invocation.getArgument(0); - assertEquals("bar", message.getHeaders().get("foo")); - assertEquals("Echoing: hello", message.getPayload()); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(message.getPayload()).isEqualTo("Echoing: hello"); return null; }).when(handler).handleMessage(any(Message.class)); testBean.echo("hello"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/RetryAdviceParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/RetryAdviceParserTests.java index 34432fa293..caa3d26564 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/RetryAdviceParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/RetryAdviceParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,10 +16,7 @@ package org.springframework.integration.config.xml; -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.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -81,36 +78,36 @@ public class RetryAdviceParserTests { @Test public void testAll() { - assertEquals(3, TestUtils.getPropertyValue(a1, "retryTemplate.retryPolicy.maxAttempts")); - assertEquals(4, TestUtils.getPropertyValue(a2, "retryTemplate.retryPolicy.maxAttempts")); - assertEquals(5, TestUtils.getPropertyValue(a3, "retryTemplate.retryPolicy.maxAttempts")); - assertEquals(6, TestUtils.getPropertyValue(a4, "retryTemplate.retryPolicy.maxAttempts")); - assertEquals(7, TestUtils.getPropertyValue(a5, "retryTemplate.retryPolicy.maxAttempts")); - assertEquals(8, TestUtils.getPropertyValue(a6, "retryTemplate.retryPolicy.maxAttempts")); - assertEquals(3, TestUtils.getPropertyValue(a7, "retryTemplate.retryPolicy.maxAttempts")); + assertThat(TestUtils.getPropertyValue(a1, "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(3); + assertThat(TestUtils.getPropertyValue(a2, "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(4); + assertThat(TestUtils.getPropertyValue(a3, "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(5); + assertThat(TestUtils.getPropertyValue(a4, "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(6); + assertThat(TestUtils.getPropertyValue(a5, "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(7); + assertThat(TestUtils.getPropertyValue(a6, "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(8); + assertThat(TestUtils.getPropertyValue(a7, "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(3); - assertEquals(1000L, TestUtils.getPropertyValue(a3, "retryTemplate.backOffPolicy.backOffPeriod")); - assertEquals(1234L, TestUtils.getPropertyValue(a4, "retryTemplate.backOffPolicy.backOffPeriod")); + assertThat(TestUtils.getPropertyValue(a3, "retryTemplate.backOffPolicy.backOffPeriod")).isEqualTo(1000L); + assertThat(TestUtils.getPropertyValue(a4, "retryTemplate.backOffPolicy.backOffPeriod")).isEqualTo(1234L); - assertEquals(100L, TestUtils.getPropertyValue(a5, "retryTemplate.backOffPolicy.initialInterval")); - assertEquals(2.0, TestUtils.getPropertyValue(a5, "retryTemplate.backOffPolicy.multiplier")); - assertEquals(30000L, TestUtils.getPropertyValue(a5, "retryTemplate.backOffPolicy.maxInterval")); - assertEquals(1000L, TestUtils.getPropertyValue(a6, "retryTemplate.backOffPolicy.initialInterval")); - assertEquals(3.0, TestUtils.getPropertyValue(a6, "retryTemplate.backOffPolicy.multiplier")); - assertEquals(10000L, TestUtils.getPropertyValue(a6, "retryTemplate.backOffPolicy.maxInterval")); + assertThat(TestUtils.getPropertyValue(a5, "retryTemplate.backOffPolicy.initialInterval")).isEqualTo(100L); + assertThat(TestUtils.getPropertyValue(a5, "retryTemplate.backOffPolicy.multiplier")).isEqualTo(2.0); + assertThat(TestUtils.getPropertyValue(a5, "retryTemplate.backOffPolicy.maxInterval")).isEqualTo(30000L); + assertThat(TestUtils.getPropertyValue(a6, "retryTemplate.backOffPolicy.initialInterval")).isEqualTo(1000L); + assertThat(TestUtils.getPropertyValue(a6, "retryTemplate.backOffPolicy.multiplier")).isEqualTo(3.0); + assertThat(TestUtils.getPropertyValue(a6, "retryTemplate.backOffPolicy.maxInterval")).isEqualTo(10000L); - assertNull(TestUtils.getPropertyValue(a1, "recoveryCallback")); - assertNotNull(TestUtils.getPropertyValue(a7, "recoveryCallback")); - assertSame(this.foo, TestUtils.getPropertyValue(a7, "recoveryCallback.channel")); - assertEquals(4567L, TestUtils.getPropertyValue(a7, "recoveryCallback.messagingTemplate.sendTimeout")); + assertThat(TestUtils.getPropertyValue(a1, "recoveryCallback")).isNull(); + assertThat(TestUtils.getPropertyValue(a7, "recoveryCallback")).isNotNull(); + assertThat(TestUtils.getPropertyValue(a7, "recoveryCallback.channel")).isSameAs(this.foo); + assertThat(TestUtils.getPropertyValue(a7, "recoveryCallback.messagingTemplate.sendTimeout")).isEqualTo(4567L); - assertSame(this.a1, TestUtils.getPropertyValue(this.handler1, "adviceChain", List.class).get(0)); - assertEquals(9, TestUtils.getPropertyValue( + assertThat(TestUtils.getPropertyValue(this.handler1, "adviceChain", List.class).get(0)).isSameAs(this.a1); + assertThat(TestUtils.getPropertyValue( TestUtils.getPropertyValue(this.handler2, "adviceChain", List.class).get(0), - "retryTemplate.retryPolicy.maxAttempts")); - assertEquals(3, TestUtils.getPropertyValue( - TestUtils.getPropertyValue(this.defaultRetryHandler, "adviceChain", List.class).get(0), - "retryTemplate.retryPolicy.maxAttempts")); + "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(9); + assertThat(TestUtils.getPropertyValue( + TestUtils.getPropertyValue(this.defaultRetryHandler, "adviceChain", List.class).get(0), + "retryTemplate.retryPolicy.maxAttempts")).isEqualTo(3); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java index a324cf36b1..1d51f43d28 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.Test; import org.junit.runner.RunWith; @@ -85,43 +84,43 @@ public class ServiceActivatorParserTests { @Test public void literalExpression() { Object result = this.sendAndReceive(literalExpressionInput, "hello"); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test public void beanAsTarget() { Object result = this.sendAndReceive(beanAsTargetInput, "hello"); - assertEquals("HELLO", result); + assertThat(result).isEqualTo("HELLO"); } @Test public void beanAsArgument() { Object result = this.sendAndReceive(beanAsArgumentInput, new TestPayload()); - assertEquals("TestBean", result); + assertThat(result).isEqualTo("TestBean"); } @Test public void beanInvocationResult() { Object result = this.sendAndReceive(beanInvocationResultInput, "hello"); - assertEquals("helloFOO", result); + assertThat(result).isEqualTo("helloFOO"); } @Test public void multipleLiteralArgs() { Object result = this.sendAndReceive(multipleLiteralArgsInput, "hello"); - assertEquals("foobar", result); + assertThat(result).isEqualTo("foobar"); } @Test public void multipleArgsFromPayload() { Object result = this.sendAndReceive(multipleArgsFromPayloadInput, new TestPerson("John", "Doe")); - assertEquals("JohnDoe", result); + assertThat(result).isEqualTo("JohnDoe"); } @Test public void advised() { Object result = this.sendAndReceive(advisedInput, "hello"); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test @@ -132,8 +131,9 @@ public class ServiceActivatorParserTests { fail("Expected exception"); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: Only one of 'ref' or 'expression' is permitted, not both, " + - "on element 'service-activator' with id='test'.")); + assertThat(e.getMessage() + .startsWith("Configuration problem: Only one of 'ref' or 'expression' is permitted, not both, " + + "on element 'service-activator' with id='test'.")).isTrue(); } } @@ -145,10 +145,10 @@ public class ServiceActivatorParserTests { fail("Expected exception"); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: Ambiguous definition. " + + assertThat(e.getMessage().startsWith("Configuration problem: Ambiguous definition. " + "Inner bean org.springframework.integration.config.xml.ServiceActivatorParserTests$TestBean " + "declaration and \"ref\" testBean are not allowed together on element " + - "'service-activator' with id='test'.")); + "'service-activator' with id='test'.")).isTrue(); } } @@ -160,9 +160,9 @@ public class ServiceActivatorParserTests { fail("Expected exception"); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: Neither 'ref' nor 'expression' " + + assertThat(e.getMessage().startsWith("Configuration problem: Neither 'ref' nor 'expression' " + "are permitted when an inner bean () is configured on element " + - "'service-activator' with id='test'.")); + "'service-activator' with id='test'.")).isTrue(); } } @@ -174,9 +174,9 @@ public class ServiceActivatorParserTests { fail("Expected exception"); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: Exactly one of the 'ref' " + + assertThat(e.getMessage().startsWith("Configuration problem: Exactly one of the 'ref' " + "attribute, 'expression' attribute, or inner bean () definition " + - "is required for element 'service-activator' with id='test'.")); + "is required for element 'service-activator' with id='test'.")).isTrue(); } } @@ -188,9 +188,10 @@ public class ServiceActivatorParserTests { fail("Expected exception"); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: Neither 'ref' nor 'expression' are permitted when " + - "an inner 'expression' element is configured on element " + - "'service-activator' with id='test'.")); + assertThat(e.getMessage() + .startsWith("Configuration problem: Neither 'ref' nor 'expression' are permitted when " + + "an inner 'expression' element is configured on element " + + "'service-activator' with id='test'.")).isTrue(); } } @@ -202,14 +203,15 @@ public class ServiceActivatorParserTests { fail("Expected exception"); } catch (BeanDefinitionParsingException e) { - assertTrue(e.getMessage().startsWith("Configuration problem: A 'method' attribute is not permitted when configuring " + - "an 'expression' on element 'service-activator' with id='test'.")); + assertThat(e.getMessage() + .startsWith("Configuration problem: A 'method' attribute is not permitted when configuring " + + "an 'expression' on element 'service-activator' with id='test'.")).isTrue(); } } @Test public void testConsumerEndpointFactoryBeanDefaultPhase() { - assertEquals(Integer.MIN_VALUE, this.testAliasEndpoint.getPhase()); + assertThat(this.testAliasEndpoint.getPhase()).isEqualTo(Integer.MIN_VALUE); } private Object sendAndReceive(MessageChannel channel, Object payload) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/StreamTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/StreamTransformerParserTests.java index 707c8a3069..539f516be4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/StreamTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/StreamTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -66,24 +64,24 @@ public class StreamTransformerParserTests { public void directChannelWithStringMessage() { this.directInput.send(new GenericMessage(new ByteArrayInputStream("foo".getBytes()))); Message result = output.receive(10000); - assertNotNull(result); - assertArrayEquals("foo".getBytes(), (byte[]) result.getPayload()); + assertThat(result).isNotNull(); + assertThat((byte[]) result.getPayload()).isEqualTo("foo".getBytes()); } @Test public void queueChannelWithStringMessage() { this.queueInput.send(new GenericMessage(new ByteArrayInputStream("foo".getBytes()))); Message result = output.receive(10000); - assertNotNull(result); - assertArrayEquals("foo".getBytes(), (byte[]) result.getPayload()); + assertThat(result).isNotNull(); + assertThat((byte[]) result.getPayload()).isEqualTo("foo".getBytes()); } @Test public void charset() { this.charsetChannel.send(new GenericMessage(new ByteArrayInputStream("foo".getBytes()))); Message result = output.receive(10000); - assertNotNull(result); - assertEquals("foo", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("foo"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/SyslogTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/SyslogTransformerParserTests.java index e50c3b0399..544b44b983 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/SyslogTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/SyslogTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; import java.util.Map; @@ -56,15 +54,15 @@ public class SyslogTransformerParserTests { public void testMap() { toMapChannel.send(new GenericMessage<>("<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE")); Map map = (Map) out.receive(1000).getPayload(); - assertNotNull(map); - assertEquals(6, map.size()); - assertEquals(19, map.get(SyslogToMapTransformer.FACILITY)); - assertEquals(5, map.get(SyslogToMapTransformer.SEVERITY)); + assertThat(map).isNotNull(); + assertThat(map.size()).isEqualTo(6); + assertThat(map.get(SyslogToMapTransformer.FACILITY)).isEqualTo(19); + assertThat(map.get(SyslogToMapTransformer.SEVERITY)).isEqualTo(5); Object date = map.get(SyslogToMapTransformer.TIMESTAMP); - assertTrue(date instanceof Date || date instanceof String); - assertEquals("WEBERN", map.get(SyslogToMapTransformer.HOST)); - assertEquals("TESTING", map.get(SyslogToMapTransformer.TAG)); - assertEquals("[70729]: TEST SYSLOG MESSAGE", map.get(SyslogToMapTransformer.MESSAGE)); + assertThat(date instanceof Date || date instanceof String).isTrue(); + assertThat(map.get(SyslogToMapTransformer.HOST)).isEqualTo("WEBERN"); + assertThat(map.get(SyslogToMapTransformer.TAG)).isEqualTo("TESTING"); + assertThat(map.get(SyslogToMapTransformer.MESSAGE)).isEqualTo("[70729]: TEST SYSLOG MESSAGE"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/TransactionSynchronizationFactoryParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/TransactionSynchronizationFactoryParserTests.java index 26428f396e..411cf2e858 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/TransactionSynchronizationFactoryParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/TransactionSynchronizationFactoryParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.config.xml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -49,35 +47,35 @@ public class TransactionSynchronizationFactoryParserTests { DefaultTransactionSynchronizationFactory syncFactory = context.getBean("syncFactoryComplete", DefaultTransactionSynchronizationFactory.class); - assertNotNull(syncFactory); + assertThat(syncFactory).isNotNull(); TransactionSynchronizationProcessor processor = TestUtils.getPropertyValue(syncFactory, "processor", ExpressionEvaluatingTransactionSynchronizationProcessor.class); - assertNotNull(processor); + assertThat(processor).isNotNull(); MessageChannel beforeCommitResultChannel = TestUtils.getPropertyValue(processor, "beforeCommitChannel", MessageChannel.class); - assertNotNull(beforeCommitResultChannel); - assertEquals(beforeCommitResultChannel, context.getBean("beforeCommitChannel")); + assertThat(beforeCommitResultChannel).isNotNull(); + assertThat(context.getBean("beforeCommitChannel")).isEqualTo(beforeCommitResultChannel); Object beforeCommitExpression = TestUtils.getPropertyValue(processor, "beforeCommitExpression"); - assertNull(beforeCommitExpression); + assertThat(beforeCommitExpression).isNull(); MessageChannel afterCommitResultChannel = TestUtils.getPropertyValue(processor, "afterCommitChannel", MessageChannel.class); - assertNotNull(afterCommitResultChannel); - assertEquals(afterCommitResultChannel, context.getBean("nullChannel")); + assertThat(afterCommitResultChannel).isNotNull(); + assertThat(context.getBean("nullChannel")).isEqualTo(afterCommitResultChannel); Expression afterCommitExpression = TestUtils.getPropertyValue(processor, "afterCommitExpression", Expression.class); - assertNotNull(afterCommitExpression); - assertEquals("'afterCommit'", ((SpelExpression) afterCommitExpression).getExpressionString()); + assertThat(afterCommitExpression).isNotNull(); + assertThat(((SpelExpression) afterCommitExpression).getExpressionString()).isEqualTo("'afterCommit'"); MessageChannel afterRollbackResultChannel = TestUtils.getPropertyValue(processor, "afterRollbackChannel", MessageChannel.class); - assertNotNull(afterRollbackResultChannel); - assertEquals(afterRollbackResultChannel, context.getBean("afterRollbackChannel")); + assertThat(afterRollbackResultChannel).isNotNull(); + assertThat(context.getBean("afterRollbackChannel")).isEqualTo(afterRollbackResultChannel); Expression afterRollbackExpression = TestUtils.getPropertyValue(processor, "afterRollbackExpression", Expression.class); - assertNotNull(afterRollbackExpression); - assertEquals("'afterRollback'", ((SpelExpression) afterRollbackExpression).getExpressionString()); + assertThat(afterRollbackExpression).isNotNull(); + assertThat(((SpelExpression) afterRollbackExpression).getExpressionString()).isEqualTo("'afterRollback'"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java index 93fa4243af..27c734c5c1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java @@ -16,21 +16,8 @@ package org.springframework.integration.configuration; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -52,7 +39,6 @@ import java.util.concurrent.atomic.AtomicReference; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.apache.commons.logging.Log; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -300,16 +286,16 @@ public class EnableIntegrationTests { @Test public void testAnnotatedServiceActivator() throws Exception { this.serviceActivatorEndpoint.start(); - assertTrue(this.inputReceiveLatch.await(10, TimeUnit.SECONDS)); + assertThat(this.inputReceiveLatch.await(10, TimeUnit.SECONDS)).isTrue(); - assertEquals(10L, TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "maxMessagesPerPoll")); + assertThat(TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "maxMessagesPerPoll")).isEqualTo(10L); Trigger trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "trigger", Trigger.class); - assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class)); - assertEquals(100L, TestUtils.getPropertyValue(trigger, "period")); - assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)); + assertThat(trigger).isInstanceOf(PeriodicTrigger.class); + assertThat(TestUtils.getPropertyValue(trigger, "period")).isEqualTo(100L); + assertThat(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)).isFalse(); - assertTrue(this.annotationTestService.isRunning()); + assertThat(this.annotationTestService.isRunning()).isTrue(); Log logger = spy(TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "logger", Log.class)); when(logger.isDebugEnabled()).thenReturn(true); final CountDownLatch pollerInterruptedLatch = new CountDownLatch(1); @@ -321,120 +307,120 @@ public class EnableIntegrationTests { new DirectFieldAccessor(this.serviceActivatorEndpoint).setPropertyValue("logger", logger); this.serviceActivatorEndpoint.stop(); - assertFalse(this.annotationTestService.isRunning()); + assertThat(this.annotationTestService.isRunning()).isFalse(); // wait until the service activator's poller is interrupted. - assertTrue(pollerInterruptedLatch.await(10, TimeUnit.SECONDS)); + assertThat(pollerInterruptedLatch.await(10, TimeUnit.SECONDS)).isTrue(); this.serviceActivatorEndpoint.start(); - assertTrue(this.annotationTestService.isRunning()); + assertThat(this.annotationTestService.isRunning()).isTrue(); trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint1, "trigger", Trigger.class); - assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class)); - assertEquals(100L, TestUtils.getPropertyValue(trigger, "period")); - assertTrue(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)); + assertThat(trigger).isInstanceOf(PeriodicTrigger.class); + assertThat(TestUtils.getPropertyValue(trigger, "period")).isEqualTo(100L); + assertThat(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)).isTrue(); trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint2, "trigger", Trigger.class); - assertThat(trigger, Matchers.instanceOf(CronTrigger.class)); - assertEquals("0 5 7 * * *", TestUtils.getPropertyValue(trigger, "sequenceGenerator.expression")); + assertThat(trigger).isInstanceOf(CronTrigger.class); + assertThat(TestUtils.getPropertyValue(trigger, "sequenceGenerator.expression")).isEqualTo("0 5 7 * * *"); trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint3, "trigger", Trigger.class); - assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class)); - assertEquals(11L, TestUtils.getPropertyValue(trigger, "period")); - assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)); + assertThat(trigger).isInstanceOf(PeriodicTrigger.class); + assertThat(TestUtils.getPropertyValue(trigger, "period")).isEqualTo(11L); + assertThat(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)).isFalse(); trigger = TestUtils.getPropertyValue(this.serviceActivatorEndpoint4, "trigger", Trigger.class); - assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class)); - assertEquals(1000L, TestUtils.getPropertyValue(trigger, "period")); - assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)); - assertSame(this.myTrigger, trigger); + assertThat(trigger).isInstanceOf(PeriodicTrigger.class); + assertThat(TestUtils.getPropertyValue(trigger, "period")).isEqualTo(1000L); + assertThat(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)).isFalse(); + assertThat(trigger).isSameAs(this.myTrigger); trigger = TestUtils.getPropertyValue(this.transformer, "trigger", Trigger.class); - assertThat(trigger, Matchers.instanceOf(PeriodicTrigger.class)); - assertEquals(10L, TestUtils.getPropertyValue(trigger, "period")); - assertFalse(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)); + assertThat(trigger).isInstanceOf(PeriodicTrigger.class); + assertThat(TestUtils.getPropertyValue(trigger, "period")).isEqualTo(10L); + assertThat(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)).isFalse(); this.input.send(MessageBuilder.withPayload("Foo").build()); Message interceptedMessage = this.wireTapChannel.receive(10000); - assertNotNull(interceptedMessage); - assertEquals("Foo", interceptedMessage.getPayload()); + assertThat(interceptedMessage).isNotNull(); + assertThat(interceptedMessage.getPayload()).isEqualTo("Foo"); Message receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals("FOO", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("FOO"); receive = this.wireTapFromOutput.receive(10000); - assertNotNull(receive); - assertEquals("FOO", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("FOO"); MessageHistory messageHistory = receive.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class); - assertNotNull(messageHistory); + assertThat(messageHistory).isNotNull(); String messageHistoryString = messageHistory.toString(); - assertThat(messageHistoryString, Matchers.containsString("input")); - assertThat(messageHistoryString, - Matchers.containsString("annotationTestService.handle.serviceActivator.handler")); - assertThat(messageHistoryString, Matchers.not(Matchers.containsString("output"))); + assertThat(messageHistoryString).contains("input"); + assertThat(messageHistoryString).contains("annotationTestService.handle.serviceActivator.handler"); + assertThat(messageHistoryString).doesNotContain("output"); receive = this.publishedChannel.receive(10000); - assertNotNull(receive); - assertEquals("foo", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("foo"); messageHistory = receive.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class); - assertNotNull(messageHistory); + assertThat(messageHistory).isNotNull(); messageHistoryString = messageHistory.toString(); - assertThat(messageHistoryString, Matchers.not(Matchers.containsString("input"))); - assertThat(messageHistoryString, Matchers.not(Matchers.containsString("output"))); - assertThat(messageHistoryString, Matchers.containsString("publishedChannel")); + assertThat(messageHistoryString).doesNotContain("input"); + assertThat(messageHistoryString).doesNotContain("output"); + assertThat(messageHistoryString).contains("publishedChannel"); - assertNull(this.wireTapChannel.receive(0)); - assertThat(this.testChannelInterceptor.getInvoked(), Matchers.greaterThan(0)); - assertThat(this.fbInterceptorCounter.get(), Matchers.greaterThan(0)); + assertThat(this.wireTapChannel.receive(0)).isNull(); + assertThat(this.testChannelInterceptor.getInvoked()).isGreaterThan(0); + assertThat(this.fbInterceptorCounter.get()).isGreaterThan(0); - assertTrue(this.context.containsBean("annotationTestService.count.inboundChannelAdapter.source")); + assertThat(this.context.containsBean("annotationTestService.count.inboundChannelAdapter.source")).isTrue(); Object messageSource = this.context.getBean("annotationTestService.count.inboundChannelAdapter.source"); - assertThat(messageSource, Matchers.instanceOf(MethodInvokingMessageSource.class)); + assertThat(messageSource).isInstanceOf(MethodInvokingMessageSource.class); - assertNull(this.counterChannel.receive(10)); + assertThat(this.counterChannel.receive(10)).isNull(); SmartLifecycle countSA = this.context.getBean("annotationTestService.count.inboundChannelAdapter", SmartLifecycle.class); - assertFalse(countSA.isAutoStartup()); - assertEquals(23, countSA.getPhase()); + assertThat(countSA.isAutoStartup()).isFalse(); + assertThat(countSA.getPhase()).isEqualTo(23); countSA.start(); for (int i = 0; i < 10; i++) { Message message = this.counterChannel.receive(1000); - assertNotNull(message); - assertEquals(i + 1, message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo(i + 1); } Message message = this.fooChannel.receive(1000); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); message = this.fooChannel.receive(1000); - assertNotNull(message); - assertEquals("foo", message.getPayload()); - assertNull(this.fooChannel.receive(10)); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); + assertThat(this.fooChannel.receive(10)).isNull(); message = this.messageChannel.receive(1000); - assertNotNull(message); - assertEquals("bar", message.getPayload()); - assertTrue(message.getHeaders().containsKey("foo")); - assertEquals("FOO", message.getHeaders().get("foo")); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("bar"); + assertThat(message.getHeaders().containsKey("foo")).isTrue(); + assertThat(message.getHeaders().get("foo")).isEqualTo("FOO"); MessagingTemplate messagingTemplate = new MessagingTemplate(this.controlBusChannel); - assertEquals(false, messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class)); + assertThat(messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class)).isEqualTo(false); this.controlBusChannel.send(new GenericMessage<>("@lifecycle.start()")); - assertEquals(true, messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class)); + assertThat(messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class)).isEqualTo(true); this.controlBusChannel.send(new GenericMessage<>("@lifecycle.stop()")); - assertEquals(false, messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class)); + assertThat(messagingTemplate.convertSendAndReceive("@lifecycle.isRunning()", Boolean.class)).isEqualTo(false); Map beansOfType = this.context.getBeansOfType(ServiceActivatingHandler.class); - assertFalse(beansOfType.keySet() - .contains("enableIntegrationTests.ContextConfiguration2.controlBus.serviceActivator.handler")); + assertThat(beansOfType.keySet() + .contains("enableIntegrationTests.ContextConfiguration2.controlBus.serviceActivator.handler")) + .isFalse(); } @Test @@ -445,36 +431,37 @@ public class EnableIntegrationTests { fail("ExpectedException"); } catch (IllegalStateException e) { - assertThat(e.getMessage(), containsString("cannot be changed")); + assertThat(e.getMessage()).contains("cannot be changed"); } this.configurer.stop(); this.configurer.setComponentNamePatterns(new String[] { "*" }); - assertEquals("*", TestUtils.getPropertyValue(this.configurer, "componentNamePatterns", String[].class)[0]); + assertThat(TestUtils.getPropertyValue(this.configurer, "componentNamePatterns", String[].class)[0]) + .isEqualTo("*"); } @Test public void testMessagingGateway() throws InterruptedException { String payload = "bar"; String result = this.testGateway.echo(payload); - assertEquals(payload.toUpperCase(), result.substring(0, payload.length())); - assertThat(result, containsString("InvocableHandlerMethod")); - assertThat(result, not(containsString("SpelExpression"))); + assertThat(result.substring(0, payload.length())).isEqualTo(payload.toUpperCase()); + assertThat(result).contains("InvocableHandlerMethod"); + assertThat(result).doesNotContain("SpelExpression"); result = this.testGateway2.echo2(payload); - assertNotNull(result); - assertEquals(payload.toUpperCase() + "2", result.substring(0, payload.length() + 1)); - assertThat(result, not(containsString("InvocableHandlerMethod"))); - assertThat(result, containsString("SpelExpression")); - assertThat(result, containsString("CompoundExpression.getValueInternal")); - assertNotNull(this.testGateway2.echo2("baz")); + assertThat(result).isNotNull(); + assertThat(result.substring(0, payload.length() + 1)).isEqualTo(payload.toUpperCase() + "2"); + assertThat(result).doesNotContain("InvocableHandlerMethod"); + assertThat(result).contains("SpelExpression"); + assertThat(result).contains("CompoundExpression.getValueInternal"); + assertThat(this.testGateway2.echo2("baz")).isNotNull(); // third one should be compiled, but it's not since SF-5.0.2 - proxies aren't compilable SpELs any more result = this.testGateway2.echo2("baz"); - assertNotNull(result); - assertEquals("BAZ2", result.substring(0, 4)); - assertThat(result, not(containsString("InvocableHandlerMethod"))); - assertThat(result, containsString("SpelExpression")); + assertThat(result).isNotNull(); + assertThat(result.substring(0, 4)).isEqualTo("BAZ2"); + assertThat(result).doesNotContain("InvocableHandlerMethod"); + assertThat(result).contains("SpelExpression"); this.testGateway.sendAsync("foo"); - assertTrue(this.asyncAnnotationProcessLatch.await(1, TimeUnit.SECONDS)); - assertThat(this.asyncAnnotationProcessThread.get(), not(sameInstance(Thread.currentThread()))); + assertThat(this.asyncAnnotationProcessLatch.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(this.asyncAnnotationProcessThread.get()).isNotSameAs(Thread.currentThread()); } @Test @@ -485,8 +472,8 @@ public class EnableIntegrationTests { child.refresh(); AbstractMessageChannel foo = child.getBean("foo", AbstractMessageChannel.class); ChannelInterceptor baz = child.getBean("baz", ChannelInterceptor.class); - assertTrue(foo.getChannelInterceptors().contains(baz)); - assertFalse(this.output.getChannelInterceptors().contains(baz)); + assertThat(foo.getChannelInterceptors().contains(baz)).isTrue(); + assertThat(this.output.getChannelInterceptors().contains(baz)).isFalse(); child.close(); } @@ -498,8 +485,8 @@ public class EnableIntegrationTests { child.refresh(); AbstractMessageChannel foo = child.getBean("foo", AbstractMessageChannel.class); ChannelInterceptor baz = child.getBean("baz", ChannelInterceptor.class); - assertTrue(foo.getChannelInterceptors().contains(baz)); - assertFalse(this.output.getChannelInterceptors().contains(baz)); + assertThat(foo.getChannelInterceptors().contains(baz)).isTrue(); + assertThat(this.output.getChannelInterceptors().contains(baz)).isFalse(); child.close(); } @@ -507,78 +494,79 @@ public class EnableIntegrationTests { public void testIntegrationConverter() { this.numberChannel.send(new GenericMessage(10)); this.numberChannel.send(new GenericMessage(true)); - assertThat(this.testConverter.getInvoked(), Matchers.greaterThan(0)); + assertThat(this.testConverter.getInvoked()).isGreaterThan(0); - assertTrue(this.bytesChannel.send(new GenericMessage("foo".getBytes()))); - assertTrue(this.bytesChannel.send(new GenericMessage<>(MutableMessageBuilder.withPayload("").build()))); + assertThat(this.bytesChannel.send(new GenericMessage("foo".getBytes()))).isTrue(); + assertThat(this.bytesChannel.send(new GenericMessage<>(MutableMessageBuilder.withPayload("").build()))) + .isTrue(); } @Test public void testMetaAnnotations() { - assertEquals(2, this.context.getBeanNamesForType(GatewayProxyFactoryBean.class).length); + assertThat(this.context.getBeanNamesForType(GatewayProxyFactoryBean.class).length).isEqualTo(2); PollingConsumer consumer = this.context.getBean("annotationTestService.annCount.serviceActivator", PollingConsumer.class); - assertFalse(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)); - assertEquals(23, TestUtils.getPropertyValue(consumer, "phase")); - assertSame(context.getBean("annInput"), TestUtils.getPropertyValue(consumer, "inputChannel")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.outputChannelName")); - assertSame(context.getBean("annAdvice"), TestUtils.getPropertyValue(consumer, - "handler.adviceChain", List.class).get(0)); - assertEquals(1000L, TestUtils.getPropertyValue(consumer, "trigger.period")); + assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(23); + assertThat(TestUtils.getPropertyValue(consumer, "inputChannel")).isSameAs(context.getBean("annInput")); + assertThat(TestUtils.getPropertyValue(consumer, "handler.outputChannelName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, + "handler.adviceChain", List.class).get(0)).isSameAs(context.getBean("annAdvice")); + assertThat(TestUtils.getPropertyValue(consumer, "trigger.period")).isEqualTo(1000L); consumer = this.context.getBean("annotationTestService.annCount1.serviceActivator", PollingConsumer.class); consumer.stop(); - assertTrue(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)); - assertEquals(23, TestUtils.getPropertyValue(consumer, "phase")); - assertSame(context.getBean("annInput1"), TestUtils.getPropertyValue(consumer, "inputChannel")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.outputChannel.beanName")); - assertSame(context.getBean("annAdvice1"), TestUtils.getPropertyValue(consumer, - "handler.adviceChain", List.class).get(0)); - assertEquals(2000L, TestUtils.getPropertyValue(consumer, "trigger.period")); + assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(23); + assertThat(TestUtils.getPropertyValue(consumer, "inputChannel")).isSameAs(context.getBean("annInput1")); + assertThat(TestUtils.getPropertyValue(consumer, "handler.outputChannel.beanName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, + "handler.adviceChain", List.class).get(0)).isSameAs(context.getBean("annAdvice1")); + assertThat(TestUtils.getPropertyValue(consumer, "trigger.period")).isEqualTo(2000L); consumer = this.context.getBean("annotationTestService.annCount2.serviceActivator", PollingConsumer.class); - assertFalse(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)); - assertEquals(23, TestUtils.getPropertyValue(consumer, "phase")); - assertSame(context.getBean("annInput"), TestUtils.getPropertyValue(consumer, "inputChannel")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.outputChannelName")); - assertSame(context.getBean("annAdvice"), TestUtils.getPropertyValue(consumer, - "handler.adviceChain", List.class).get(0)); - assertEquals(1000L, TestUtils.getPropertyValue(consumer, "trigger.period")); + assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(23); + assertThat(TestUtils.getPropertyValue(consumer, "inputChannel")).isSameAs(context.getBean("annInput")); + assertThat(TestUtils.getPropertyValue(consumer, "handler.outputChannelName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, + "handler.adviceChain", List.class).get(0)).isSameAs(context.getBean("annAdvice")); + assertThat(TestUtils.getPropertyValue(consumer, "trigger.period")).isEqualTo(1000L); // Tests when the channel is in a "middle" annotation consumer = this.context.getBean("annotationTestService.annCount5.serviceActivator", PollingConsumer.class); - assertFalse(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)); - assertEquals(23, TestUtils.getPropertyValue(consumer, "phase")); - assertSame(context.getBean("annInput3"), TestUtils.getPropertyValue(consumer, "inputChannel")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.outputChannelName")); - assertSame(context.getBean("annAdvice"), TestUtils.getPropertyValue(consumer, - "handler.adviceChain", List.class).get(0)); - assertEquals(1000L, TestUtils.getPropertyValue(consumer, "trigger.period")); + assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(23); + assertThat(TestUtils.getPropertyValue(consumer, "inputChannel")).isSameAs(context.getBean("annInput3")); + assertThat(TestUtils.getPropertyValue(consumer, "handler.outputChannelName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, + "handler.adviceChain", List.class).get(0)).isSameAs(context.getBean("annAdvice")); + assertThat(TestUtils.getPropertyValue(consumer, "trigger.period")).isEqualTo(1000L); consumer = this.context.getBean("annotationTestService.annAgg1.aggregator", PollingConsumer.class); - assertFalse(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)); - assertEquals(23, TestUtils.getPropertyValue(consumer, "phase")); - assertSame(context.getBean("annInput"), TestUtils.getPropertyValue(consumer, "inputChannel")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.outputChannelName")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.discardChannelName")); - assertEquals(1000L, TestUtils.getPropertyValue(consumer, "trigger.period")); - assertEquals(-1L, TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")); - assertFalse(TestUtils.getPropertyValue(consumer, "handler.sendPartialResultOnExpiry", Boolean.class)); + assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(23); + assertThat(TestUtils.getPropertyValue(consumer, "inputChannel")).isSameAs(context.getBean("annInput")); + assertThat(TestUtils.getPropertyValue(consumer, "handler.outputChannelName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, "handler.discardChannelName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, "trigger.period")).isEqualTo(1000L); + assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(-1L); + assertThat(TestUtils.getPropertyValue(consumer, "handler.sendPartialResultOnExpiry", Boolean.class)).isFalse(); consumer = this.context.getBean("annotationTestService.annAgg2.aggregator", PollingConsumer.class); - assertFalse(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)); - assertEquals(23, TestUtils.getPropertyValue(consumer, "phase")); - assertSame(context.getBean("annInput"), TestUtils.getPropertyValue(consumer, "inputChannel")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.outputChannelName")); - assertEquals("annOutput", TestUtils.getPropertyValue(consumer, "handler.discardChannelName")); - assertEquals(1000L, TestUtils.getPropertyValue(consumer, "trigger.period")); - assertEquals(75L, TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")); - assertTrue(TestUtils.getPropertyValue(consumer, "handler.sendPartialResultOnExpiry", Boolean.class)); + assertThat(TestUtils.getPropertyValue(consumer, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(consumer, "phase")).isEqualTo(23); + assertThat(TestUtils.getPropertyValue(consumer, "inputChannel")).isSameAs(context.getBean("annInput")); + assertThat(TestUtils.getPropertyValue(consumer, "handler.outputChannelName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, "handler.discardChannelName")).isEqualTo("annOutput"); + assertThat(TestUtils.getPropertyValue(consumer, "trigger.period")).isEqualTo(1000L); + assertThat(TestUtils.getPropertyValue(consumer, "handler.messagingTemplate.sendTimeout")).isEqualTo(75L); + assertThat(TestUtils.getPropertyValue(consumer, "handler.sendPartialResultOnExpiry", Boolean.class)).isTrue(); } @Test @@ -586,23 +574,23 @@ public class EnableIntegrationTests { GenericMessage testMessage = new GenericMessage("foo"); this.bridgeInput.send(testMessage); Message receive = this.bridgeOutput.receive(10_000); - assertNotNull(receive); - assertSame(receive, testMessage); - assertNull(this.bridgeOutput.receive(10)); + assertThat(receive).isNotNull(); + assertThat(testMessage).isSameAs(receive); + assertThat(this.bridgeOutput.receive(10)).isNull(); this.pollableBridgeInput.send(testMessage); receive = this.pollableBridgeOutput.receive(10_000); - assertNotNull(receive); - assertSame(receive, testMessage); - assertNull(this.pollableBridgeOutput.receive(10)); + assertThat(receive).isNotNull(); + assertThat(testMessage).isSameAs(receive); + assertThat(this.pollableBridgeOutput.receive(10)).isNull(); try { this.metaBridgeInput.send(testMessage); fail("MessageDeliveryException expected"); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(MessageDeliveryException.class)); - assertThat(e.getMessage(), Matchers.containsString("Dispatcher has no subscribers")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getMessage()).contains("Dispatcher has no subscribers"); } this.context.getBean("enableIntegrationTests.ContextConfiguration.metaBridgeOutput.bridgeFrom", @@ -610,31 +598,31 @@ public class EnableIntegrationTests { this.metaBridgeInput.send(testMessage); receive = this.metaBridgeOutput.receive(10_000); - assertNotNull(receive); - assertSame(receive, testMessage); - assertNull(this.metaBridgeOutput.receive(10)); + assertThat(receive).isNotNull(); + assertThat(testMessage).isSameAs(receive); + assertThat(this.metaBridgeOutput.receive(10)).isNull(); this.bridgeToInput.send(testMessage); receive = this.bridgeToOutput.receive(10_000); - assertNotNull(receive); - assertSame(receive, testMessage); - assertNull(this.bridgeToOutput.receive(10)); + assertThat(receive).isNotNull(); + assertThat(testMessage).isSameAs(receive); + assertThat(this.bridgeToOutput.receive(10)).isNull(); PollableChannel replyChannel = new QueueChannel(); Message bridgeMessage = MessageBuilder.fromMessage(testMessage).setReplyChannel(replyChannel).build(); this.pollableBridgeToInput.send(bridgeMessage); receive = replyChannel.receive(10_000); - assertNotNull(receive); - assertSame(receive, bridgeMessage); - assertNull(replyChannel.receive(10)); + assertThat(receive).isNotNull(); + assertThat(bridgeMessage).isSameAs(receive); + assertThat(replyChannel.receive(10)).isNull(); try { this.myBridgeToInput.send(testMessage); fail("MessageDeliveryException expected"); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(MessageDeliveryException.class)); - assertThat(e.getMessage(), Matchers.containsString("Dispatcher has no subscribers")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getMessage()).contains("Dispatcher has no subscribers"); } this.context.getBean("enableIntegrationTests.ContextConfiguration.myBridgeToInput.bridgeTo", @@ -642,9 +630,9 @@ public class EnableIntegrationTests { this.myBridgeToInput.send(bridgeMessage); receive = replyChannel.receive(10_000); - assertNotNull(receive); - assertSame(receive, bridgeMessage); - assertNull(replyChannel.receive(10)); + assertThat(receive).isNotNull(); + assertThat(bridgeMessage).isSameAs(receive); + assertThat(replyChannel.receive(10)).isNull(); } @Test @@ -663,42 +651,42 @@ public class EnableIntegrationTests { }); - assertTrue(consumeLatch.await(0, TimeUnit.SECONDS)); // runs on same thread + assertThat(consumeLatch.await(0, TimeUnit.SECONDS)).isTrue(); // runs on same thread List integers = ref.get(); - assertEquals(5, integers.size()); + assertThat(integers.size()).isEqualTo(5); - assertThat(integers, contains(2, 4, 6, 8, 10)); + assertThat(integers).containsExactly(2, 4, 6, 8, 10); } @Test @DirtiesContext public void testRoles() { - assertThat(this.roleController.getRoles(), containsInAnyOrder("foo", "bar")); - assertFalse(this.roleController.allEndpointsRunning("foo")); - assertFalse(this.roleController.noEndpointsRunning("foo")); - assertTrue(this.roleController.allEndpointsRunning("bar")); - assertFalse(this.roleController.noEndpointsRunning("bar")); + assertThat(this.roleController.getRoles()).contains("foo", "bar"); + assertThat(this.roleController.allEndpointsRunning("foo")).isFalse(); + assertThat(this.roleController.noEndpointsRunning("foo")).isFalse(); + assertThat(this.roleController.allEndpointsRunning("bar")).isTrue(); + assertThat(this.roleController.noEndpointsRunning("bar")).isFalse(); Map state = this.roleController.getEndpointsRunningStatus("foo"); - assertThat(state.get("annotationTestService.handle.serviceActivator"), equalTo(Boolean.FALSE)); - assertThat(state.get("enableIntegrationTests.ContextConfiguration2.sendAsyncHandler.serviceActivator"), - equalTo(Boolean.TRUE)); + assertThat(state.get("annotationTestService.handle.serviceActivator")).isEqualTo(Boolean.FALSE); + assertThat(state.get("enableIntegrationTests.ContextConfiguration2.sendAsyncHandler.serviceActivator")) + .isEqualTo(Boolean.TRUE); this.roleController.startLifecyclesInRole("foo"); - assertTrue(this.roleController.allEndpointsRunning("foo")); + assertThat(this.roleController.allEndpointsRunning("foo")).isTrue(); this.roleController.stopLifecyclesInRole("foo"); - assertFalse(this.roleController.allEndpointsRunning("foo")); - assertTrue(this.roleController.noEndpointsRunning("foo")); + assertThat(this.roleController.allEndpointsRunning("foo")).isFalse(); + assertThat(this.roleController.noEndpointsRunning("foo")).isTrue(); @SuppressWarnings("unchecked") MultiValueMap lifecycles = TestUtils.getPropertyValue(this.roleController, "lifecycles", MultiValueMap.class); - assertEquals(2, lifecycles.size()); - assertEquals(2, lifecycles.get("foo").size()); - assertEquals(1, lifecycles.get("bar").size()); - assertFalse(this.serviceActivatorEndpoint.isRunning()); - assertFalse(this.sendAsyncHandler.isRunning()); - assertEquals(2, lifecycles.size()); - assertEquals(2, lifecycles.get("foo").size()); + assertThat(lifecycles.size()).isEqualTo(2); + assertThat(lifecycles.get("foo").size()).isEqualTo(2); + assertThat(lifecycles.get("bar").size()).isEqualTo(1); + assertThat(this.serviceActivatorEndpoint.isRunning()).isFalse(); + assertThat(this.sendAsyncHandler.isRunning()).isFalse(); + assertThat(lifecycles.size()).isEqualTo(2); + assertThat(lifecycles.get("foo").size()).isEqualTo(2); } @Test @@ -711,8 +699,8 @@ public class EnableIntegrationTests { this.autoCreatedChannelMessageSourceAdapter.start(); Message receive = testChannel.receive(10000); - assertNotNull(receive); - assertEquals("bar", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("bar"); this.autoCreatedChannelMessageSourceAdapter.stop(); } @@ -720,14 +708,15 @@ public class EnableIntegrationTests { public void testIntegrationEvaluationContextCustomization() { EvaluationContext evaluationContext = this.context.getBean(StandardEvaluationContext.class); List propertyAccessors = TestUtils.getPropertyValue(evaluationContext, "propertyAccessors", List.class); - assertEquals(4, propertyAccessors.size()); - assertThat(propertyAccessors.get(0), instanceOf(JsonPropertyAccessor.class)); - assertThat(propertyAccessors.get(1), instanceOf(EnvironmentAccessor.class)); - assertThat(propertyAccessors.get(2), instanceOf(MapAccessor.class)); - assertThat(propertyAccessors.get(3), instanceOf(ReflectivePropertyAccessor.class)); + assertThat(propertyAccessors.size()).isEqualTo(4); + assertThat(propertyAccessors.get(0)).isInstanceOf(JsonPropertyAccessor.class); + assertThat(propertyAccessors.get(1)).isInstanceOf(EnvironmentAccessor.class); + assertThat(propertyAccessors.get(2)).isInstanceOf(MapAccessor.class); + assertThat(propertyAccessors.get(3)).isInstanceOf(ReflectivePropertyAccessor.class); Map variables = TestUtils.getPropertyValue(evaluationContext, "variables", Map.class); Object testSpelFunction = variables.get("testSpelFunction"); - assertEquals(ClassUtils.getStaticMethod(TestSpelFunction.class, "bar", Object.class), testSpelFunction); + assertThat(testSpelFunction).isEqualTo(ClassUtils.getStaticMethod(TestSpelFunction.class, "bar", + Object.class)); } @Autowired @@ -744,11 +733,11 @@ public class EnableIntegrationTests { Message receive = this.myHandlerSuccessChannel.receive(10_000); - assertNotNull(receive); - assertEquals(testDate, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(testDate); - assertTrue(this.publisherAnnotationBeanPostProcessor.isProxyTargetClass()); - assertEquals(Integer.MAX_VALUE - 1, this.publisherAnnotationBeanPostProcessor.getOrder()); + assertThat(this.publisherAnnotationBeanPostProcessor.isProxyTargetClass()).isTrue(); + assertThat(this.publisherAnnotationBeanPostProcessor.getOrder()).isEqualTo(Integer.MAX_VALUE - 1); } @Configuration @@ -1261,20 +1250,20 @@ public class EnableIntegrationTests { @Transformer(inputChannel = "gatewayChannel") public String transform(Message message) { - assertTrue(message.getHeaders().containsKey("foo")); - assertEquals("FOO", message.getHeaders().get("foo")); - assertTrue(message.getHeaders().containsKey("calledMethod")); - assertEquals("echo", message.getHeaders().get("calledMethod")); + assertThat(message.getHeaders()).containsKey("foo"); + assertThat(message.getHeaders().get("foo")).isEqualTo("FOO"); + assertThat(message.getHeaders()).containsKey("calledMethod"); + assertThat(message.getHeaders().get("calledMethod")).isEqualTo("echo"); return this.handle(message.getPayload()) + Arrays.asList(new Throwable().getStackTrace()).toString(); } @Transformer(inputChannel = "gatewayChannel2") @UseSpelInvoker(compilerMode = "${xxxxxxxx:IMMEDIATE}") public String transform2(Message message) { - assertTrue(message.getHeaders().containsKey("foo")); - assertEquals("FOO", message.getHeaders().get("foo")); - assertTrue(message.getHeaders().containsKey("calledMethod")); - assertEquals("echo2", message.getHeaders().get("calledMethod")); + assertThat(message.getHeaders()).containsKey("foo"); + assertThat(message.getHeaders().get("foo")).isEqualTo("FOO"); + assertThat(message.getHeaders()).containsKey("calledMethod"); + assertThat(message.getHeaders().get("calledMethod")).isEqualTo("echo2"); return this.handle(message.getPayload()) + "2" + Arrays.asList(new Throwable().getStackTrace()).toString(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/context/IntegrationContextTests.java b/spring-integration-core/src/test/java/org/springframework/integration/context/IntegrationContextTests.java index 718e5c88a5..14b71fcee0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/context/IntegrationContextTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/context/IntegrationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 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,7 @@ package org.springframework.integration.context; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Properties; @@ -59,14 +57,15 @@ public class IntegrationContextTests { @Test public void testIntegrationContextComponents() { - assertEquals("true", this.integrationProperties.get(IntegrationProperties.THROW_EXCEPTION_ON_LATE_REPLY)); - assertEquals("20", this.integrationProperties.get(IntegrationProperties.TASK_SCHEDULER_POOL_SIZE)); - assertEquals(this.integrationProperties, this.serviceActivator.getIntegrationProperties()); - assertEquals(20, TestUtils.getPropertyValue(this.taskScheduler, "poolSize")); - assertFalse(this.serviceActivator.isAutoStartup()); - assertFalse(this.serviceActivator.isRunning()); - assertTrue(this.serviceActivatorExplicit.isAutoStartup()); - assertTrue(this.serviceActivatorExplicit.isRunning()); + assertThat(this.integrationProperties.get(IntegrationProperties.THROW_EXCEPTION_ON_LATE_REPLY)) + .isEqualTo("true"); + assertThat(this.integrationProperties.get(IntegrationProperties.TASK_SCHEDULER_POOL_SIZE)).isEqualTo("20"); + assertThat(this.serviceActivator.getIntegrationProperties()).isEqualTo(this.integrationProperties); + assertThat(TestUtils.getPropertyValue(this.taskScheduler, "poolSize")).isEqualTo(20); + assertThat(this.serviceActivator.isAutoStartup()).isFalse(); + assertThat(this.serviceActivator.isRunning()).isFalse(); + assertThat(this.serviceActivatorExplicit.isAutoStartup()).isTrue(); + assertThat(this.serviceActivatorExplicit.isRunning()).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java index cea759d9b6..a693f6dcaf 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; @@ -59,9 +56,9 @@ public class AsyncMessagingTemplateTests { template.setDefaultDestination(channel); Message message = MessageBuilder.withPayload("test").build(); Future future = template.asyncSend(message); - assertNull(future.get(10000, TimeUnit.MILLISECONDS)); + assertThat(future.get(10000, TimeUnit.MILLISECONDS)).isNull(); Message result = channel.receive(0); - assertEquals(message, result); + assertThat(result).isEqualTo(message); } @Test @@ -70,9 +67,9 @@ public class AsyncMessagingTemplateTests { AsyncMessagingTemplate template = new AsyncMessagingTemplate(); Message message = MessageBuilder.withPayload("test").build(); Future future = template.asyncSend(channel, message); - assertNull(future.get(10000, TimeUnit.MILLISECONDS)); + assertThat(future.get(10000, TimeUnit.MILLISECONDS)).isNull(); Message result = channel.receive(0); - assertEquals(message, result); + assertThat(result).isEqualTo(message); } @Test @@ -85,9 +82,9 @@ public class AsyncMessagingTemplateTests { template.setBeanFactory(context); Message message = MessageBuilder.withPayload("test").build(); Future future = template.asyncSend("testChannel", message); - assertNull(future.get(10000, TimeUnit.MILLISECONDS)); + assertThat(future.get(10000, TimeUnit.MILLISECONDS)).isNull(); Message result = channel.receive(0); - assertEquals(message, result); + assertThat(result).isEqualTo(message); } @Test(expected = TimeoutException.class) @@ -105,9 +102,9 @@ public class AsyncMessagingTemplateTests { AsyncMessagingTemplate template = new AsyncMessagingTemplate(); template.setDefaultDestination(channel); Future future = template.asyncConvertAndSend("test"); - assertNull(future.get(10000, TimeUnit.MILLISECONDS)); + assertThat(future.get(10000, TimeUnit.MILLISECONDS)).isNull(); Message result = channel.receive(0); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); } @Test @@ -115,9 +112,9 @@ public class AsyncMessagingTemplateTests { QueueChannel channel = new QueueChannel(); AsyncMessagingTemplate template = new AsyncMessagingTemplate(); Future future = template.asyncConvertAndSend(channel, "test"); - assertNull(future.get(10000, TimeUnit.MILLISECONDS)); + assertThat(future.get(10000, TimeUnit.MILLISECONDS)).isNull(); Message result = channel.receive(0); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); } @Test @@ -129,9 +126,9 @@ public class AsyncMessagingTemplateTests { AsyncMessagingTemplate template = new AsyncMessagingTemplate(); template.setBeanFactory(context); Future future = template.asyncConvertAndSend("testChannel", "test"); - assertNull(future.get(10000, TimeUnit.MILLISECONDS)); + assertThat(future.get(10000, TimeUnit.MILLISECONDS)).isNull(); Message result = channel.receive(0); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); } @Test(expected = TimeoutException.class) @@ -151,10 +148,10 @@ public class AsyncMessagingTemplateTests { Future> result = template.asyncReceive(); sendMessageAfterDelay(channel, new GenericMessage("test"), 200); long start = System.currentTimeMillis(); - assertNotNull(result.get(100000, TimeUnit.MILLISECONDS)); + assertThat(result.get(100000, TimeUnit.MILLISECONDS)).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertEquals("test", result.get().getPayload()); - assertTrue(elapsed >= 200 - safety); + assertThat(result.get().getPayload()).isEqualTo("test"); + assertThat(elapsed >= 200 - safety).isTrue(); } @Test @@ -164,10 +161,10 @@ public class AsyncMessagingTemplateTests { Future> result = template.asyncReceive(channel); sendMessageAfterDelay(channel, new GenericMessage("test"), 200); long start = System.currentTimeMillis(); - assertNotNull(result.get(10000, TimeUnit.MILLISECONDS)); + assertThat(result.get(10000, TimeUnit.MILLISECONDS)).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertEquals("test", result.get().getPayload()); - assertTrue(elapsed >= 200 - safety); + assertThat(result.get().getPayload()).isEqualTo("test"); + assertThat(elapsed >= 200 - safety).isTrue(); } @Test @@ -181,11 +178,11 @@ public class AsyncMessagingTemplateTests { Future> result = template.asyncReceive("testChannel"); sendMessageAfterDelay(channel, new GenericMessage("test"), 200); long start = System.currentTimeMillis(); - assertNotNull(result.get(10000, TimeUnit.MILLISECONDS)); + assertThat(result.get(10000, TimeUnit.MILLISECONDS)).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("test", result.get().getPayload()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get().getPayload()).isEqualTo("test"); } @Test(expected = TimeoutException.class) @@ -203,11 +200,11 @@ public class AsyncMessagingTemplateTests { Future result = template.asyncReceiveAndConvert(); sendMessageAfterDelay(channel, new GenericMessage("test"), 200); long start = System.currentTimeMillis(); - assertNotNull(result.get(10000, TimeUnit.MILLISECONDS)); + assertThat(result.get(10000, TimeUnit.MILLISECONDS)).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertEquals("test", result.get()); + assertThat(result.get()).isEqualTo("test"); - assertTrue(elapsed >= 200 - safety); + assertThat(elapsed >= 200 - safety).isTrue(); } @Test @@ -217,11 +214,11 @@ public class AsyncMessagingTemplateTests { Future result = template.asyncReceiveAndConvert(channel); sendMessageAfterDelay(channel, new GenericMessage("test"), 200); long start = System.currentTimeMillis(); - assertNotNull(result.get(10000, TimeUnit.MILLISECONDS)); + assertThat(result.get(10000, TimeUnit.MILLISECONDS)).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertEquals("test", result.get()); + assertThat(result.get()).isEqualTo("test"); - assertTrue(elapsed >= 200 - safety); + assertThat(elapsed >= 200 - safety).isTrue(); } @Test @@ -235,11 +232,11 @@ public class AsyncMessagingTemplateTests { Future result = template.asyncReceiveAndConvert("testChannel"); sendMessageAfterDelay(channel, new GenericMessage("test"), 200); long start = System.currentTimeMillis(); - assertNotNull(result.get(10000, TimeUnit.MILLISECONDS)); + assertThat(result.get(10000, TimeUnit.MILLISECONDS)).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("test", result.get()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get()).isEqualTo("test"); } @Test(expected = TimeoutException.class) @@ -257,10 +254,10 @@ public class AsyncMessagingTemplateTests { template.setDefaultDestination(channel); long start = System.currentTimeMillis(); Future> result = template.asyncSendAndReceive(MessageBuilder.withPayload("test").build()); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); + assertThat(elapsed >= 200 - safety).isTrue(); } @Test @@ -270,11 +267,11 @@ public class AsyncMessagingTemplateTests { AsyncMessagingTemplate template = new AsyncMessagingTemplate(); long start = System.currentTimeMillis(); Future> result = template.asyncSendAndReceive(channel, MessageBuilder.withPayload("test").build()); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("TEST", result.get().getPayload()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get().getPayload()).isEqualTo("TEST"); } @Test @@ -288,11 +285,11 @@ public class AsyncMessagingTemplateTests { template.setBeanFactory(context); long start = System.currentTimeMillis(); Future> result = template.asyncSendAndReceive("testChannel", MessageBuilder.withPayload("test").build()); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("TEST", result.get().getPayload()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get().getPayload()).isEqualTo("TEST"); } @Test @@ -303,11 +300,11 @@ public class AsyncMessagingTemplateTests { template.setDefaultDestination(channel); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive("test"); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("TEST", result.get()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get()).isEqualTo("TEST"); } @Test @@ -317,11 +314,11 @@ public class AsyncMessagingTemplateTests { AsyncMessagingTemplate template = new AsyncMessagingTemplate(); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive(channel, "test"); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("TEST", result.get()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get()).isEqualTo("TEST"); } @Test @@ -335,11 +332,11 @@ public class AsyncMessagingTemplateTests { template.setBeanFactory(context); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive("testChannel", "test"); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("TEST", result.get()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get()).isEqualTo("TEST"); } @Test @@ -350,11 +347,11 @@ public class AsyncMessagingTemplateTests { template.setDefaultDestination(channel); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive(123, new TestMessagePostProcessor()); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("123-bar", result.get()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get()).isEqualTo("123-bar"); } @Test @@ -364,11 +361,11 @@ public class AsyncMessagingTemplateTests { AsyncMessagingTemplate template = new AsyncMessagingTemplate(); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive(channel, "test", new TestMessagePostProcessor()); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("TEST-bar", result.get()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get()).isEqualTo("TEST-bar"); } @Test @@ -382,11 +379,11 @@ public class AsyncMessagingTemplateTests { template.setBeanFactory(context); long start = System.currentTimeMillis(); Future result = template.asyncConvertSendAndReceive("testChannel", "test", new TestMessagePostProcessor()); - assertNotNull(result.get()); + assertThat(result.get()).isNotNull(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200 - safety); - assertEquals("TEST-bar", result.get()); + assertThat(elapsed >= 200 - safety).isTrue(); + assertThat(result.get()).isEqualTo("TEST-bar"); } @Test(expected = TimeoutException.class) @@ -408,7 +405,7 @@ public class AsyncMessagingTemplateTests { Future> result = template.asyncSendAndReceive(MessageBuilder.withPayload("test").build()); try { result.get(10, TimeUnit.SECONDS); - fail(); + fail("ExecutionException expected"); } catch (ExecutionException e) { throw e.getCause(); @@ -427,7 +424,7 @@ public class AsyncMessagingTemplateTests { Thread.sleep(200); result.cancel(true); result.get(); - fail(); + fail("ExecutionException expected"); } catch (ExecutionException e) { Assert.isTrue(handler.interrupted, "handler should have been interrupted"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java index 4306468b7c..f872527601 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.core; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Properties; @@ -47,15 +41,15 @@ public class MessageHistoryTests { @Test public void addComponents() { GenericMessage original = new GenericMessage("foo"); - assertNull(MessageHistory.read(original)); + assertThat(MessageHistory.read(original)).isNull(); Message result1 = MessageHistory.write(original, new TestComponent(1)); MessageHistory history1 = MessageHistory.read(result1); - assertNotNull(history1); - assertEquals("testComponent-1", history1.toString()); + assertThat(history1).isNotNull(); + assertThat(history1.toString()).isEqualTo("testComponent-1"); Message result2 = MessageHistory.write(result1, new TestComponent(2)); MessageHistory history2 = MessageHistory.read(result2); - assertNotNull(history2); - assertEquals("testComponent-1,testComponent-2", history2.toString()); + assertThat(history2).isNotNull(); + assertThat(history2.toString()).isEqualTo("testComponent-1,testComponent-2"); } @Test(expected = UnsupportedOperationException.class) @@ -68,64 +62,64 @@ public class MessageHistoryTests { @Test public void testCorrectMutableMessageAfterWrite() { MutableMessage original = new MutableMessage<>("foo"); - assertNull(MessageHistory.read(original)); + assertThat(MessageHistory.read(original)).isNull(); Message result1 = MessageHistory.write(original, new TestComponent(1)); - assertThat(result1, instanceOf(MutableMessage.class)); - assertSame(original, result1); + assertThat(result1).isInstanceOf(MutableMessage.class); + assertThat(result1).isSameAs(original); MessageHistory history1 = MessageHistory.read(result1); - assertNotNull(history1); - assertEquals("testComponent-1", history1.toString()); + assertThat(history1).isNotNull(); + assertThat(history1.toString()).isEqualTo("testComponent-1"); Message result2 = MessageHistory.write(result1, new TestComponent(2)); - assertSame(original, result2); + assertThat(result2).isSameAs(original); MessageHistory history2 = MessageHistory.read(result2); - assertNotNull(history2); - assertEquals("testComponent-1,testComponent-2", history2.toString()); + assertThat(history2).isNotNull(); + assertThat(history2.toString()).isEqualTo("testComponent-1,testComponent-2"); } @Test public void testCorrectErrorMessageAfterWrite() { RuntimeException payload = new RuntimeException(); ErrorMessage original = new ErrorMessage(payload); - assertNull(MessageHistory.read(original)); + assertThat(MessageHistory.read(original)).isNull(); Message result1 = MessageHistory.write(original, new TestComponent(1)); - assertThat(result1, instanceOf(ErrorMessage.class)); - assertNotSame(original, result1); - assertSame(original.getPayload(), result1.getPayload()); + assertThat(result1).isInstanceOf(ErrorMessage.class); + assertThat(result1).isNotSameAs(original); + assertThat(result1.getPayload()).isSameAs(original.getPayload()); MessageHistory history1 = MessageHistory.read(result1); - assertNotNull(history1); - assertEquals("testComponent-1", history1.toString()); + assertThat(history1).isNotNull(); + assertThat(history1.toString()).isEqualTo("testComponent-1"); Message result2 = MessageHistory.write(result1, new TestComponent(2)); - assertThat(result2, instanceOf(ErrorMessage.class)); - assertNotSame(original, result2); - assertNotSame(result1, result2); - assertSame(original.getPayload(), result2.getPayload()); + assertThat(result2).isInstanceOf(ErrorMessage.class); + assertThat(result2).isNotSameAs(original); + assertThat(result2).isNotSameAs(result1); + assertThat(result2.getPayload()).isSameAs(original.getPayload()); MessageHistory history2 = MessageHistory.read(result2); - assertNotNull(history2); - assertEquals("testComponent-1,testComponent-2", history2.toString()); + assertThat(history2).isNotNull(); + assertThat(history2.toString()).isEqualTo("testComponent-1,testComponent-2"); } @Test public void testCorrectAdviceMessageAfterWrite() { Message inputMessage = new GenericMessage<>("input"); AdviceMessage original = new AdviceMessage<>("foo", inputMessage); - assertNull(MessageHistory.read(original)); + assertThat(MessageHistory.read(original)).isNull(); Message result1 = MessageHistory.write(original, new TestComponent(1)); - assertThat(result1, instanceOf(AdviceMessage.class)); - assertNotSame(original, result1); - assertSame(original.getPayload(), result1.getPayload()); - assertSame(original.getInputMessage(), ((AdviceMessage) result1).getInputMessage()); + assertThat(result1).isInstanceOf(AdviceMessage.class); + assertThat(result1).isNotSameAs(original); + assertThat(result1.getPayload()).isSameAs(original.getPayload()); + assertThat(((AdviceMessage) result1).getInputMessage()).isSameAs(original.getInputMessage()); MessageHistory history1 = MessageHistory.read(result1); - assertNotNull(history1); - assertEquals("testComponent-1", history1.toString()); + assertThat(history1).isNotNull(); + assertThat(history1.toString()).isEqualTo("testComponent-1"); Message result2 = MessageHistory.write(result1, new TestComponent(2)); - assertThat(result2, instanceOf(AdviceMessage.class)); - assertNotSame(original, result2); - assertSame(original.getPayload(), result2.getPayload()); - assertSame(original.getInputMessage(), ((AdviceMessage) result2).getInputMessage()); - assertNotSame(result1, result2); + assertThat(result2).isInstanceOf(AdviceMessage.class); + assertThat(result2).isNotSameAs(original); + assertThat(result2.getPayload()).isSameAs(original.getPayload()); + assertThat(((AdviceMessage) result2).getInputMessage()).isSameAs(original.getInputMessage()); + assertThat(result2).isNotSameAs(result1); MessageHistory history2 = MessageHistory.read(result2); - assertNotNull(history2); - assertEquals("testComponent-1,testComponent-2", history2.toString()); + assertThat(history2).isNotNull(); + assertThat(history2.toString()).isEqualTo("testComponent-1,testComponent-2"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java index 6a91a2e004..e8c57f1189 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.core; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; @@ -178,7 +178,7 @@ public class MessageIdGenerationTests { private void assertDestroy() throws Exception { Field idGenField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator"); ReflectionUtils.makeAccessible(idGenField); - assertNull("the idGenerator field has not been properly reset to null", idGenField.get(null)); + assertThat(idGenField.get(null)).as("the idGenerator field has not been properly reset to null").isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/AggregateMessageDeliveryExceptionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/AggregateMessageDeliveryExceptionTests.java index 4a789529dd..ff74d0a635 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/AggregateMessageDeliveryExceptionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/AggregateMessageDeliveryExceptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.dispatcher; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.List; @@ -62,14 +60,14 @@ public class AggregateMessageDeliveryExceptionTests { @Test public void shouldShowOriginalExceptionsInMessage() { - assertThat(exception.getMessage(), containsString("first problem")); - assertThat(exception.getMessage(), containsString("second problem")); - assertThat(exception.getMessage(), containsString("third problem")); + assertThat(exception.getMessage()).contains("first problem"); + assertThat(exception.getMessage()).contains("second problem"); + assertThat(exception.getMessage()).contains("third problem"); } @Test public void shouldShowFirstOriginalExceptionInCause() { - assertThat(this.exception.getCause(), is(this.firstProblem)); + assertThat(this.exception.getCause()).isEqualTo(this.firstProblem); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java index 5395841c4b..ad47163d66 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.dispatcher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; @@ -209,11 +208,11 @@ public class BroadcastingDispatcherTests { dispatcher.addHandler(target1); dispatcher.addHandler(target2); dispatcher.dispatch(new GenericMessage("test")); - assertEquals(2, messages.size()); - assertEquals(0, new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceSize()); - assertEquals(0, new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceSize()); + assertThat(messages.size()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceNumber()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceSize()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceNumber()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceSize()).isEqualTo(0); } @Test @@ -230,16 +229,16 @@ public class BroadcastingDispatcherTests { Message inputMessage = new GenericMessage("test"); Object originalId = inputMessage.getHeaders().getId(); dispatcher.dispatch(inputMessage); - assertEquals(3, messages.size()); - assertEquals(1, new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceNumber()); - assertEquals(3, new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceSize()); - assertEquals(originalId, new IntegrationMessageHeaderAccessor(messages.get(0)).getCorrelationId()); - assertEquals(2, new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceNumber()); - assertEquals(3, new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceSize()); - assertEquals(originalId, new IntegrationMessageHeaderAccessor(messages.get(1)).getCorrelationId()); - assertEquals(3, new IntegrationMessageHeaderAccessor(messages.get(2)).getSequenceNumber()); - assertEquals(3, new IntegrationMessageHeaderAccessor(messages.get(2)).getSequenceSize()); - assertEquals(originalId, new IntegrationMessageHeaderAccessor(messages.get(2)).getCorrelationId()); + assertThat(messages.size()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(0)).getSequenceSize()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(0)).getCorrelationId()).isEqualTo(originalId); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceNumber()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(1)).getSequenceSize()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(1)).getCorrelationId()).isEqualTo(originalId); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(2)).getSequenceNumber()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(2)).getSequenceSize()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(messages.get(2)).getCorrelationId()).isEqualTo(originalId); } /** @@ -257,7 +256,7 @@ public class BroadcastingDispatcherTests { fail("Expected Exception"); } catch (MessagingException e) { - assertEquals(messageMock, e.getFailedMessage()); + assertThat(e.getFailedMessage()).isEqualTo(messageMock); } } @@ -278,7 +277,7 @@ public class BroadcastingDispatcherTests { fail("Expected Exception"); } catch (MessagingException e) { - assertEquals(dontReplaceThisMessage, e.getFailedMessage()); + assertThat(e.getFailedMessage()).isEqualTo(dontReplaceThisMessage); } } @@ -288,7 +287,7 @@ public class BroadcastingDispatcherTests { @Test public void testNoHandler() { dispatcher = new BroadcastingDispatcher(); - assertTrue(dispatcher.dispatch(messageMock)); + assertThat(dispatcher.dispatch(messageMock)).isTrue(); } /** @@ -297,7 +296,7 @@ public class BroadcastingDispatcherTests { @Test public void testNoHandlerWithExecutor() { dispatcher = new BroadcastingDispatcher(taskExecutorMock); - assertTrue(dispatcher.dispatch(messageMock)); + assertThat(dispatcher.dispatch(messageMock)).isTrue(); } /** @@ -312,7 +311,7 @@ public class BroadcastingDispatcherTests { fail("Expected Exception"); } catch (MessageDispatchingException exception) { - assertEquals(messageMock, exception.getFailedMessage()); + assertThat(exception.getFailedMessage()).isEqualTo(messageMock); } } @@ -328,7 +327,7 @@ public class BroadcastingDispatcherTests { fail("Expected Exception"); } catch (MessageDispatchingException exception) { - assertEquals(messageMock, exception.getFailedMessage()); + assertThat(exception.getFailedMessage()).isEqualTo(messageMock); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java index 269e504381..836782d515 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java @@ -16,9 +16,7 @@ package org.springframework.integration.dispatcher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.concurrent.CountDownLatch; @@ -48,7 +46,7 @@ public class FailOverDispatcherTests { final CountDownLatch latch = new CountDownLatch(1); dispatcher.addHandler(createConsumer(TestHandlers.countDownHandler(latch))); dispatcher.dispatch(new GenericMessage<>("test")); - assertTrue(latch.await(500, TimeUnit.MILLISECONDS)); + assertThat(latch.await(500, TimeUnit.MILLISECONDS)).isTrue(); } @Test @@ -60,8 +58,8 @@ public class FailOverDispatcherTests { dispatcher.addHandler(createConsumer(TestHandlers.countingCountDownHandler(counter1, latch))); dispatcher.addHandler(createConsumer(TestHandlers.countingCountDownHandler(counter2, latch))); dispatcher.dispatch(new GenericMessage<>("test")); - assertTrue(latch.await(500, TimeUnit.MILLISECONDS)); - assertEquals("only 1 handler should have received the message", 1, counter1.get() + counter2.get()); + assertThat(latch.await(500, TimeUnit.MILLISECONDS)).isTrue(); + assertThat(counter1.get() + counter2.get()).as("only 1 handler should have received the message").isEqualTo(1); } @Test @@ -77,7 +75,7 @@ public class FailOverDispatcherTests { catch (Exception e) { // ignore } - assertEquals("target should not have duplicate subscriptions", 1, counter.get()); + assertThat(counter.get()).as("target should not have duplicate subscriptions").isEqualTo(1); } @Test @@ -97,7 +95,7 @@ public class FailOverDispatcherTests { catch (Exception e) { // ignore } - assertEquals(2, counter.get()); + assertThat(counter.get()).isEqualTo(2); } @Test @@ -116,7 +114,7 @@ public class FailOverDispatcherTests { catch (Exception e) { // ignore } - assertEquals(3, counter.get()); + assertThat(counter.get()).isEqualTo(3); dispatcher.removeHandler(target2); try { dispatcher.dispatch(new GenericMessage<>("test2")); @@ -124,7 +122,7 @@ public class FailOverDispatcherTests { catch (Exception e) { // ignore } - assertEquals(5, counter.get()); + assertThat(counter.get()).isEqualTo(5); dispatcher.removeHandler(target1); try { dispatcher.dispatch(new GenericMessage<>("test3")); @@ -132,7 +130,7 @@ public class FailOverDispatcherTests { catch (Exception e) { // ignore } - assertEquals(6, counter.get()); + assertThat(counter.get()).isEqualTo(6); } @Test(expected = MessageDeliveryException.class) @@ -147,7 +145,7 @@ public class FailOverDispatcherTests { catch (Exception e) { // ignore } - assertEquals(1, counter.get()); + assertThat(counter.get()).isEqualTo(1); dispatcher.removeHandler(target); dispatcher.dispatch(new GenericMessage<>("test2")); } @@ -162,8 +160,8 @@ public class FailOverDispatcherTests { dispatcher.addHandler(target1); dispatcher.addHandler(target2); dispatcher.addHandler(target3); - assertTrue(dispatcher.dispatch(new GenericMessage<>("test"))); - assertEquals("only the first target should have been invoked", 1, counter.get()); + assertThat(dispatcher.dispatch(new GenericMessage<>("test"))).isTrue(); + assertThat(counter.get()).as("only the first target should have been invoked").isEqualTo(1); } @Test @@ -176,8 +174,8 @@ public class FailOverDispatcherTests { dispatcher.addHandler(target1); dispatcher.addHandler(target2); dispatcher.addHandler(target3); - assertTrue(dispatcher.dispatch(new GenericMessage<>("test"))); - assertEquals("first two targets should have been invoked", 2, counter.get()); + assertThat(dispatcher.dispatch(new GenericMessage<>("test"))).isTrue(); + assertThat(counter.get()).as("first two targets should have been invoked").isEqualTo(2); } @Test @@ -191,12 +189,12 @@ public class FailOverDispatcherTests { dispatcher.addHandler(target2); dispatcher.addHandler(target3); try { - assertFalse(dispatcher.dispatch(new GenericMessage<>("test"))); + assertThat(dispatcher.dispatch(new GenericMessage<>("test"))).isFalse(); } catch (Exception e) { // ignore } - assertEquals("each target should have been invoked", 3, counter.get()); + assertThat(counter.get()).as("each target should have been invoked").isEqualTo(3); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java index 8ccd2cffef..54186f344e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.dispatcher; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -42,11 +42,11 @@ public class OrderedAwareCopyOnWriteArraySetTests { setToTest.add("foo"); setToTest.add("bar"); setToTest.add("baz"); - assertEquals(3, setToTest.size()); + assertThat(setToTest.size()).isEqualTo(3); Object[] elements = setToTest.toArray(); - assertEquals("foo", elements[0]); - assertEquals("bar", elements[1]); - assertEquals("baz", elements[2]); + assertThat(elements[0]).isEqualTo("foo"); + assertThat(elements[1]).isEqualTo("bar"); + assertThat(elements[2]).isEqualTo("baz"); } /** * Tests that semantics of TreeSet(Comparator) were not broken. @@ -80,18 +80,18 @@ public class OrderedAwareCopyOnWriteArraySetTests { setToTest.add(o8); setToTest.add(o9); setToTest.add(o10); - assertEquals(10, setToTest.size()); + assertThat(setToTest.size()).isEqualTo(10); Object[] elements = setToTest.toArray(); - assertEquals(o7, elements[0]); - assertEquals(o8, elements[1]); - assertEquals(o2, elements[2]); - assertEquals(o3, elements[3]); - assertEquals(o4, elements[4]); - assertEquals(o10, elements[5]); - assertEquals(o1, elements[6]); - assertEquals(o9, elements[7]); - assertEquals(o5, elements[8]); - assertEquals(o6, elements[9]); + assertThat(elements[0]).isEqualTo(o7); + assertThat(elements[1]).isEqualTo(o8); + assertThat(elements[2]).isEqualTo(o2); + assertThat(elements[3]).isEqualTo(o3); + assertThat(elements[4]).isEqualTo(o4); + assertThat(elements[5]).isEqualTo(o10); + assertThat(elements[6]).isEqualTo(o1); + assertThat(elements[7]).isEqualTo(o9); + assertThat(elements[8]).isEqualTo(o5); + assertThat(elements[9]).isEqualTo(o6); } @SuppressWarnings("rawtypes") @@ -118,20 +118,20 @@ public class OrderedAwareCopyOnWriteArraySetTests { tempList.add(o8); tempList.add(o9); tempList.add(o10); - assertEquals(10, tempList.size()); + assertThat(tempList.size()).isEqualTo(10); OrderedAwareCopyOnWriteArraySet orderAwareSet = new OrderedAwareCopyOnWriteArraySet(); orderAwareSet.addAll(tempList); Object[] elements = orderAwareSet.toArray(); - assertEquals(o7, elements[0]); - assertEquals(o8, elements[1]); - assertEquals(o2, elements[2]); - assertEquals(o4, elements[3]); - assertEquals(o1, elements[4]); - assertEquals(o9, elements[5]); - assertEquals(o5, elements[6]); - assertEquals(o6, elements[7]); - assertEquals(o3, elements[8]); - assertEquals(o10, elements[9]); + assertThat(elements[0]).isEqualTo(o7); + assertThat(elements[1]).isEqualTo(o8); + assertThat(elements[2]).isEqualTo(o2); + assertThat(elements[3]).isEqualTo(o4); + assertThat(elements[4]).isEqualTo(o1); + assertThat(elements[5]).isEqualTo(o9); + assertThat(elements[6]).isEqualTo(o5); + assertThat(elements[7]).isEqualTo(o6); + assertThat(elements[8]).isEqualTo(o3); + assertThat(elements[9]).isEqualTo(o10); } @Test @@ -188,7 +188,7 @@ public class OrderedAwareCopyOnWriteArraySetTests { } - assertEquals(15, setToTest.size()); + assertThat(setToTest.size()).isEqualTo(15); } /** * Will test addAll operation including the removal and adding an object in the concurrent environment @@ -263,7 +263,7 @@ public class OrderedAwareCopyOnWriteArraySetTests { throw new RuntimeException(e); } Object[] elements = orderAwareSet.toArray(); - assertEquals(18, elements.length); + assertThat(elements.length).isEqualTo(18); } private static class Foo implements Ordered { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/PollingTransactionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/PollingTransactionTests.java index 0918d46140..434b40c8bb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/PollingTransactionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/PollingTransactionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.dispatcher; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.concurrent.Callable; @@ -67,15 +62,15 @@ public class PollingTransactionTests { TestTransactionManager txManager = (TestTransactionManager) context.getBean("txManager"); MessageChannel input = (MessageChannel) context.getBean("goodInput"); PollableChannel output = (PollableChannel) context.getBean("output"); - assertEquals(0, txManager.getCommitCount()); - assertEquals(0, txManager.getRollbackCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); + assertThat(txManager.getRollbackCount()).isEqualTo(0); context.getBean("goodService", Lifecycle.class).start(); input.send(new GenericMessage<>("test")); txManager.waitForCompletion(10000); Message message = output.receive(0); - assertNotNull(message); - assertEquals(1, txManager.getCommitCount()); - assertEquals(0, txManager.getRollbackCount()); + assertThat(message).isNotNull(); + assertThat(txManager.getCommitCount()).isEqualTo(1); + assertThat(txManager.getRollbackCount()).isEqualTo(0); context.close(); } @@ -87,28 +82,28 @@ public class PollingTransactionTests { PollingConsumer advisedPoller = context.getBean("advisedSa", PollingConsumer.class); List adviceChain = TestUtils.getPropertyValue(advisedPoller, "adviceChain", List.class); - assertEquals(4, adviceChain.size()); + assertThat(adviceChain.size()).isEqualTo(4); advisedPoller.start(); Callable pollingTask = TestUtils.getPropertyValue(advisedPoller, "pollingTask", Callable.class); - assertTrue("Poller is not Advised", pollingTask instanceof Advised); + assertThat(pollingTask instanceof Advised).as("Poller is not Advised").isTrue(); Advisor[] advisors = ((Advised) pollingTask).getAdvisors(); - assertEquals(4, advisors.length); + assertThat(advisors.length).isEqualTo(4); - assertThat("First advisor is not TX", advisors[0].getAdvice(), instanceOf(TransactionInterceptor.class)); + assertThat(advisors[0].getAdvice()).as("First advisor is not TX").isInstanceOf(TransactionInterceptor.class); TestTransactionManager txManager = (TestTransactionManager) context.getBean("txManager"); MessageChannel input = (MessageChannel) context.getBean("goodInputWithAdvice"); PollableChannel output = (PollableChannel) context.getBean("output"); - assertEquals(0, txManager.getCommitCount()); - assertEquals(0, txManager.getRollbackCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); + assertThat(txManager.getRollbackCount()).isEqualTo(0); input.send(new GenericMessage<>("test")); input.send(new GenericMessage<>("test2")); txManager.waitForCompletion(10000); Message message = output.receive(0); - assertNotNull(message); + assertThat(message).isNotNull(); message = output.receive(0); - assertNotNull(message); - assertEquals(0, txManager.getRollbackCount()); + assertThat(message).isNotNull(); + assertThat(txManager.getRollbackCount()).isEqualTo(0); context.close(); } @@ -119,17 +114,17 @@ public class PollingTransactionTests { TestTransactionManager txManager = (TestTransactionManager) context.getBean("txManager"); MessageChannel input = (MessageChannel) context.getBean("badInput"); PollableChannel output = (PollableChannel) context.getBean("output"); - assertEquals(0, txManager.getCommitCount()); - assertEquals(0, txManager.getRollbackCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); + assertThat(txManager.getRollbackCount()).isEqualTo(0); context.getBean("badService", Lifecycle.class).start(); input.send(new GenericMessage<>("test")); txManager.waitForCompletion(10000); Message message = output.receive(0); - assertNull(message); - assertEquals(0, txManager.getCommitCount()); - assertEquals(1, txManager.getRollbackCount()); + assertThat(message).isNull(); + assertThat(txManager.getCommitCount()).isEqualTo(0); + assertThat(txManager.getRollbackCount()).isEqualTo(1); context.close(); } @@ -140,13 +135,13 @@ public class PollingTransactionTests { TestTransactionManager txManager = (TestTransactionManager) context.getBean("txManager"); PollableChannel input = (PollableChannel) context.getBean("input"); PollableChannel output = (PollableChannel) context.getBean("output"); - assertEquals(0, txManager.getCommitCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); input.send(new GenericMessage<>("test")); Message reply = output.receive(10000); - assertNotNull(reply); + assertThat(reply).isNotNull(); txManager.waitForCompletion(10000); - assertEquals(1, txManager.getCommitCount()); - assertEquals(Propagation.REQUIRED.value(), txManager.getLastDefinition().getPropagationBehavior()); + assertThat(txManager.getCommitCount()).isEqualTo(1); + assertThat(txManager.getLastDefinition().getPropagationBehavior()).isEqualTo(Propagation.REQUIRED.value()); context.close(); } @@ -157,13 +152,13 @@ public class PollingTransactionTests { TestTransactionManager txManager = (TestTransactionManager) context.getBean("txManager"); PollableChannel input = (PollableChannel) context.getBean("input"); PollableChannel output = (PollableChannel) context.getBean("output"); - assertEquals(0, txManager.getCommitCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); input.send(new GenericMessage<>("test")); Message reply = output.receive(10000); - assertNotNull(reply); + assertThat(reply).isNotNull(); txManager.waitForCompletion(10000); - assertEquals(1, txManager.getCommitCount()); - assertEquals(Propagation.REQUIRES_NEW.value(), txManager.getLastDefinition().getPropagationBehavior()); + assertThat(txManager.getCommitCount()).isEqualTo(1); + assertThat(txManager.getLastDefinition().getPropagationBehavior()).isEqualTo(Propagation.REQUIRES_NEW.value()); context.close(); } @@ -174,12 +169,12 @@ public class PollingTransactionTests { TestTransactionManager txManager = (TestTransactionManager) context.getBean("txManager"); PollableChannel input = (PollableChannel) context.getBean("input"); PollableChannel output = (PollableChannel) context.getBean("output"); - assertEquals(0, txManager.getCommitCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); input.send(new GenericMessage<>("test")); Message reply = output.receive(10000); - assertNotNull(reply); - assertEquals(0, txManager.getCommitCount()); - assertNull(txManager.getLastDefinition()); + assertThat(reply).isNotNull(); + assertThat(txManager.getCommitCount()).isEqualTo(0); + assertThat(txManager.getLastDefinition()).isNull(); context.close(); } @@ -190,12 +185,12 @@ public class PollingTransactionTests { TestTransactionManager txManager = (TestTransactionManager) context.getBean("txManager"); PollableChannel input = (PollableChannel) context.getBean("input"); PollableChannel output = (PollableChannel) context.getBean("output"); - assertEquals(0, txManager.getCommitCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); input.send(new GenericMessage<>("test")); Message reply = output.receive(10000); - assertNotNull(reply); - assertEquals(0, txManager.getCommitCount()); - assertNull(txManager.getLastDefinition()); + assertThat(reply).isNotNull(); + assertThat(txManager.getCommitCount()).isEqualTo(0); + assertThat(txManager.getLastDefinition()).isNull(); context.close(); } @@ -207,16 +202,16 @@ public class PollingTransactionTests { PollableChannel input = (PollableChannel) context.getBean("input"); PollableChannel output = (PollableChannel) context.getBean("output"); PollableChannel errorChannel = (PollableChannel) context.getBean("errorChannel"); - assertEquals(0, txManager.getCommitCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); input.send(new GenericMessage<>("test")); Message errorMessage = errorChannel.receive(10000); - assertNotNull(errorMessage); + assertThat(errorMessage).isNotNull(); Object payload = errorMessage.getPayload(); - assertEquals(MessagingException.class, payload.getClass()); + assertThat(payload.getClass()).isEqualTo(MessagingException.class); MessagingException messagingException = (MessagingException) payload; - assertEquals(IllegalTransactionStateException.class, messagingException.getCause().getClass()); - assertNull(output.receive(0)); - assertEquals(0, txManager.getCommitCount()); + assertThat(messagingException.getCause().getClass()).isEqualTo(IllegalTransactionStateException.class); + assertThat(output.receive(0)).isNull(); + assertThat(txManager.getCommitCount()).isEqualTo(0); context.close(); } @@ -229,28 +224,28 @@ public class PollingTransactionTests { PollableChannel inputHandlerFail = (PollableChannel) context.getBean("inputHandlerFailure"); PollableChannel output = (PollableChannel) context.getBean("output"); PollableChannel errorChannel = (PollableChannel) context.getBean("errorChannel"); - assertEquals(0, txManager.getCommitCount()); + assertThat(txManager.getCommitCount()).isEqualTo(0); inputTxFail.send(new GenericMessage<>("commitFailureTest")); Message errorMessage = errorChannel.receive(20000); - assertNotNull(errorMessage); + assertThat(errorMessage).isNotNull(); Object payload = errorMessage.getPayload(); - assertEquals(MessagingException.class, payload.getClass()); + assertThat(payload.getClass()).isEqualTo(MessagingException.class); MessagingException messagingException = (MessagingException) payload; - assertEquals(IllegalTransactionStateException.class, messagingException.getCause().getClass()); - assertNotNull(messagingException.getFailedMessage()); - assertNotNull(output.receive(0)); - assertEquals(0, txManager.getCommitCount()); + assertThat(messagingException.getCause().getClass()).isEqualTo(IllegalTransactionStateException.class); + assertThat(messagingException.getFailedMessage()).isNotNull(); + assertThat(output.receive(0)).isNotNull(); + assertThat(txManager.getCommitCount()).isEqualTo(0); inputHandlerFail.send(new GenericMessage<>("handlerFailureTest")); errorMessage = errorChannel.receive(10000); - assertNotNull(errorMessage); + assertThat(errorMessage).isNotNull(); payload = errorMessage.getPayload(); - assertEquals(MessageHandlingException.class, payload.getClass()); + assertThat(payload.getClass()).isEqualTo(MessageHandlingException.class); messagingException = (MessageHandlingException) payload; - assertEquals(RuntimeException.class, messagingException.getCause().getClass()); - assertNotNull(messagingException.getFailedMessage()); - assertNull(output.receive(0)); - assertEquals(0, txManager.getCommitCount()); + assertThat(messagingException.getCause().getClass()).isEqualTo(RuntimeException.class); + assertThat(messagingException.getFailedMessage()).isNotNull(); + assertThat(output.receive(0)).isNull(); + assertThat(txManager.getCommitCount()).isEqualTo(0); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java index 84ff8ce0cc..1554903bd5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.dispatcher; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -108,8 +107,8 @@ public class RoundRobinDispatcherConcurrentTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); - assertFalse("not all messages were accepted", failed.get()); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(failed.get()).as("not all messages were accepted").isFalse(); verify(handler1, times(TOTAL_EXECUTIONS / 4)).handleMessage(message); verify(handler2, times(TOTAL_EXECUTIONS / 4)).handleMessage(message); verify(handler3, times(TOTAL_EXECUTIONS / 4)).handleMessage(message); @@ -142,7 +141,7 @@ public class RoundRobinDispatcherConcurrentTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); } @Test @@ -172,8 +171,8 @@ public class RoundRobinDispatcherConcurrentTests { executor.execute(messageSenderTask); } start.countDown(); - assertTrue(allDone.await(10, TimeUnit.SECONDS)); - assertFalse("not all messages were accepted", failed.get()); + assertThat(allDone.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(failed.get()).as("not all messages were accepted").isFalse(); verify(handler1, times(TOTAL_EXECUTIONS / 2)).handleMessage(message); verify(handler2, times(TOTAL_EXECUTIONS)).handleMessage(message); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherTests.java index d697f6ac44..9ffca587e8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.dispatcher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; @@ -117,7 +117,7 @@ public class RoundRobinDispatcherTests { fail("Expected Exception"); } catch (MessagingException e) { - assertEquals(message, e.getFailedMessage()); + assertThat(e.getFailedMessage()).isEqualTo(message); } } @@ -136,7 +136,7 @@ public class RoundRobinDispatcherTests { fail("Expected Exception"); } catch (MessagingException e) { - assertEquals(dontReplaceThisMessage, e.getFailedMessage()); + assertThat(e.getFailedMessage()).isEqualTo(dontReplaceThisMessage); } } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/TransactionalPollerWithMixedAopConfigTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/TransactionalPollerWithMixedAopConfigTests.java index 272ded4a12..50cee183c6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/TransactionalPollerWithMixedAopConfigTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/TransactionalPollerWithMixedAopConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.dispatcher; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -39,8 +39,8 @@ public class TransactionalPollerWithMixedAopConfigTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("TransactionalPollerWithMixedAopConfig-context.xml", this.getClass()); - assertTrue(!(context.getBean("foo") instanceof Advised)); - assertTrue(!(context.getBean("inputChannel") instanceof Advised)); + assertThat(!(context.getBean("foo") instanceof Advised)).isTrue(); + assertThat(!(context.getBean("inputChannel") instanceof Advised)).isTrue(); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java index 69cb3fd4f1..93a917344f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.dispatcher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -45,14 +44,14 @@ public class UnicastingDispatcherTests { SubscribableChannel errorChannel = context.getBean("errorChannel", SubscribableChannel.class); MessageHandler errorHandler = message -> { MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - assertTrue(message.getPayload() instanceof MessageDeliveryException); + assertThat(message.getPayload() instanceof MessageDeliveryException).isTrue(); replyChannel.send(new GenericMessage("reply")); }; errorChannel.subscribe(errorHandler); RequestReplyExchanger exchanger = context.getBean(RequestReplyExchanger.class); Message reply = (Message) exchanger.exchange(new GenericMessage("Hello")); - assertEquals("reply", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("reply"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/LambdaMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/LambdaMessageProcessorTests.java index 95769d749a..3e8dc9f547 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/LambdaMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/LambdaMessageProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,11 +16,9 @@ package org.springframework.integration.dsl; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -53,7 +51,7 @@ public class LambdaMessageProcessorTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e.getCause(), instanceOf(ArithmeticException.class)); + assertThat(e.getCause()).isInstanceOf(ArithmeticException.class); } } @@ -70,7 +68,7 @@ public class LambdaMessageProcessorTests { lmp.setBeanFactory(mock(BeanFactory.class)); GenericMessage testMessage = new GenericMessage<>("foo"); Object result = lmp.processMessage(testMessage); - assertSame(testMessage, result); + assertThat(result).isSameAs(testMessage); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/correlation/CorrelationHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/correlation/CorrelationHandlerTests.java index 9a1a36ee8a..646e1f3a2b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/correlation/CorrelationHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/correlation/CorrelationHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,12 +16,7 @@ package org.springframework.integration.dsl.correlation; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; @@ -106,11 +101,11 @@ public class CorrelationHandlerTests { for (int i = 0; i < 12; i++) { Message receive = replyChannel.receive(2000); - assertNotNull(receive); - assertFalse(receive.getHeaders().containsKey("foo")); - assertTrue(receive.getHeaders().containsKey("FOO")); - assertEquals("BAR", receive.getHeaders().get("FOO")); - assertEquals(i + 1, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getHeaders().containsKey("foo")).isFalse(); + assertThat(receive.getHeaders().containsKey("FOO")).isTrue(); + assertThat(receive.getHeaders().get("FOO")).isEqualTo("BAR"); + assertThat(receive.getPayload()).isEqualTo(i + 1); } } @@ -124,13 +119,13 @@ public class CorrelationHandlerTests { .build()); Message receive = replyChannel.receive(2000); - assertNotNull(receive); - assertThat(receive.getPayload(), instanceOf(List.class)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isInstanceOf(List.class); @SuppressWarnings("unchecked") List result = (List) receive.getPayload(); for (int i = 0; i < payload.size(); i++) { - assertThat(result.get(i), instanceOf(TextNode.class)); - assertEquals(TextNode.valueOf(payload.get(i)), result.get(i)); + assertThat(result.get(i)).isInstanceOf(TextNode.class); + assertThat(result.get(i)).isEqualTo(TextNode.valueOf(payload.get(i))); } } @@ -139,8 +134,8 @@ public class CorrelationHandlerTests { this.subscriberAggregateFlowInput.send(new GenericMessage<>("test")); Message receive1 = this.subscriberAggregateResult.receive(10000); - assertNotNull(receive1); - assertEquals("Hello World!", receive1.getPayload()); + assertThat(receive1).isNotNull(); + assertThat(receive1.getPayload()).isEqualTo("Hello World!"); } @@ -151,8 +146,8 @@ public class CorrelationHandlerTests { Message suspending = MessageBuilder.withPayload("foo").setHeader(BARRIER, "foo").build(); this.barrierFlowInput.send(suspending); Message out = this.barrierResults.receive(10000); - assertNotNull(out); - assertEquals("bar", out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("bar"); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java index 8610d18fbb..9bbbe83435 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java @@ -16,16 +16,8 @@ package org.springframework.integration.dsl.flows; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.Serializable; import java.util.concurrent.CountDownLatch; @@ -180,20 +172,20 @@ public class IntegrationFlowTests { @Test public void testWithSupplierMessageSourceImpliedPoller() { - assertEquals("FOO", this.suppliedChannel.receive(10000).getPayload()); + assertThat(this.suppliedChannel.receive(10000).getPayload()).isEqualTo("FOO"); } @Test public void testWithSupplierMessageSourceProvidedPoller() { - assertEquals("FOO", this.suppliedChannel2.receive(10000).getPayload()); + assertThat(this.suppliedChannel2.receive(10000).getPayload()).isEqualTo("FOO"); } @Test public void testDirectFlow() { - assertTrue(this.beanFactory.containsBean("filter")); - assertTrue(this.beanFactory.containsBean("filter.handler")); - assertTrue(this.beanFactory.containsBean("expressionFilter")); - assertTrue(this.beanFactory.containsBean("expressionFilter.handler")); + assertThat(this.beanFactory.containsBean("filter")).isTrue(); + assertThat(this.beanFactory.containsBean("filter.handler")).isTrue(); + assertThat(this.beanFactory.containsBean("expressionFilter")).isTrue(); + assertThat(this.beanFactory.containsBean("expressionFilter.handler")).isTrue(); QueueChannel replyChannel = new QueueChannel(); Message message = MessageBuilder.withPayload("100").setReplyChannel(replyChannel).build(); try { @@ -201,9 +193,9 @@ public class IntegrationFlowTests { fail("Expected MessageDispatchingException"); } catch (Exception e) { - assertThat(e, instanceOf(MessageDeliveryException.class)); - assertThat(e.getCause(), instanceOf(MessageDispatchingException.class)); - assertThat(e.getMessage(), containsString("Dispatcher has no subscribers")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getCause()).isInstanceOf(MessageDispatchingException.class); + assertThat(e.getMessage()).contains("Dispatcher has no subscribers"); } this.controlBus.send("@payloadSerializingTransformer.start()"); @@ -213,19 +205,19 @@ public class IntegrationFlowTests { this.inputChannel.send(message); Message reply = replyChannel.receive(10000); - assertNotNull(reply); - assertEquals(200, reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo(200); Message successMessage = this.successChannel.receive(10000); - assertNotNull(successMessage); - assertEquals(100, successMessage.getPayload()); + assertThat(successMessage).isNotNull(); + assertThat(successMessage.getPayload()).isEqualTo(100); - assertTrue(used.get()); + assertThat(used.get()).isTrue(); this.inputChannel.send(new GenericMessage(1000)); Message discarded = this.discardChannel.receive(10000); - assertNotNull(discarded); - assertEquals("Discarded: 1000", discarded.getPayload()); + assertThat(discarded).isNotNull(); + assertThat(discarded.getPayload()).isEqualTo("Discarded: 1000"); } @Test @@ -233,27 +225,27 @@ public class IntegrationFlowTests { GenericMessage message = new GenericMessage<>("test"); this.bridgeFlowInput.send(message); Message reply = this.bridgeFlowOutput.receive(10000); - assertNotNull(reply); - assertEquals("test", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("test"); - assertTrue(this.beanFactory.containsBean("bridgeFlow2.channel#0")); - assertThat(this.beanFactory.getBean("bridgeFlow2.channel#0"), instanceOf(FixedSubscriberChannel.class)); + assertThat(this.beanFactory.containsBean("bridgeFlow2.channel#0")).isTrue(); + assertThat(this.beanFactory.getBean("bridgeFlow2.channel#0")).isInstanceOf(FixedSubscriberChannel.class); try { this.bridgeFlow2Input.send(message); fail("Expected MessageDispatchingException"); } catch (Exception e) { - assertThat(e, instanceOf(MessageDeliveryException.class)); - assertThat(e.getCause(), instanceOf(MessageDispatchingException.class)); - assertThat(e.getMessage(), containsString("Dispatcher has no subscribers")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getCause()).isInstanceOf(MessageDispatchingException.class); + assertThat(e.getMessage()).contains("Dispatcher has no subscribers"); } this.controlBus.send("@bridge.start()"); this.bridgeFlow2Input.send(message); reply = this.bridgeFlow2Output.receive(10000); - assertNotNull(reply); - assertEquals("test", reply.getPayload()); - assertTrue(this.delayedAdvice.getInvoked()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("test"); + assertThat(this.delayedAdvice.getInvoked()).isTrue(); } @Test @@ -264,9 +256,9 @@ public class IntegrationFlowTests { fail("BeanCreationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanCreationException.class)); - assertThat(e.getMessage(), containsString("'.fixedSubscriberChannel()' " + - "can't be the last EIP-method in the 'IntegrationFlow' definition")); + assertThat(e).isInstanceOf(BeanCreationException.class); + assertThat(e.getMessage()).contains("'.fixedSubscriberChannel()' " + + "can't be the last EIP-method in the 'IntegrationFlow' definition"); } finally { if (context != null) { @@ -283,14 +275,14 @@ public class IntegrationFlowTests { .build(); this.methodInvokingInput.send(message); Message receive = replyChannel.receive(10000); - assertNotNull(receive); - assertEquals("Hello World and world", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("Hello World and world"); } @Test public void testLambdas() { - assertTrue(this.beanFactory.containsBean("lambdasFlow.filter#0")); - assertTrue(this.beanFactory.containsBean("lambdasFlow.transformer#0")); + assertThat(this.beanFactory.containsBean("lambdasFlow.filter#0")).isTrue(); + assertThat(this.beanFactory.containsBean("lambdasFlow.transformer#0")).isTrue(); QueueChannel replyChannel = new QueueChannel(); Message message = MessageBuilder.withPayload("World".getBytes()) @@ -298,15 +290,15 @@ public class IntegrationFlowTests { .build(); this.lambdasInput.send(message); Message receive = replyChannel.receive(10000); - assertNotNull(receive); - assertEquals("Hello World", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("Hello World"); message = MessageBuilder.withPayload("Spring") .setHeader(MessageHeaders.REPLY_CHANNEL, replyChannel) .build(); this.lambdasInput.send(message); - assertNull(replyChannel.receive(10)); + assertThat(replyChannel.receive(10)).isNull(); } @@ -319,11 +311,11 @@ public class IntegrationFlowTests { this.claimCheckInput.send(message); Message receive = replyChannel.receive(10000); - assertNotNull(receive); - assertSame(message, receive); + assertThat(receive).isNotNull(); + assertThat(receive).isSameAs(message); - assertEquals(1, this.messageStore.getMessageCount()); - assertSame(message, this.messageStore.getMessage(message.getHeaders().getId())); + assertThat(this.messageStore.getMessageCount()).isEqualTo(1); + assertThat(this.messageStore.getMessage(message.getHeaders().getId())).isSameAs(message); } @Autowired @@ -356,37 +348,37 @@ public class IntegrationFlowTests { this.tappedChannel1.send(new GenericMessage<>("foo")); this.tappedChannel1.send(new GenericMessage<>("bar")); Message out = this.tapChannel.receive(10000); - assertNotNull(out); - assertEquals("foo", out.getPayload()); - assertNull(this.tapChannel.receive(0)); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("foo"); + assertThat(this.tapChannel.receive(0)).isNull(); this.tappedChannel2.send(new GenericMessage<>("foo")); this.tappedChannel2.send(new GenericMessage<>("bar")); out = this.tapChannel.receive(10000); - assertNotNull(out); - assertEquals("foo", out.getPayload()); - assertNull(this.tapChannel.receive(0)); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("foo"); + assertThat(this.tapChannel.receive(0)).isNull(); this.tappedChannel3.send(new GenericMessage<>("foo")); this.tappedChannel3.send(new GenericMessage<>("bar")); out = this.tapChannel.receive(10000); - assertNotNull(out); - assertEquals("foo", out.getPayload()); - assertNull(this.tapChannel.receive(0)); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("foo"); + assertThat(this.tapChannel.receive(0)).isNull(); this.tappedChannel4.send(new GenericMessage<>("foo")); this.tappedChannel4.send(new GenericMessage<>("bar")); out = this.tapChannel.receive(10000); - assertNotNull(out); - assertEquals("foo", out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("foo"); out = this.tapChannel.receive(10000); - assertNotNull(out); - assertEquals("bar", out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("bar"); this.tappedChannel5.send(new GenericMessage<>("foo")); out = this.wireTapSubflowResult.receive(10000); - assertNotNull(out); - assertEquals("FOO", out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("FOO"); } @Autowired @@ -410,15 +402,15 @@ public class IntegrationFlowTests { this.subscribersFlowInput.send(new GenericMessage<>(2)); Message receive1 = this.subscriber1Results.receive(10000); - assertNotNull(receive1); - assertEquals(1, receive1.getPayload()); + assertThat(receive1).isNotNull(); + assertThat(receive1.getPayload()).isEqualTo(1); Message receive2 = this.subscriber2Results.receive(10000); - assertNotNull(receive2); - assertEquals(4, receive2.getPayload()); + assertThat(receive2).isNotNull(); + assertThat(receive2.getPayload()).isEqualTo(4); Message receive3 = this.subscriber3Results.receive(10000); - assertNotNull(receive3); - assertEquals(6, receive3.getPayload()); + assertThat(receive3).isNotNull(); + assertThat(receive3.getPayload()).isEqualTo(6); } @Autowired @@ -427,7 +419,7 @@ public class IntegrationFlowTests { @Test public void testReplyChannelFromReplyMessage() { - assertEquals("foo", this.errorRecovererFlowGateway.apply("foo")); + assertThat(this.errorRecovererFlowGateway.apply("foo")).isEqualTo("foo"); } @Autowired @@ -447,9 +439,9 @@ public class IntegrationFlowTests { this.dedicatedQueueChannel.send(new GenericMessage<>("foo")); - assertTrue(resultLatch.await(10, TimeUnit.SECONDS)); + assertThat(resultLatch.await(10, TimeUnit.SECONDS)).isTrue(); - assertEquals("dedicatedTaskScheduler-1", threadNameReference.get()); + assertThat(threadNameReference.get()).isEqualTo("dedicatedTaskScheduler-1"); } @Autowired @@ -464,7 +456,7 @@ public class IntegrationFlowTests { this.flowWithNullChannelInput.send(new GenericMessage<>("foo")); - assertEquals(1, this.nullChannel.getSendCount()); + assertThat(this.nullChannel.getSendCount()).isEqualTo(1); this.nullChannel.setCountsEnabled(false); } @@ -483,9 +475,9 @@ public class IntegrationFlowTests { this.flowWithLocalNullChannelInput.send(new GenericMessage<>("foo")); - assertEquals(1, this.localNullChannel.getSendCount()); + assertThat(this.localNullChannel.getSendCount()).isEqualTo(1); - assertNotSame(this.nullChannel, this.localNullChannel); + assertThat(this.localNullChannel).isNotSameAs(this.nullChannel); } @@ -497,8 +489,8 @@ public class IntegrationFlowTests { @Test public void testPrototypeIsNotOverridden() { - assertNotSame(this.flow1WithPrototypeHandlerConsumer.getHandler(), - this.flow2WithPrototypeHandlerConsumer.getHandler()); + assertThat(this.flow2WithPrototypeHandlerConsumer.getHandler()) + .isNotSameAs(this.flow1WithPrototypeHandlerConsumer.getHandler()); } @MessagingGateway @@ -718,7 +710,7 @@ public class IntegrationFlowTests { @ServiceActivator(inputChannel = "publishSubscribeChannel") public void handle(Object payload) { - assertEquals(100, payload); + assertThat(payload).isEqualTo(100); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java index 3226f9df8d..18a18e319b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,11 +16,7 @@ package org.springframework.integration.dsl.flowservices; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.Collections; @@ -90,25 +86,25 @@ public class FlowServiceTests { @Test public void testFlowServiceAndLogAsLastNoError() throws Exception { - assertNotNull(this.myFlow); - assertTrue(AopUtils.isAopProxy(this.myFlow)); - assertThat(this.myFlow, instanceOf(Advised.class)); - assertThat(this.myFlow, instanceOf(Ordered.class)); - assertThat(this.myFlow, instanceOf(SmartLifecycle.class)); + assertThat(this.myFlow).isNotNull(); + assertThat(AopUtils.isAopProxy(this.myFlow)).isTrue(); + assertThat(this.myFlow).isInstanceOf(Advised.class); + assertThat(this.myFlow).isInstanceOf(Ordered.class); + assertThat(this.myFlow).isInstanceOf(SmartLifecycle.class); this.input.send(MessageBuilder.withPayload("foo").build()); MyFlow myFlow = (MyFlow) ((Advised) this.myFlow).getTargetSource().getTarget(); Object result = myFlow.resultOverLoggingHandler.get(); - assertNotNull(result); - assertEquals("FOO", result); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("FOO"); } @Test public void testFlowAdapterService() { Message receive = this.myFlowAdapterOutput.receive(10000); - assertNotNull(receive); - assertEquals("bar:FOO", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("bar:FOO"); } @@ -121,8 +117,8 @@ public class FlowServiceTests { QueueChannel replyChannel = new QueueChannel(); this.testGatewayInput.send(MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build()); Message message = replyChannel.receive(10000); - assertNotNull(message); - assertEquals("FOO", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("FOO"); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java index db332bf3a4..cee083953b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,19 +16,9 @@ package org.springframework.integration.dsl.manualflow; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.lessThan; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import java.util.Arrays; import java.util.Date; @@ -43,7 +33,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -150,23 +139,23 @@ public class ManualFlowTests { .channel(channel) .get(); IntegrationFlowRegistration flowRegistration = this.integrationFlowContext.registration(flow).register(); - assertTrue(started.get()); + assertThat(started.get()).isTrue(); Set replyProducers = TestUtils.getPropertyValue(flowBuilder, "REFERENCED_REPLY_PRODUCERS", Set.class); - assertTrue(replyProducers.contains(bridgeHandler)); + assertThat(replyProducers.contains(bridgeHandler)).isTrue(); - assertNotNull(this.integrationManagementConfigurer.getChannelMetrics("channel")); - assertNotNull(this.integrationManagementConfigurer.getHandlerMetrics("bridge")); + assertThat(this.integrationManagementConfigurer.getChannelMetrics("channel")).isNotNull(); + assertThat(this.integrationManagementConfigurer.getHandlerMetrics("bridge")).isNotNull(); flowRegistration.destroy(); - assertFalse(replyProducers.contains(bridgeHandler)); + assertThat(replyProducers.contains(bridgeHandler)).isFalse(); - assertNull(this.integrationManagementConfigurer.getChannelMetrics("channel")); - assertNull(this.integrationManagementConfigurer.getHandlerMetrics("bridge")); + assertThat(this.integrationManagementConfigurer.getChannelMetrics("channel")).isNull(); + assertThat(this.integrationManagementConfigurer.getHandlerMetrics("bridge")).isNull(); } @Test @@ -194,7 +183,7 @@ public class ManualFlowTests { .channel(channel) .get(); IntegrationFlowRegistration flowRegistration = this.integrationFlowContext.registration(flow).register(); - assertTrue(started.get()); + assertThat(started.get()).isTrue(); flowRegistration.destroy(); } @@ -225,34 +214,34 @@ public class ManualFlowTests { BeanFactoryHandler bean = this.beanFactory.getBean(flowRegistrationId + BeanFactoryHandler.class.getName() + "#0", BeanFactoryHandler.class); - assertSame(additionalBean, bean); - assertSame(this.beanFactory, bean.beanFactory); + assertThat(bean).isSameAs(additionalBean); + assertThat(bean.beanFactory).isSameAs(this.beanFactory); bean = this.beanFactory.getBean(flowRegistrationId + "." + "anId.handler", BeanFactoryHandler.class); MessagingTemplate messagingTemplate = flowRegistration.getMessagingTemplate(); messagingTemplate.setReceiveTimeout(10000); - assertEquals("Hello, FOO", messagingTemplate.convertSendAndReceive("foo", String.class)); + assertThat(messagingTemplate.convertSendAndReceive("foo", String.class)).isEqualTo("Hello, FOO"); - assertEquals("Hello, BAR", messagingTemplate.convertSendAndReceive("bar", String.class)); + assertThat(messagingTemplate.convertSendAndReceive("bar", String.class)).isEqualTo("Hello, BAR"); try { messagingTemplate.receive(); fail("UnsupportedOperationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(UnsupportedOperationException.class)); - assertThat(e.getMessage(), containsString("The 'receive()/receiveAndConvert()' isn't supported")); + assertThat(e).isInstanceOf(UnsupportedOperationException.class); + assertThat(e.getMessage()).contains("The 'receive()/receiveAndConvert()' isn't supported"); } - assertThat(this.beanFactory.getBeanNamesForType(MessageTransformingHandler.class)[0], - startsWith(flowId + ".")); + assertThat(this.beanFactory.getBeanNamesForType(MessageTransformingHandler.class)[0]).startsWith(flowId + "."); flowRegistration.destroy(); - assertFalse(this.beanFactory.containsBean(flowRegistrationId)); - assertFalse(this.beanFactory.containsBean(flowRegistrationId + ".input")); - assertFalse(this.beanFactory.containsBean(flowRegistrationId + BeanFactoryHandler.class.getName() + "#0")); + assertThat(this.beanFactory.containsBean(flowRegistrationId)).isFalse(); + assertThat(this.beanFactory.containsBean(flowRegistrationId + ".input")).isFalse(); + assertThat(this.beanFactory.containsBean(flowRegistrationId + BeanFactoryHandler.class.getName() + "#0")) + .isFalse(); ThreadPoolTaskScheduler taskScheduler = this.beanFactory.getBean(ThreadPoolTaskScheduler.class); @@ -260,9 +249,9 @@ public class ManualFlowTests { while (taskScheduler.getActiveCount() > 0 && n++ < 100) { Thread.sleep(100); } - assertThat(n, lessThan(100)); + assertThat(n).isLessThan(100); - assertTrue(additionalBean.destroyed); + assertThat(additionalBean.destroyed).isTrue(); } @Test @@ -272,9 +261,9 @@ public class ManualFlowTests { fail("IllegalStateException expected"); } catch (Exception e) { - assertThat(e, instanceOf(IllegalStateException.class)); - assertThat(e.getMessage(), - containsString("An IntegrationFlow with the id [" + "foo" + "] doesn't exist in the registry.")); + assertThat(e).isInstanceOf(IllegalStateException.class); + assertThat(e.getMessage()) + .contains("An IntegrationFlow with the id [" + "foo" + "] doesn't exist in the registry."); } } @@ -293,14 +282,14 @@ public class ManualFlowTests { this.integrationFlowContext.messagingTemplateFor("dynamicFlow").send(new GenericMessage<>("test")); Message receive = resultChannel.receive(1000); - assertNotNull(receive); - assertEquals("test", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("test"); MessageHistory messageHistory = MessageHistory.read(receive); - assertNotNull(messageHistory); + assertThat(messageHistory).isNotNull(); String messageHistoryString = messageHistory.toString(); - assertThat(messageHistoryString, Matchers.containsString("dynamicFlow.input")); - assertThat(messageHistoryString, Matchers.containsString("dynamicFlow.subFlow#0.channel#1")); + assertThat(messageHistoryString).contains("dynamicFlow.input"); + assertThat(messageHistoryString).contains("dynamicFlow.subFlow#0.channel#1"); this.integrationFlowContext.remove("dynamicFlow"); } @@ -312,8 +301,8 @@ public class ManualFlowTests { PollableChannel resultChannel = this.beanFactory.getBean("flowAdapterOutput", PollableChannel.class); Message receive = resultChannel.receive(1000); - assertNotNull(receive); - assertEquals("flowAdapterMessage", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("flowAdapterMessage"); flowRegistration.destroy(); } @@ -326,8 +315,8 @@ public class ManualFlowTests { fail("BeanCreationNotAllowedException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanCreationNotAllowedException.class)); - assertThat(e.getMessage(), containsString("IntegrationFlows can not be scoped beans.")); + assertThat(e).isInstanceOf(BeanCreationNotAllowedException.class); + assertThat(e.getMessage()).contains("IntegrationFlows can not be scoped beans."); } } @@ -368,8 +357,8 @@ public class ManualFlowTests { .send(new GenericMessage<>("test")); Message receive = resultChannel.receive(1000); - assertNotNull(receive); - assertEquals("test", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("test"); flowRegistration.destroy(); } @@ -393,8 +382,8 @@ public class ManualFlowTests { messagingTemplate.send(new GenericMessage<>("test")); Message receive = resultChannel.receive(1000); - assertNotNull(receive); - assertEquals("test", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("test"); this.roleController.stopLifecyclesInRole(testRole); @@ -402,8 +391,8 @@ public class ManualFlowTests { messagingTemplate.send(new GenericMessage<>("test2")); } catch (Exception e) { - assertThat(e, instanceOf(MessageDeliveryException.class)); - assertThat(e.getMessage(), containsString("Dispatcher has no subscribers for channel")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getMessage()).contains("Dispatcher has no subscribers for channel"); } this.roleController.startLifecyclesInRole(testRole); @@ -411,12 +400,12 @@ public class ManualFlowTests { messagingTemplate.send(new GenericMessage<>("test2")); receive = resultChannel.receive(1000); - assertNotNull(receive); - assertEquals("test2", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("test2"); flowRegistration.destroy(); - assertTrue(this.roleController.getEndpointsRunningStatus(testRole).isEmpty()); + assertThat(this.roleController.getEndpointsRunningStatus(testRole).isEmpty()).isTrue(); } @Test @@ -447,10 +436,10 @@ public class ManualFlowTests { for (int i = 0; i < 4; i++) { Message receive = resultChannel.receive(10_000); - assertNotNull(receive); + assertThat(receive).isNotNull(); } - assertNull(resultChannel.receive(0)); + assertThat(resultChannel.receive(0)).isNull(); flowRegistration.destroy(); } @@ -476,8 +465,8 @@ public class ManualFlowTests { .register(); } catch (Exception e) { - assertThat(e, instanceOf(IllegalArgumentException.class)); - assertThat(e.getMessage(), containsString("with flowId '" + testId + "' is already registered.")); + assertThat(e).isInstanceOf(IllegalArgumentException.class); + assertThat(e.getMessage()).contains("with flowId '" + testId + "' is already registered."); } flowRegistration.destroy(); @@ -514,9 +503,9 @@ public class ManualFlowTests { } executorService.shutdownNow(); - assertTrue(executorService.awaitTermination(10, TimeUnit.SECONDS)); + assertThat(executorService.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); - assertFalse(exceptionHappened.get()); + assertThat(exceptionHappened.get()).isFalse(); flowRegistrations.forEach(IntegrationFlowRegistration::destroy); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/publishsubscribe/PublishSubscribeTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/publishsubscribe/PublishSubscribeTests.java index 9e5f842904..d281e622bb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/publishsubscribe/PublishSubscribeTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/publishsubscribe/PublishSubscribeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.dsl.publishsubscribe; -import static org.hamcrest.Matchers.contains; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.LinkedList; import java.util.List; @@ -56,7 +55,7 @@ public class PublishSubscribeTests { @Test public void executeFirstFlow() { this.inputChannel.send(new GenericMessage<>("Test")); - assertThat(this.subscribersOrderedCall, contains(0, 1, 2, 3, 4, 5)); + assertThat(this.subscribersOrderedCall).containsExactly(0, 1, 2, 3, 4, 5); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java index df5eeb3bc2..fcc0905b6e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java @@ -16,10 +16,7 @@ package org.springframework.integration.dsl.reactivestreams; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; import java.util.ArrayList; @@ -111,9 +108,9 @@ public class ReactiveStreamsTests { latch.countDown(); }); this.messageSource.start(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); String[] strings = results.toArray(new String[0]); - assertArrayEquals(new String[] { "A", "B", "C", "D", "E", "F" }, strings); + assertThat(strings).isEqualTo(new String[] { "A", "B", "C", "D", "E", "F" }); this.messageSource.stop(); } @@ -146,11 +143,11 @@ public class ReactiveStreamsTests { this.inputChannel.send(new GenericMessage<>("6,7,8,9,10")); - assertTrue(latch.await(20, TimeUnit.SECONDS)); + assertThat(latch.await(20, TimeUnit.SECONDS)).isTrue(); List integers = future.get(20, TimeUnit.SECONDS); - assertNotNull(integers); - assertEquals(7, integers.size()); + assertThat(integers).isNotNull(); + assertThat(integers.size()).isEqualTo(7); exec.shutdownNow(); } @@ -175,8 +172,8 @@ public class ReactiveStreamsTests { for (int i = 0; i < 4; i++) { Message receive = resultChannel.receive(10000); - assertNotNull(receive); - assertEquals((i + 1) * 2, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo((i + 1) * 2); } } @@ -208,8 +205,8 @@ public class ReactiveStreamsTests { Message receive = resultChannel.receive(10_000); - assertNotNull(receive); - assertEquals("A,B,C,D,E", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("A,B,C,D,E"); integrationFlowRegistration.destroy(); } @@ -223,7 +220,7 @@ public class ReactiveStreamsTests { latch.countDown(); }); this.singleChannel.send(new GenericMessage<>("foo")); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test @@ -235,7 +232,7 @@ public class ReactiveStreamsTests { latch.countDown(); }); this.fixedSubscriberChannel.send(new GenericMessage<>("bar")); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/routers/RouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/routers/RouterTests.java index 4eab6a7cad..0a66e9e53a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/routers/RouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/routers/RouterTests.java @@ -16,16 +16,9 @@ package org.springframework.integration.dsl.routers; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.fail; import java.util.Arrays; import java.util.List; @@ -104,12 +97,12 @@ public class RouterTests { for (int i = 0; i < 3; i++) { Message receive = this.oddChannel.receive(2000); - assertNotNull(receive); - assertEquals(payloads[i * 2] * 3, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(payloads[i * 2] * 3); receive = this.evenChannel.receive(2000); - assertNotNull(receive); - assertEquals(payloads[i * 2 + 1], receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(payloads[i * 2 + 1]); } } @@ -125,13 +118,13 @@ public class RouterTests { public void testRouterWithTwoSubflows() { this.routerTwoSubFlowsInput.send(new GenericMessage(Arrays.asList(1, 2, 3, 4, 5, 6))); Message receive = this.routerTwoSubFlowsOutput.receive(5000); - assertNotNull(receive); + assertThat(receive).isNotNull(); Object payload = receive.getPayload(); - assertThat(payload, instanceOf(List.class)); + assertThat(payload).isInstanceOf(List.class); @SuppressWarnings("unchecked") List results = (List) payload; - assertArrayEquals(new Integer[] { 3, 4, 9, 8, 15, 12 }, results.toArray(new Integer[results.size()])); + assertThat(results.toArray(new Integer[results.size()])).isEqualTo(new Integer[] { 3, 4, 9, 8, 15, 12 }); } @Autowired @@ -147,8 +140,8 @@ public class RouterTests { .build()); Message receive = replyChannel.receive(10000); - assertNotNull(receive); - assertEquals("BAZ", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("BAZ"); } @@ -165,11 +158,11 @@ public class RouterTests { this.routeSubflowWithoutReplyToMainFlowInput.send(new GenericMessage<>("BOO")); Message receive = routerSubflowResult.receive(10000); - assertNotNull(receive); - assertEquals("boo", receive.getPayload()); - assertNull(this.defaultOutputChannel.receive(1)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("boo"); + assertThat(this.defaultOutputChannel.receive(1)).isNull(); this.routeSubflowWithoutReplyToMainFlowInput.send(new GenericMessage<>("foo")); - assertNotNull(this.defaultOutputChannel.receive(10000)); + assertThat(this.defaultOutputChannel.receive(10000)).isNotNull(); } @Autowired @@ -211,53 +204,53 @@ public class RouterTests { this.recipientListInput.send(fooMessage); Message result1a = this.fooChannel.receive(10000); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); Message result1b = this.barChannel.receive(10000); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); Message result1c = this.recipientListSubFlow1Result.receive(10000); - assertNotNull(result1c); - assertEquals("FOO", result1c.getPayload()); - assertNull(this.recipientListSubFlow2Result.receive(0)); + assertThat(result1c).isNotNull(); + assertThat(result1c.getPayload()).isEqualTo("FOO"); + assertThat(this.recipientListSubFlow2Result.receive(0)).isNull(); this.recipientListInput.send(barMessage); - assertNull(this.fooChannel.receive(0)); - assertNull(this.recipientListSubFlow2Result.receive(0)); + assertThat(this.fooChannel.receive(0)).isNull(); + assertThat(this.recipientListSubFlow2Result.receive(0)).isNull(); Message result2b = this.barChannel.receive(10000); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); Message result2c = this.recipientListSubFlow1Result.receive(10000); - assertNotNull(result1c); - assertEquals("BAR", result2c.getPayload()); + assertThat(result1c).isNotNull(); + assertThat(result2c.getPayload()).isEqualTo("BAR"); this.recipientListInput.send(bazMessage); - assertNull(this.fooChannel.receive(0)); - assertNull(this.barChannel.receive(0)); + assertThat(this.fooChannel.receive(0)).isNull(); + assertThat(this.barChannel.receive(0)).isNull(); Message result3c = this.recipientListSubFlow1Result.receive(10000); - assertNotNull(result3c); - assertEquals("BAZ", result3c.getPayload()); + assertThat(result3c).isNotNull(); + assertThat(result3c.getPayload()).isEqualTo("BAZ"); Message result4c = this.recipientListSubFlow2Result.receive(10000); - assertNotNull(result4c); - assertEquals("Hello baz", result4c.getPayload()); + assertThat(result4c).isNotNull(); + assertThat(result4c.getPayload()).isEqualTo("Hello baz"); this.recipientListInput.send(badMessage); - assertNull(this.fooChannel.receive(0)); - assertNull(this.barChannel.receive(0)); - assertNull(this.recipientListSubFlow1Result.receive(0)); - assertNull(this.recipientListSubFlow2Result.receive(0)); + assertThat(this.fooChannel.receive(0)).isNull(); + assertThat(this.barChannel.receive(0)).isNull(); + assertThat(this.recipientListSubFlow1Result.receive(0)).isNull(); + assertThat(this.recipientListSubFlow2Result.receive(0)).isNull(); Message resultD = this.defaultOutputChannel.receive(10000); - assertNotNull(resultD); - assertEquals("bad", resultD.getPayload()); + assertThat(resultD).isNotNull(); + assertThat(resultD.getPayload()).isEqualTo("bad"); this.recipientListInput.send(new GenericMessage<>("bax")); Message result5c = this.recipientListSubFlow3Result.receive(10000); - assertNotNull(result5c); - assertEquals("bax", result5c.getPayload()); - assertNull(this.fooChannel.receive(0)); - assertNull(this.barChannel.receive(0)); - assertNull(this.recipientListSubFlow1Result.receive(0)); - assertNull(this.recipientListSubFlow2Result.receive(0)); + assertThat(result5c).isNotNull(); + assertThat(result5c.getPayload()).isEqualTo("bax"); + assertThat(this.fooChannel.receive(0)).isNull(); + assertThat(this.barChannel.receive(0)).isNull(); + assertThat(this.recipientListSubFlow1Result.receive(0)).isNull(); + assertThat(this.recipientListSubFlow2Result.receive(0)).isNull(); } @Autowired @@ -285,23 +278,22 @@ public class RouterTests { this.routerMethodInput.send(fooMessage); Message result1a = this.fooChannel.receive(2000); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); - assertNull(this.barChannel.receive(0)); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); + assertThat(this.barChannel.receive(0)).isNull(); this.routerMethodInput.send(barMessage); - assertNull(this.fooChannel.receive(0)); + assertThat(this.fooChannel.receive(0)).isNull(); Message result2b = this.barChannel.receive(2000); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { this.routerMethodInput.send(badMessage); fail("MessageDeliveryException expected."); } catch (MessageDeliveryException e) { - assertThat(e.getMessage(), - containsString("No channel resolved by router")); + assertThat(e.getMessage()).contains("No channel resolved by router"); } } @@ -315,24 +307,23 @@ public class RouterTests { this.routerMethod2Input.send(fooMessage); Message result1a = this.fooChannel.receive(2000); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); - assertNull(this.barChannel.receive(0)); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); + assertThat(this.barChannel.receive(0)).isNull(); this.routerMethod2Input.send(barMessage); - assertNull(this.fooChannel.receive(0)); + assertThat(this.fooChannel.receive(0)).isNull(); Message result2b = this.barChannel.receive(2000); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { this.routerMethod2Input.send(badMessage); fail("DestinationResolutionException expected."); } catch (MessagingException e) { - assertThat(e.getCause(), instanceOf(DestinationResolutionException.class)); - assertThat(e.getCause().getMessage(), - containsString("failed to look up MessageChannel with name 'bad-channel'")); + assertThat(e.getCause()).isInstanceOf(DestinationResolutionException.class); + assertThat(e.getCause().getMessage()).contains("failed to look up MessageChannel with name 'bad-channel'"); } } @@ -346,24 +337,23 @@ public class RouterTests { this.routerMethod3Input.send(fooMessage); Message result1a = this.fooChannel.receive(2000); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); - assertNull(this.barChannel.receive(0)); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); + assertThat(this.barChannel.receive(0)).isNull(); this.routerMethod3Input.send(barMessage); - assertNull(this.fooChannel.receive(0)); + assertThat(this.fooChannel.receive(0)).isNull(); Message result2b = this.barChannel.receive(2000); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { this.routerMethod3Input.send(badMessage); fail("DestinationResolutionException expected."); } catch (MessagingException e) { - assertThat(e.getCause(), instanceOf(DestinationResolutionException.class)); - assertThat(e.getCause().getMessage(), - containsString("failed to look up MessageChannel with name 'bad-channel'")); + assertThat(e.getCause()).isInstanceOf(DestinationResolutionException.class); + assertThat(e.getCause().getMessage()).contains("failed to look up MessageChannel with name 'bad-channel'"); } } @@ -376,27 +366,26 @@ public class RouterTests { this.routerMultiInput.send(fooMessage); Message result1a = this.fooChannel.receive(2000); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); Message result1b = this.barChannel.receive(2000); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); this.routerMultiInput.send(barMessage); Message result2a = this.fooChannel.receive(2000); - assertNotNull(result2a); - assertEquals("bar", result2a.getPayload()); + assertThat(result2a).isNotNull(); + assertThat(result2a.getPayload()).isEqualTo("bar"); Message result2b = this.barChannel.receive(2000); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { this.routerMultiInput.send(badMessage); fail("MessageDeliveryException expected."); } catch (MessageDeliveryException e) { - assertThat(e.getMessage(), - containsString("No channel resolved by router")); + assertThat(e.getMessage()).contains("No channel resolved by router"); } } @@ -420,24 +409,24 @@ public class RouterTests { this.payloadTypeRouteFlowInput.send(new GenericMessage<>("BAR")); Message receive = this.stringsChannel.receive(10000); - assertNotNull(receive); - assertEquals("foo", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("foo"); receive = this.stringsChannel.receive(10000); - assertNotNull(receive); - assertEquals("BAR", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("BAR"); - assertNull(this.stringsChannel.receive(10)); + assertThat(this.stringsChannel.receive(10)).isNull(); receive = this.integersChannel.receive(10000); - assertNotNull(receive); - assertEquals(22, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(22); receive = this.integersChannel.receive(10000); - assertNotNull(receive); - assertEquals(33, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(33); - assertNull(this.integersChannel.receive(10)); + assertThat(this.integersChannel.receive(10)).isNull(); } @Autowired @@ -457,17 +446,17 @@ public class RouterTests { public void testRecipientListRouterOrder() { this.recipientListOrderFlowInput.send(new GenericMessage<>(new AtomicReference<>(""))); Message receive = this.recipientListOrderResult.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); AtomicReference result = (AtomicReference) receive.getPayload(); - assertEquals("Hello World", result.get()); + assertThat(result.get()).isEqualTo("Hello World"); receive = this.recipientListOrderResult.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); result = (AtomicReference) receive.getPayload(); - assertEquals("Hello World", result.get()); + assertThat(result.get()).isEqualTo("Hello World"); - assertEquals(1, this.alwaysRecipient.getQueueSize()); + assertThat(this.alwaysRecipient.getQueueSize()).isEqualTo(1); } @Autowired @@ -482,8 +471,8 @@ public class RouterTests { public void testRouterAsNonLastComponent() { this.routerAsNonLastFlowChannel.send(new GenericMessage<>("Hello World")); Message receive = this.routerAsNonLastDefaultOutputChannel.receive(1000); - assertNotNull(receive); - assertEquals("Hello World", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("Hello World"); } @Autowired @@ -498,10 +487,10 @@ public class RouterTests { .build(); this.scatterGatherFlowInput.send(request); Message bestQuoteMessage = replyChannel.receive(10000); - assertNotNull(bestQuoteMessage); + assertThat(bestQuoteMessage).isNotNull(); Object payload = bestQuoteMessage.getPayload(); - assertThat(payload, instanceOf(List.class)); - assertThat(((List) payload).size(), greaterThanOrEqualTo(1)); + assertThat(payload).isInstanceOf(List.class); + assertThat(((List) payload).size()).isGreaterThanOrEqualTo(1); } @@ -531,10 +520,10 @@ public class RouterTests { this.exceptionTypeRouteFlowInput.send(message); - assertNotNull(this.illegalArgumentChannel.receive(1000)); - assertNull(this.exceptionRouterDefaultChannel.receive(0)); - assertNull(this.runtimeExceptionChannel.receive(0)); - assertNull(this.messageHandlingExceptionChannel.receive(0)); + assertThat(this.illegalArgumentChannel.receive(1000)).isNotNull(); + assertThat(this.exceptionRouterDefaultChannel.receive(0)).isNull(); + assertThat(this.runtimeExceptionChannel.receive(0)).isNull(); + assertThat(this.messageHandlingExceptionChannel.receive(0)).isNull(); } @Autowired @@ -550,25 +539,25 @@ public class RouterTests { .build(); this.nestedScatterGatherFlowInput.send(request); Message bestQuoteMessage = replyChannel.receive(10000); - assertNotNull(bestQuoteMessage); + assertThat(bestQuoteMessage).isNotNull(); Object payload = bestQuoteMessage.getPayload(); - assertThat(payload, instanceOf(String.class)); + assertThat(payload).isInstanceOf(String.class); List topSequenceDetails = (List) bestQuoteMessage.getHeaders() .get(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS, List.class) .get(0); - assertEquals(request.getHeaders().getId(), - bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID)); + assertThat(bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID)) + .isEqualTo(request.getHeaders().getId()); - assertEquals(bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID), - topSequenceDetails.get(0)); + assertThat(topSequenceDetails.get(0)) + .isEqualTo(bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.CORRELATION_ID)); - assertEquals(bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER), - topSequenceDetails.get(1)); + assertThat(topSequenceDetails.get(1)) + .isEqualTo(bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)); - assertEquals(bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE), - topSequenceDetails.get(2)); + assertThat(topSequenceDetails.get(2)) + .isEqualTo(bestQuoteMessage.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); } @Autowired @@ -586,10 +575,10 @@ public class RouterTests { this.scatterGatherAndExecutorChannelSubFlowInput.send(testMessage); Message receive = replyChannel.receive(10_000); - assertNotNull(receive); + assertThat(receive).isNotNull(); Object payload = receive.getPayload(); - assertThat(payload, instanceOf(List.class)); - assertThat(((List) payload).get(1), instanceOf(RuntimeException.class)); + assertThat(payload).isInstanceOf(List.class); + assertThat(((List) payload).get(1)).isInstanceOf(RuntimeException.class); } @Autowired diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/transformers/TransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/transformers/TransformerTests.java index d29045b94f..217f56d935 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/transformers/TransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/transformers/TransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-2019 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,15 +16,8 @@ package org.springframework.integration.dsl.transformers; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.IOException; import java.io.InputStream; @@ -33,7 +26,6 @@ import java.util.Collections; import java.util.Date; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -100,19 +92,19 @@ public class TransformerTests { .build(); this.enricherInput.send(message); Message receive = replyChannel.receive(5000); - assertNotNull(receive); - assertEquals("Bar Bar", receive.getHeaders().get("foo")); + assertThat(receive).isNotNull(); + assertThat(receive.getHeaders().get("foo")).isEqualTo("Bar Bar"); Object payload = receive.getPayload(); - assertThat(payload, instanceOf(TestPojo.class)); + assertThat(payload).isInstanceOf(TestPojo.class); TestPojo result = (TestPojo) payload; - assertEquals("Bar Bar", result.getName()); - assertNotNull(result.getDate()); - assertThat(new Date(), Matchers.greaterThanOrEqualTo(result.getDate())); + assertThat(result.getName()).isEqualTo("Bar Bar"); + assertThat(result.getDate()).isNotNull(); + assertThat(new Date()).isAfterOrEqualsTo(result.getDate()); this.enricherInput.send(new GenericMessage<>(new TestPojo("junk"))); Message errorMessage = this.enricherErrorChannel.receive(10_000); - assertNotNull(errorMessage); + assertThat(errorMessage).isNotNull(); } @Test @@ -123,14 +115,14 @@ public class TransformerTests { .build(); this.enricherInput2.send(message); Message receive = replyChannel.receive(5000); - assertNotNull(receive); - assertNull(receive.getHeaders().get("foo")); + assertThat(receive).isNotNull(); + assertThat(receive.getHeaders().get("foo")).isNull(); Object payload = receive.getPayload(); - assertThat(payload, instanceOf(TestPojo.class)); + assertThat(payload).isInstanceOf(TestPojo.class); TestPojo result = (TestPojo) payload; - assertEquals("Bar Bar", result.getName()); - assertNotNull(result.getDate()); - assertThat(new Date(), Matchers.greaterThanOrEqualTo(result.getDate())); + assertThat(result.getName()).isEqualTo("Bar Bar"); + assertThat(result.getDate()).isNotNull(); + assertThat(new Date()).isAfterOrEqualsTo(result.getDate()); } @Test @@ -141,13 +133,13 @@ public class TransformerTests { .build(); this.enricherInput3.send(message); Message receive = replyChannel.receive(5000); - assertNotNull(receive); - assertEquals("Bar Bar", receive.getHeaders().get("foo")); + assertThat(receive).isNotNull(); + assertThat(receive.getHeaders().get("foo")).isEqualTo("Bar Bar"); Object payload = receive.getPayload(); - assertThat(payload, instanceOf(TestPojo.class)); + assertThat(payload).isInstanceOf(TestPojo.class); TestPojo result = (TestPojo) payload; - assertEquals("Bar", result.getName()); - assertNull(result.getDate()); + assertThat(result.getName()).isEqualTo("Bar"); + assertThat(result.getDate()).isNull(); } @Autowired @@ -166,21 +158,21 @@ public class TransformerTests { public void testSubFlowContentEnricher() { this.replyProducingSubFlowEnricherInput.send(MessageBuilder.withPayload(new TestPojo("Bar")).build()); Message receive = this.subFlowTestReplyChannel.receive(5000); - assertNotNull(receive); - assertEquals("Foo Bar (Reply Producing)", receive.getHeaders().get("foo")); + assertThat(receive).isNotNull(); + assertThat(receive.getHeaders().get("foo")).isEqualTo("Foo Bar (Reply Producing)"); Object payload = receive.getPayload(); - assertThat(payload, instanceOf(TestPojo.class)); + assertThat(payload).isInstanceOf(TestPojo.class); TestPojo result = (TestPojo) payload; - assertThat(result.getName(), is("Foo Bar (Reply Producing)")); + assertThat(result.getName()).isEqualTo("Foo Bar (Reply Producing)"); this.terminatingSubFlowEnricherInput.send(MessageBuilder.withPayload(new TestPojo("Bar")).build()); receive = this.subFlowTestReplyChannel.receive(5000); - assertNotNull(receive); - assertEquals("Foo Bar (Terminating)", receive.getHeaders().get("foo")); + assertThat(receive).isNotNull(); + assertThat(receive.getHeaders().get("foo")).isEqualTo("Foo Bar (Terminating)"); payload = receive.getPayload(); - assertThat(payload, instanceOf(TestPojo.class)); + assertThat(payload).isInstanceOf(TestPojo.class); result = (TestPojo) payload; - assertThat(result.getName(), is("Foo Bar (Terminating)")); + assertThat(result.getName()).isEqualTo("Foo Bar (Terminating)"); } @Autowired @@ -199,15 +191,15 @@ public class TransformerTests { public void testCodec() { this.encodingFlowInput.send(new GenericMessage<>("bar")); Message receive = this.codecReplyChannel.receive(10000); - assertNotNull(receive); - assertThat(receive.getPayload(), instanceOf(byte[].class)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isInstanceOf(byte[].class); byte[] transformed = (byte[]) receive.getPayload(); - assertArrayEquals("foo".getBytes(), transformed); + assertThat(transformed).isEqualTo("foo".getBytes()); this.decodingFlowInput.send(new GenericMessage<>(transformed)); receive = this.codecReplyChannel.receive(10000); - assertNotNull(receive); - assertEquals(42, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(42); } @@ -229,21 +221,21 @@ public class TransformerTests { .build(); this.pojoTransformFlowInput.send(message); Message receive = replyChannel.receive(10000); - assertNotNull(receive); - assertEquals("FooBar", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("FooBar"); try { this.pojoTransformFlowInput.send(message); fail("MessageRejectedException expected"); } catch (Exception e) { - assertThat(e, instanceOf(MessageRejectedException.class)); - assertThat(e.getMessage(), containsString("IdempotentReceiver")); - assertThat(e.getMessage(), containsString("rejected duplicate Message")); + assertThat(e).isInstanceOf(MessageRejectedException.class); + assertThat(e.getMessage()).contains("IdempotentReceiver"); + assertThat(e.getMessage()).contains("rejected duplicate Message"); } - assertNotNull(this.idempotentDiscardChannel.receive(10000)); - assertNotNull(this.adviceChannel.receive(10000)); + assertThat(this.idempotentDiscardChannel.receive(10000)).isNotNull(); + assertThat(this.adviceChannel.receive(10000)).isNotNull(); } @Autowired @@ -262,16 +254,16 @@ public class TransformerTests { Message receive = replyChannel.receive(10_000); - assertNotNull(receive); + assertThat(receive).isNotNull(); Object payload = receive.getPayload(); - assertThat(payload, instanceOf(TestPojo.class)); + assertThat(payload).isInstanceOf(TestPojo.class); TestPojo testPojo = (TestPojo) payload; - assertEquals("Baz", testPojo.getName()); - assertEquals(date, testPojo.getDate()); + assertThat(testPojo.getName()).isEqualTo("Baz"); + assertThat(testPojo.getDate()).isEqualTo(date); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/enablecomponentscan/EnableComponentScanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/enablecomponentscan/EnableComponentScanTests.java index 37f4964bac..a76320b6c9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/enablecomponentscan/EnableComponentScanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/enablecomponentscan/EnableComponentScanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2019 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,7 @@ package org.springframework.integration.enablecomponentscan; -import static org.hamcrest.Matchers.emptyArray; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; import java.util.Collections; @@ -55,8 +53,7 @@ public class EnableComponentScanTests { @Test public void testCustomIntegrationComponentScan() { - assertThat(applicationContext.getBeanNamesForType(IntegrationFlowTests.ControlBusGateway.class), - not(emptyArray())); + assertThat(applicationContext.getBeanNamesForType(IntegrationFlowTests.ControlBusGateway.class)).isNotEmpty(); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java index 28b45a4883..4714644cef 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; @@ -51,9 +50,9 @@ public class CorrelationIdTests { serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); Message reply = outputChannel.receive(0); - assertEquals(correlationId, new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()).isEqualTo(correlationId); } @Test @@ -68,10 +67,10 @@ public class CorrelationIdTests { serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); Message reply = outputChannel.receive(0); - assertEquals(new IntegrationMessageHeaderAccessor(message).getCorrelationId(), - new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()) + .isEqualTo(new IntegrationMessageHeaderAccessor(message).getCorrelationId()); } @Test @@ -87,9 +86,9 @@ public class CorrelationIdTests { serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); Message reply = outputChannel.receive(0); - assertEquals("456-XYZ", new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()).isEqualTo("456-XYZ"); } @Test @@ -103,9 +102,9 @@ public class CorrelationIdTests { serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); Message reply = outputChannel.receive(0); - assertEquals("456-XYZ", new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()).isEqualTo("456-XYZ"); } @Test @@ -120,8 +119,10 @@ public class CorrelationIdTests { splitter.handleMessage(message); Message reply1 = testChannel.receive(100); Message reply2 = testChannel.receive(100); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); } @Test @@ -137,12 +138,14 @@ public class CorrelationIdTests { splitter.handleMessage(message); Message reply1 = testChannel.receive(100); Message reply2 = testChannel.receive(100); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()); - assertTrue("Sequence details missing", - reply1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); - assertTrue("Sequence details missing", - reply2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); + assertThat(reply1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)) + .as("Sequence details missing").isTrue(); + assertThat(reply2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)) + .as("Sequence details missing").isTrue(); } @SuppressWarnings("unused") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java index 213d048de8..bef531c589 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -78,17 +78,17 @@ public class ExpressionEvaluatingMessageSourceIntegrationTests { } scheduler.destroy(); Message message1 = messages.get(0); - assertEquals("test-1", message1.getPayload()); - assertEquals("x", message1.getHeaders().get("foo")); - assertEquals(42, message1.getHeaders().get("bar")); + assertThat(message1.getPayload()).isEqualTo("test-1"); + assertThat(message1.getHeaders().get("foo")).isEqualTo("x"); + assertThat(message1.getHeaders().get("bar")).isEqualTo(42); Message message2 = messages.get(1); - assertEquals("test-2", message2.getPayload()); - assertEquals("x", message2.getHeaders().get("foo")); - assertEquals(42, message2.getHeaders().get("bar")); + assertThat(message2.getPayload()).isEqualTo("test-2"); + assertThat(message2.getHeaders().get("foo")).isEqualTo("x"); + assertThat(message2.getHeaders().get("bar")).isEqualTo(42); Message message3 = messages.get(2); - assertEquals("test-3", message3.getPayload()); - assertEquals("x", message3.getHeaders().get("foo")); - assertEquals(42, message3.getHeaders().get("bar")); + assertThat(message3.getPayload()).isEqualTo("test-3"); + assertThat(message3.getHeaders().get("foo")).isEqualTo("x"); + assertThat(message3.getHeaders().get("bar")).isEqualTo(42); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java index 5521198eda..00170fe978 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; @@ -43,8 +42,8 @@ public class ExpressionEvaluatingMessageSourceTests { new ExpressionEvaluatingMessageSource(expression, String.class); source.setBeanFactory(mock(BeanFactory.class)); Message message = source.receive(); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test(expected = ConversionFailedException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java index 40050777e7..e560ba1b3a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java @@ -16,12 +16,7 @@ package org.springframework.integration.endpoint; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -118,11 +113,11 @@ public class MessageProducerSupportTests { mps.start(); Message message = new GenericMessage<>("hello"); mps.sendMessage(message); - assertThat(errorService.lastMessage, instanceOf(ErrorMessage.class)); + assertThat(errorService.lastMessage).isInstanceOf(ErrorMessage.class); ErrorMessage errorMessage = (ErrorMessage) errorService.lastMessage; - assertEquals(MessageDeliveryException.class, errorMessage.getPayload().getClass()); + assertThat(errorMessage.getPayload().getClass()).isEqualTo(MessageDeliveryException.class); MessageDeliveryException exception = (MessageDeliveryException) errorMessage.getPayload(); - assertEquals(message, exception.getFailedMessage()); + assertThat(exception.getFailedMessage()).isEqualTo(message); } @Test @@ -137,21 +132,21 @@ public class MessageProducerSupportTests { mps.setBeanFactory(this.context); mps.afterPropertiesSet(); mps.start(); - assertSame(outChannel, mps.getOutputChannel()); + assertThat(mps.getOutputChannel()).isSameAs(outChannel); } @Test public void customDoStop() { final CustomEndpoint endpoint = new CustomEndpoint(); - assertEquals(0, endpoint.getCount()); - assertTrue(endpoint.isStopped()); + assertThat(endpoint.getCount()).isEqualTo(0); + assertThat(endpoint.isStopped()).isTrue(); endpoint.start(); - assertFalse(endpoint.isStopped()); + assertThat(endpoint.isStopped()).isFalse(); endpoint.stop(() -> { // Do nothing }); - assertEquals(1, endpoint.getCount()); - assertTrue(endpoint.isStopped()); + assertThat(endpoint.getCount()).isEqualTo(1); + assertThat(endpoint.isStopped()).isTrue(); } private static class SuccessfulErrorService { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageSourcePollingTemplateTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageSourcePollingTemplateTests.java index 83890c44eb..2653f03772 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageSourcePollingTemplateTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageSourcePollingTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 the original author or authors. + * Copyright 2018-2019 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,8 @@ package org.springframework.integration.endpoint; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -59,7 +58,7 @@ public class MessageSourcePollingTemplateTests { fail("expected exception"); } catch (MessageHandlingException e) { - assertThat(e.getCause().getMessage(), equalTo("expected")); + assertThat(e.getCause().getMessage()).isEqualTo("expected"); } verify(callback).acknowledge(Status.REJECT); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollerAdviceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollerAdviceTests.java index fa2fcafa2e..2cd94b02d8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollerAdviceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollerAdviceTests.java @@ -16,13 +16,7 @@ package org.springframework.integration.endpoint; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.spy; @@ -119,7 +113,7 @@ public class PollerAdviceTests { adapter.setAdviceChain(adviceChain); adapter.afterPropertiesSet(); adapter.start(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); adapter.stop(); } @@ -157,24 +151,24 @@ public class PollerAdviceTests { adapter.setAdviceChain(adviceChain); adapter.afterPropertiesSet(); adapter.start(); - assertFalse(latch.await(10, TimeUnit.MILLISECONDS)); - assertFalse(ehCalled.get()); + assertThat(latch.await(10, TimeUnit.MILLISECONDS)).isFalse(); + assertThat(ehCalled.get()).isFalse(); adapter.stop(); skipper.reset(); latch = new CountDownLatch(1); adapter.setSource(new LocalSource(latch)); adapter.setTrigger(new OnlyOnceTrigger()); adapter.start(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); adapter.stop(); } @Test public void testSkipSimpleControlBus() { this.control.send(new GenericMessage<>("@skipper.skipPolls()")); - assertTrue(this.skipper.skipPoll()); + assertThat(this.skipper.skipPoll()).isTrue(); this.control.send(new GenericMessage<>("@skipper.reset()")); - assertFalse(this.skipper.skipPoll()); + assertThat(this.skipper.skipPoll()).isFalse(); } @Test @@ -223,15 +217,15 @@ public class PollerAdviceTests { adapter.setAdviceChain(adviceChain); adapter.afterPropertiesSet(); adapter.start(); - assertTrue(latch.get().await(10, TimeUnit.SECONDS)); - assertThat(callOrder, contains("a", "b", "c", "d")); // advice + advice + source + advice + assertThat(latch.get().await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(callOrder).containsExactly("a", "b", "c", "d"); // advice + advice + source + advice adapter.stop(); trigger.reset(); latch.set(new CountDownLatch(4)); adapter.start(); - assertTrue(latch.get().await(10, TimeUnit.SECONDS)); + assertThat(latch.get().await(10, TimeUnit.SECONDS)).isTrue(); adapter.stop(); - assertEquals(2, count.get()); + assertThat(count.get()).isEqualTo(2); // Now test when the source is already a proxy. @@ -243,17 +237,17 @@ public class PollerAdviceTests { count.set(0); callOrder.clear(); adapter.start(); - assertTrue(latch.get().await(10, TimeUnit.SECONDS)); - assertThat(callOrder, contains("a", "b", "c", "d")); // advice + advice + source + advice + assertThat(latch.get().await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(callOrder).containsExactly("a", "b", "c", "d"); // advice + advice + source + advice adapter.stop(); trigger.reset(); latch.set(new CountDownLatch(4)); adapter.start(); - assertTrue(latch.get().await(10, TimeUnit.SECONDS)); + assertThat(latch.get().await(10, TimeUnit.SECONDS)).isTrue(); adapter.stop(); - assertEquals(2, count.get()); + assertThat(count.get()).isEqualTo(2); Advisor[] advisors = ((Advised) adapter.getMessageSource()).getAdvisors(); - assertEquals(2, advisors.length); // make sure we didn't remove the original one + assertThat(advisors.length).isEqualTo(2); // make sure we didn't remove the original one } @Test @@ -281,10 +275,10 @@ public class PollerAdviceTests { configure(adapter); adapter.afterPropertiesSet(); adapter.start(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); adapter.stop(); synchronized (triggerPeriods) { - assertThat(triggerPeriods.subList(0, 5), contains(10L, 12L, 11L, 12L, 11L)); + assertThat(triggerPeriods.subList(0, 5)).containsExactly(10L, 12L, 11L, 12L, 11L); } } @@ -312,10 +306,10 @@ public class PollerAdviceTests { configure(adapter); adapter.afterPropertiesSet(); adapter.start(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); adapter.stop(); synchronized (overridePresent) { - assertThat(overridePresent.subList(0, 5), contains(null, override, null, override, null)); + assertThat(overridePresent.subList(0, 5)).containsExactly(null, override, null, override, null); } verify(override, atLeast(2)).nextExecutionTime(any(TriggerContext.class)); } @@ -333,14 +327,14 @@ public class PollerAdviceTests { SourcePollingChannelAdapter adapter = ctx.getBean(SourcePollingChannelAdapter.class); Source source = ctx.getBean(Source.class); adapter.start(); - assertTrue(source.latch.await(10, TimeUnit.SECONDS)); - assertNotNull(TestUtils.getPropertyValue(adapter, "trigger.override")); + assertThat(source.latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(TestUtils.getPropertyValue(adapter, "trigger.override")).isNotNull(); adapter.stop(); OtherAdvice sourceAdvice = ctx.getBean(OtherAdvice.class); int count = sourceAdvice.calls; - assertThat(count, greaterThan(0)); + assertThat(count).isGreaterThan(0); ((Foo) adapter.getMessageSource()).otherMethod(); - assertEquals(count, sourceAdvice.calls); + assertThat(sourceAdvice.calls).isEqualTo(count); ctx.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java index d1c2316cd1..a8deca7a1c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.concurrent.atomic.AtomicInteger; @@ -90,7 +90,7 @@ public class PollingConsumerEndpointTests { this.endpoint.start(); this.trigger.await(); this.endpoint.stop(); - assertEquals(1, this.consumer.counter.get()); + assertThat(this.consumer.counter.get()).isEqualTo(1); } @Test @@ -101,7 +101,7 @@ public class PollingConsumerEndpointTests { this.endpoint.start(); this.trigger.await(); this.endpoint.stop(); - assertEquals(5, this.consumer.counter.get()); + assertThat(this.consumer.counter.get()).isEqualTo(5); } @Test @@ -112,7 +112,7 @@ public class PollingConsumerEndpointTests { this.endpoint.start(); this.trigger.await(); this.endpoint.stop(); - assertEquals(5, this.consumer.counter.get()); + assertThat(this.consumer.counter.get()).isEqualTo(5); } @Test @@ -132,7 +132,7 @@ public class PollingConsumerEndpointTests { this.endpoint.start(); this.trigger.await(); this.endpoint.stop(); - assertEquals(1, this.consumer.counter.get()); + assertThat(this.consumer.counter.get()).isEqualTo(1); this.errorHandler.throwLastErrorIfAvailable(); } @@ -143,7 +143,7 @@ public class PollingConsumerEndpointTests { this.endpoint.start(); this.trigger.await(); this.endpoint.stop(); - assertEquals(1, this.consumer.counter.get()); + assertThat(this.consumer.counter.get()).isEqualTo(1); this.errorHandler.throwLastErrorIfAvailable(); } @@ -155,7 +155,7 @@ public class PollingConsumerEndpointTests { this.endpoint.start(); this.trigger.await(); this.endpoint.stop(); - assertEquals(0, this.consumer.counter.get()); + assertThat(this.consumer.counter.get()).isEqualTo(0); } @Test @@ -166,7 +166,7 @@ public class PollingConsumerEndpointTests { this.endpoint.start(); this.trigger.await(); this.endpoint.stop(); - assertEquals(1, this.consumer.counter.get()); + assertThat(this.consumer.counter.get()).isEqualTo(1); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingEndpointErrorHandlingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingEndpointErrorHandlingTests.java index 8adecc00b5..2f1b4d3186 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingEndpointErrorHandlingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingEndpointErrorHandlingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -39,8 +38,9 @@ public class PollingEndpointErrorHandlingTests { "pollingEndpointErrorHandlingTests.xml", this.getClass()); PollableChannel errorChannel = (PollableChannel) context.getBean("errorChannel"); Message errorMessage = errorChannel.receive(5000); - assertNotNull("No error message received", errorMessage); - assertEquals("Message received was not an ErrorMessage", ErrorMessage.class, errorMessage.getClass()); + assertThat(errorMessage).as("No error message received").isNotNull(); + assertThat(errorMessage.getClass()).as("Message received was not an ErrorMessage") + .isEqualTo(ErrorMessage.class); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java index cc736124f8..afb94d468a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -93,7 +91,7 @@ public class PollingLifecycleTests { consumer.setBeanFactory(mock(BeanFactory.class)); consumer.afterPropertiesSet(); consumer.start(); - assertTrue(latch.await(2, TimeUnit.SECONDS)); + assertThat(latch.await(2, TimeUnit.SECONDS)).isTrue(); Mockito.verify(handler, times(1)).handleMessage(Mockito.any(Message.class)); consumer.stop(); Mockito.reset(handler); @@ -130,10 +128,10 @@ public class PollingLifecycleTests { adapter.setTaskScheduler(this.taskScheduler); adapter.afterPropertiesSet(); adapter.start(); - assertTrue(latch.await(20, TimeUnit.SECONDS)); - assertNotNull(channel.receive(100)); + assertThat(latch.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat(channel.receive(100)).isNotNull(); adapter.stop(); - assertNull(channel.receive(10)); + assertThat(channel.receive(10)).isNull(); Mockito.verify(source, times(1)).receive(); } @@ -171,11 +169,11 @@ public class PollingLifecycleTests { adapter.setTaskScheduler(this.taskScheduler); adapter.afterPropertiesSet(); adapter.start(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); // adapter.stop(); - assertTrue(interruptedLatch.await(10, TimeUnit.SECONDS)); + assertThat(interruptedLatch.await(10, TimeUnit.SECONDS)).isTrue(); Mockito.verify(caughtInterrupted, times(1)).run(); } @@ -220,8 +218,8 @@ public class PollingLifecycleTests { adapter.start(); adapter.stop(); - assertTrue(startInvoked.get()); - assertTrue(stopInvoked.get()); + assertThat(startInvoked.get()).isTrue(); + assertThat(stopInvoked.get()).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java index e486f160c9..114f705a4b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -58,9 +58,9 @@ public class ProducerAndConsumerAutoStartupTests { received.add(this.consumer.poll(10000)); } this.context.stop(); - assertEquals(new Integer(1), received.get(0)); - assertEquals(new Integer(2), received.get(1)); - assertEquals(new Integer(3), received.get(2)); + assertThat(received.get(0)).isEqualTo(new Integer(1)); + assertThat(received.get(1)).isEqualTo(new Integer(2)); + assertThat(received.get(2)).isEqualTo(new Integer(3)); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java index bd3a90e388..b910be517e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,18 +16,14 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; -import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; @@ -102,7 +98,7 @@ public class PseudoTransactionalMessageSourceTests { MessageChannel afterCommitChannel = TestUtils.getPropertyValue(syncProcessor, "afterCommitChannel", MessageChannel.class); - assertThat(afterCommitChannel, Matchers.instanceOf(NullChannel.class)); + assertThat(afterCommitChannel).isInstanceOf(NullChannel.class); Log logger = TestUtils.getPropertyValue(afterCommitChannel, "logger", Log.class); @@ -119,8 +115,8 @@ public class PseudoTransactionalMessageSourceTests { TransactionSynchronizationUtils.triggerBeforeCommit(false); TransactionSynchronizationUtils.triggerAfterCommit(); Message beforeCommitMessage = queueChannel.receive(1000); - assertNotNull(beforeCommitMessage); - assertEquals("qox", beforeCommitMessage.getPayload()); + assertThat(beforeCommitMessage).isNotNull(); + assertThat(beforeCommitMessage.getPayload()).isEqualTo("qox"); Mockito.verify(logger).debug(Mockito.anyString()); @@ -162,11 +158,11 @@ public class PseudoTransactionalMessageSourceTests { TransactionSynchronizationUtils.triggerBeforeCommit(false); TransactionSynchronizationUtils.triggerAfterCommit(); Message beforeCommitMessage = queueChannel.receive(1000); - assertNotNull(beforeCommitMessage); - assertEquals("qox", beforeCommitMessage.getPayload()); + assertThat(beforeCommitMessage).isNotNull(); + assertThat(beforeCommitMessage.getPayload()).isEqualTo("qox"); Message afterCommitMessage = queueChannel.receive(1000); - assertNotNull(afterCommitMessage); - assertEquals("qux", afterCommitMessage.getPayload()); + assertThat(afterCommitMessage).isNotNull(); + assertThat(afterCommitMessage.getPayload()).isEqualTo("qux"); TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED); TransactionSynchronizationManager.clearSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(false); @@ -210,8 +206,8 @@ public class PseudoTransactionalMessageSourceTests { doPoll(adapter); TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); Message rollbackMessage = queueChannel.receive(1000); - assertNotNull(rollbackMessage); - assertSame(testMessage, rollbackMessage); + assertThat(rollbackMessage).isNotNull(); + assertThat(rollbackMessage).isSameAs(testMessage); TransactionSynchronizationManager.clearSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(false); } @@ -254,11 +250,11 @@ public class PseudoTransactionalMessageSourceTests { return null; }); Message beforeCommitMessage = queueChannel.receive(1000); - assertNotNull(beforeCommitMessage); - assertEquals("qox", beforeCommitMessage.getPayload()); + assertThat(beforeCommitMessage).isNotNull(); + assertThat(beforeCommitMessage.getPayload()).isEqualTo("qox"); Message afterCommitMessage = queueChannel.receive(1000); - assertNotNull(afterCommitMessage); - assertEquals("qux", afterCommitMessage.getPayload()); + assertThat(afterCommitMessage).isNotNull(); + assertThat(afterCommitMessage.getPayload()).isEqualTo("qux"); } @Test @@ -298,11 +294,11 @@ public class PseudoTransactionalMessageSourceTests { }); } catch (Exception e) { - assertEquals("Force rollback", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Force rollback"); } Message rollbackMessage = queueChannel.receive(1000); - assertNotNull(rollbackMessage); - assertEquals("qux", rollbackMessage.getPayload()); + assertThat(rollbackMessage).isNotNull(); + assertThat(rollbackMessage.getPayload()).isEqualTo("qux"); } @Test @@ -341,8 +337,8 @@ public class PseudoTransactionalMessageSourceTests { return null; }); Message rollbackMessage = queueChannel.receive(1000); - assertNotNull(rollbackMessage); - assertEquals("qux", rollbackMessage.getPayload()); + assertThat(rollbackMessage).isNotNull(); + assertThat(rollbackMessage.getPayload()).isEqualTo("qux"); } @Test @@ -389,7 +385,7 @@ public class PseudoTransactionalMessageSourceTests { TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED); TransactionSynchronizationManager.clearSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(false); - assertEquals(1, txSyncCounter.get()); + assertThat(txSyncCounter.get()).isEqualTo(1); TransactionSynchronizationManager.initSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(true); @@ -397,7 +393,7 @@ public class PseudoTransactionalMessageSourceTests { TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED); TransactionSynchronizationManager.clearSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(false); - assertEquals(2, txSyncCounter.get()); + assertThat(txSyncCounter.get()).isEqualTo(2); } protected void doPoll(SourcePollingChannelAdapter adapter) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ReturnAddressTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ReturnAddressTests.java index 71b0e2b3e6..6a0a1c77bd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ReturnAddressTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ReturnAddressTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -49,8 +46,8 @@ public class ReturnAddressTests { .setReplyChannel(channel5).build(); channel3.send(message); Message response = channel5.receive(3000); - assertNotNull(response); - assertEquals("**", response.getPayload()); + assertThat(response).isNotNull(); + assertThat(response.getPayload()).isEqualTo("**"); context.close(); } @@ -65,8 +62,8 @@ public class ReturnAddressTests { .setReplyChannelName("channel5").build(); channel3.send(message); Message response = channel5.receive(3000); - assertNotNull(response); - assertEquals("**", response.getPayload()); + assertThat(response).isNotNull(); + assertThat(response.getPayload()).isEqualTo("**"); context.close(); } @@ -81,10 +78,10 @@ public class ReturnAddressTests { .setReplyChannel(replyChannel).build(); channel1.send(message); Message response = replyChannel.receive(3000); - assertNotNull(response); - assertEquals("********", response.getPayload()); + assertThat(response).isNotNull(); + assertThat(response.getPayload()).isEqualTo("********"); PollableChannel channel2 = (PollableChannel) context.getBean("channel2"); - assertNull(channel2.receive(0)); + assertThat(channel2.receive(0)).isNull(); context.close(); } @@ -99,10 +96,10 @@ public class ReturnAddressTests { .setReplyChannelName("replyChannel").build(); channel1.send(message); Message response = replyChannel.receive(3000); - assertNotNull(response); - assertEquals("********", response.getPayload()); + assertThat(response).isNotNull(); + assertThat(response.getPayload()).isEqualTo("********"); PollableChannel channel2 = (PollableChannel) context.getBean("channel2"); - assertNull(channel2.receive(0)); + assertThat(channel2.receive(0)).isNull(); context.close(); } @@ -117,7 +114,7 @@ public class ReturnAddressTests { channel3.send(message); } catch (MessagingException e) { - assertTrue(e.getCause() instanceof DestinationResolutionException); + assertThat(e.getCause() instanceof DestinationResolutionException).isTrue(); } context.close(); } @@ -132,8 +129,8 @@ public class ReturnAddressTests { GenericMessage message = new GenericMessage("*"); channel4.send(message); Message response = replyChannel.receive(3000); - assertNotNull(response); - assertEquals("**", response.getPayload()); + assertThat(response).isNotNull(); + assertThat(response.getPayload()).isEqualTo("**"); context.close(); } @@ -148,10 +145,10 @@ public class ReturnAddressTests { .setReplyChannelName("channel5").build(); channel4.send(message); Message response = replyChannel.receive(3000); - assertNotNull(response); - assertEquals("**", response.getPayload()); + assertThat(response).isNotNull(); + assertThat(response.getPayload()).isEqualTo("**"); PollableChannel channel5 = (PollableChannel) context.getBean("channel5"); - assertNull(channel5.receive(0)); + assertThat(channel5.receive(0)).isNull(); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java index bfd76ee83e..3188a034a7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java @@ -16,11 +16,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; @@ -52,8 +48,8 @@ public class ServiceActivatorEndpointTests { Message message = MessageBuilder.withPayload("foo").build(); endpoint.handleMessage(message); Message reply = channel.receive(0); - assertNotNull(reply); - assertEquals("FOO", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("FOO"); } @Test @@ -65,10 +61,10 @@ public class ServiceActivatorEndpointTests { Message message = MessageBuilder.withPayload("foo").setReplyChannel(channel2).build(); endpoint.handleMessage(message); Message reply1 = channel1.receive(0); - assertNotNull(reply1); - assertEquals("FOO", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("FOO"); Message reply2 = channel2.receive(0); - assertNull(reply2); + assertThat(reply2).isNull(); } @Test @@ -78,8 +74,8 @@ public class ServiceActivatorEndpointTests { Message message = MessageBuilder.withPayload("foo").setReplyChannel(channel).build(); endpoint.handleMessage(message); Message reply = channel.receive(0); - assertNotNull(reply); - assertEquals("FOO", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("FOO"); } @Test @@ -98,8 +94,8 @@ public class ServiceActivatorEndpointTests { .setReplyChannelName("testChannel").build(); endpoint.handleMessage(message); Message reply = channel.receive(0); - assertNotNull(reply); - assertEquals("FOO", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("FOO"); testApplicationContext.close(); } @@ -127,18 +123,18 @@ public class ServiceActivatorEndpointTests { .setReplyChannel(replyChannel1).build(); endpoint.handleMessage(testMessage1); Message reply1 = replyChannel1.receive(50); - assertNotNull(reply1); - assertEquals("foobar", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foobar"); Message reply2 = replyChannel2.receive(0); - assertNull(reply2); + assertThat(reply2).isNull(); Message testMessage2 = MessageBuilder.fromMessage(testMessage1) .setReplyChannelName("replyChannel2").build(); endpoint.handleMessage(testMessage2); reply1 = replyChannel1.receive(0); - assertNull(reply1); + assertThat(reply1).isNull(); reply2 = replyChannel2.receive(0); - assertNotNull(reply2); - assertEquals("foobar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("foobar"); testApplicationContext.close(); } @@ -149,8 +145,8 @@ public class ServiceActivatorEndpointTests { Message message = MessageBuilder.withPayload("foo").setReplyChannel(channel).build(); endpoint.handleMessage(message); Message reply = channel.receive(0); - assertNotNull(reply); - assertEquals("FOO", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("FOO"); } @Test(expected = MessagingException.class) @@ -169,7 +165,7 @@ public class ServiceActivatorEndpointTests { endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo").build(); endpoint.handleMessage(message); - assertNull(channel.receive(0)); + assertThat(channel.receive(0)).isNull(); } @Test(expected = ReplyRequiredException.class) @@ -202,7 +198,7 @@ public class ServiceActivatorEndpointTests { .setReplyChannel(replyChannel).build(); endpoint.handleMessage(message); Message reply = replyChannel.receive(500); - assertNull(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()).isNull(); } @Test @@ -225,8 +221,8 @@ public class ServiceActivatorEndpointTests { endpoint.handleMessage(message); Message reply = replyChannel.receive(500); Object correlationId = new IntegrationMessageHeaderAccessor(reply).getCorrelationId(); - assertNotEquals(message.getHeaders().getId(), correlationId); - assertEquals("ABC-123", correlationId); + assertThat(correlationId).isNotEqualTo(message.getHeaders().getId()); + assertThat(correlationId).isEqualTo("ABC-123"); } @Test @@ -236,8 +232,8 @@ public class ServiceActivatorEndpointTests { endpoint.setBeanFactory(mock); endpoint.afterPropertiesSet(); Object beanFactory = TestUtils.getPropertyValue(endpoint, "processor.beanFactory"); - assertNotNull(beanFactory); - assertSame(mock, beanFactory); + assertThat(beanFactory).isNotNull(); + assertThat(beanFactory).isSameAs(mock); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java index 6356eb45ee..b593f007ba 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java @@ -16,9 +16,7 @@ package org.springframework.integration.endpoint; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.Date; @@ -53,7 +51,7 @@ public class ServiceActivatorMethodResolutionTests { serviceActivator.handleMessage(new GenericMessage<>("foo")); Message result = outputChannel.receive(0); - assertEquals("FOO", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("FOO"); } @Test(expected = IllegalArgumentException.class) @@ -73,7 +71,7 @@ public class ServiceActivatorMethodResolutionTests { serviceActivator.handleMessage(new GenericMessage<>("foo")); Message result = outputChannel.receive(0); - assertEquals("FOO", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("FOO"); } @Test(expected = IllegalArgumentException.class) @@ -94,7 +92,7 @@ public class ServiceActivatorMethodResolutionTests { @Override protected Object handleRequestMessage(Message message) { Object o = super.handleRequestMessage(message); - assertSame(test, o); + assertThat(o).isSameAs(test); return null; } }; @@ -130,11 +128,11 @@ public class ServiceActivatorMethodResolutionTests { Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); - assertEquals(test, outputChannel.receive(10)); + assertThat(outputChannel.receive(10)).isEqualTo(test); test = new GenericMessage("foo"); serviceActivator.handleMessage(test); - assertEquals("FOO", outputChannel.receive(10).getPayload()); + assertThat(outputChannel.receive(10).getPayload()).isEqualTo("FOO"); } @Test @@ -163,11 +161,11 @@ public class ServiceActivatorMethodResolutionTests { Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); - assertEquals(test, outputChannel.receive(10)); + assertThat(outputChannel.receive(10)).isEqualTo(test); test = new GenericMessage("foo"); serviceActivator.handleMessage(test); - assertEquals("FOO", outputChannel.receive(10).getPayload()); + assertThat(outputChannel.receive(10).getPayload()).isEqualTo("FOO"); } @Test @@ -201,11 +199,11 @@ public class ServiceActivatorMethodResolutionTests { Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); - assertEquals(test, outputChannel.receive(10)); + assertThat(outputChannel.receive(10)).isEqualTo(test); test = new GenericMessage("foo"); serviceActivator.handleMessage(test); - assertNotEquals("FOO", outputChannel.receive(10).getPayload()); + assertThat(outputChannel.receive(10).getPayload()).isNotEqualTo("FOO"); } @Test @@ -239,11 +237,11 @@ public class ServiceActivatorMethodResolutionTests { Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); - assertEquals(test, outputChannel.receive(10)); + assertThat(outputChannel.receive(10)).isEqualTo(test); test = new GenericMessage("foo"); serviceActivator.handleMessage(test); - assertNotEquals("FOO", outputChannel.receive(10).getPayload()); + assertThat(outputChannel.receive(10).getPayload()).isNotEqualTo("FOO"); } @Test @@ -257,7 +255,7 @@ public class ServiceActivatorMethodResolutionTests { serviceActivator.handleMessage(new GenericMessage<>(new KafkaNull())); Message result = outputChannel.receive(0); - assertEquals("gotNull", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("gotNull"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/expression/DynamicExpressionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/expression/DynamicExpressionTests.java index cdd9b1e319..925412e955 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/expression/DynamicExpressionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/expression/DynamicExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.expression; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.FileOutputStream; @@ -50,9 +50,9 @@ public class DynamicExpressionTests { source.setBasename(basename); source.setCacheSeconds(0); DynamicExpression expression = new DynamicExpression(key, source); - assertEquals("Hello World!", expression.getValue()); + assertThat(expression.getValue()).isEqualTo("Hello World!"); writeExpressionStringToFile("toUpperCase()"); - assertEquals("FOO", expression.getValue("foo")); + assertThat(expression.getValue("foo")).isEqualTo("FOO"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java index aa6b2eea83..636d2181e6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/expression/ExpressionUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 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,10 +16,7 @@ package org.springframework.integration.expression; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -50,12 +47,12 @@ public class ExpressionUtilsTests { new RootBeanDefinition(ConversionServiceFactoryBean.class)); context.refresh(); StandardEvaluationContext evalContext = ExpressionUtils.createStandardEvaluationContext(context); - assertNotNull(evalContext.getBeanResolver()); - assertNotNull(evalContext.getTypeConverter()); + assertThat(evalContext.getBeanResolver()).isNotNull(); + assertThat(evalContext.getTypeConverter()).isNotNull(); IntegrationEvaluationContextFactoryBean factory = context.getBean("&" + IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, IntegrationEvaluationContextFactoryBean.class); - assertSame(evalContext.getTypeConverter(), TestUtils.getPropertyValue(factory, "typeConverter")); + assertThat(TestUtils.getPropertyValue(factory, "typeConverter")).isSameAs(evalContext.getTypeConverter()); } @@ -66,11 +63,11 @@ public class ExpressionUtilsTests { new RootBeanDefinition(IntegrationEvaluationContextFactoryBean.class)); context.refresh(); StandardEvaluationContext evalContext = ExpressionUtils.createStandardEvaluationContext(context); - assertNotNull(evalContext.getBeanResolver()); + assertThat(evalContext.getBeanResolver()).isNotNull(); TypeConverter typeConverter = evalContext.getTypeConverter(); - assertNotNull(typeConverter); - assertSame(DefaultConversionService.getSharedInstance(), - TestUtils.getPropertyValue(typeConverter, "conversionService")); + assertThat(typeConverter).isNotNull(); + assertThat(TestUtils.getPropertyValue(typeConverter, "conversionService")) + .isSameAs(DefaultConversionService.getSharedInstance()); } @Test @@ -80,22 +77,22 @@ public class ExpressionUtilsTests { new RootBeanDefinition(ConversionServiceFactoryBean.class)); context.refresh(); StandardEvaluationContext evalContext = ExpressionUtils.createStandardEvaluationContext(context); - assertNotNull(evalContext.getBeanResolver()); + assertThat(evalContext.getBeanResolver()).isNotNull(); TypeConverter typeConverter = evalContext.getTypeConverter(); - assertNotNull(typeConverter); - assertNotSame(DefaultConversionService.getSharedInstance(), - TestUtils.getPropertyValue(typeConverter, "conversionService")); - assertSame(context.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME), - TestUtils.getPropertyValue(typeConverter, "conversionService")); + assertThat(typeConverter).isNotNull(); + assertThat(TestUtils.getPropertyValue(typeConverter, "conversionService")) + .isNotSameAs(DefaultConversionService.getSharedInstance()); + assertThat(TestUtils.getPropertyValue(typeConverter, "conversionService")) + .isSameAs(context.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME)); } @Test public void testEvaluationContextNoBeanFactory() { StandardEvaluationContext evalContext = ExpressionUtils.createStandardEvaluationContext(); - assertNull(evalContext.getBeanResolver()); + assertThat(evalContext.getBeanResolver()).isNull(); TypeConverter typeConverter = evalContext.getTypeConverter(); - assertNotNull(typeConverter); - assertSame(DefaultConversionService.getSharedInstance(), - TestUtils.getPropertyValue(typeConverter, "conversionService")); + assertThat(typeConverter).isNotNull(); + assertThat(TestUtils.getPropertyValue(typeConverter, "conversionService")) + .isSameAs(DefaultConversionService.getSharedInstance()); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java index 8c307dc0e1..fdd50186d8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,7 @@ package org.springframework.integration.expression; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -70,7 +69,7 @@ public class ForeignClassloaderTests { }); t.start(); Message reply = bar.receive(10000); - assertThat(reply.getPayload(), instanceOf(Foo.class)); + assertThat(reply.getPayload()).isInstanceOf(Foo.class); } public static class Foo { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/expression/ParentContextTests.java b/spring-integration-core/src/test/java/org/springframework/integration/expression/ParentContextTests.java index ece3c51ce1..d184b3fad4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/expression/ParentContextTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/expression/ParentContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2015 the original author or authors. + * Copyright 2013-2019 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,24 +16,16 @@ package org.springframework.integration.expression; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; -import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.beans.BeansException; @@ -59,11 +51,12 @@ import org.springframework.messaging.support.GenericMessage; /** * @author Gary Russell * @author Artem Bilan + * * @since 3.0 */ public class ParentContextTests { - private static final List evalContexts = new ArrayList(); + private static final List evalContexts = new ArrayList<>(); /** * Verifies that beans in hierarchical contexts get an evaluation context that has the proper @@ -80,18 +73,18 @@ public class ParentContextTests { */ @Test @SuppressWarnings("unchecked") - public void testSpelBeanReferencesInChildAndParent() throws Exception { + public void testSpelBeanReferencesInChildAndParent() { AbstractApplicationContext parent = new ClassPathXmlApplicationContext("ParentContext-context.xml", this.getClass()); Object parentEvaluationContextFactoryBean = parent.getBean(IntegrationEvaluationContextFactoryBean.class); Map parentFunctions = TestUtils.getPropertyValue(parentEvaluationContextFactoryBean, "functions", Map.class); - assertEquals(4, parentFunctions.size()); + assertThat(parentFunctions.size()).isEqualTo(4); Object jsonPath = parentFunctions.get("jsonPath"); - assertNotNull(jsonPath); - assertThat((Method) jsonPath, Matchers.isOneOf(JsonPathUtils.class.getMethods())); - assertEquals(2, evalContexts.size()); + assertThat(jsonPath).isNotNull(); + assertThat(jsonPath).isIn(Arrays.asList(JsonPathUtils.class.getMethods())); + assertThat(evalContexts.size()).isEqualTo(2); ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext(parent); child.setConfigLocation("org/springframework/integration/expression/ChildContext-context.xml"); child.refresh(); @@ -99,95 +92,90 @@ public class ParentContextTests { Object childEvaluationContextFactoryBean = child.getBean(IntegrationEvaluationContextFactoryBean.class); Map childFunctions = TestUtils.getPropertyValue(childEvaluationContextFactoryBean, "functions", Map.class); - assertEquals(5, childFunctions.size()); - assertTrue(childFunctions.containsKey("barParent")); - assertTrue(childFunctions.containsKey("fooFunc")); + assertThat(childFunctions.size()).isEqualTo(5); + assertThat(childFunctions.containsKey("barParent")).isTrue(); + assertThat(childFunctions.containsKey("fooFunc")).isTrue(); jsonPath = childFunctions.get("jsonPath"); - assertNotNull(jsonPath); - assertThat((Method) jsonPath, Matchers.not(Matchers.isOneOf(JsonPathUtils.class.getMethods()))); - assertEquals(3, evalContexts.size()); - assertSame(evalContexts.get(0).getBeanResolver(), evalContexts.get(1).getBeanResolver()); + assertThat(jsonPath).isNotNull(); + assertThat(jsonPath).isNotIn(Arrays.asList((JsonPathUtils.class.getMethods()))); + assertThat(evalContexts.size()).isEqualTo(3); + assertThat(evalContexts.get(1).getBeanResolver()).isSameAs(evalContexts.get(0).getBeanResolver()); List propertyAccessors = evalContexts.get(0).getPropertyAccessors(); - assertEquals(4, propertyAccessors.size()); - PropertyAccessor parentPropertyAccessorOverride = parent.getBean("jsonPropertyAccessor", PropertyAccessor.class); + assertThat(propertyAccessors.size()).isEqualTo(4); + PropertyAccessor parentPropertyAccessorOverride = parent + .getBean("jsonPropertyAccessor", PropertyAccessor.class); PropertyAccessor parentPropertyAccessor = parent.getBean("parentJsonPropertyAccessor", PropertyAccessor.class); - assertTrue(propertyAccessors.contains(parentPropertyAccessorOverride)); - assertTrue(propertyAccessors.contains(parentPropertyAccessor)); - assertTrue(propertyAccessors.indexOf(parentPropertyAccessorOverride) > propertyAccessors.indexOf(parentPropertyAccessor)); + assertThat(propertyAccessors.contains(parentPropertyAccessorOverride)).isTrue(); + assertThat(propertyAccessors.contains(parentPropertyAccessor)).isTrue(); + assertThat(propertyAccessors.indexOf(parentPropertyAccessorOverride) > propertyAccessors + .indexOf(parentPropertyAccessor)).isTrue(); Map variables = (Map) TestUtils.getPropertyValue(evalContexts.get(0), "variables"); - assertEquals(4, variables.size()); - assertTrue(variables.containsKey("bar")); - assertTrue(variables.containsKey("barParent")); - assertTrue(variables.containsKey("fooFunc")); - assertTrue(variables.containsKey("jsonPath")); + assertThat(variables).hasSize(4); + assertThat(variables).containsKeys("bar", "barParent", "fooFunc", "jsonPath"); - assertNotSame(evalContexts.get(1).getBeanResolver(), evalContexts.get(2).getBeanResolver()); + assertThat(evalContexts.get(2).getBeanResolver()).isNotSameAs(evalContexts.get(1).getBeanResolver()); propertyAccessors = evalContexts.get(1).getPropertyAccessors(); - assertEquals(4, propertyAccessors.size()); - assertTrue(propertyAccessors.contains(parentPropertyAccessorOverride)); + assertThat(propertyAccessors.size()).isEqualTo(4); + assertThat(propertyAccessors.contains(parentPropertyAccessorOverride)).isTrue(); variables = (Map) TestUtils.getPropertyValue(evalContexts.get(1), "variables"); - assertEquals(4, variables.size()); - assertTrue(variables.containsKey("bar")); - assertTrue(variables.containsKey("barParent")); - assertTrue(variables.containsKey("fooFunc")); - assertTrue(variables.containsKey("jsonPath")); + assertThat(variables).hasSize(4); + assertThat(variables).containsKeys("bar", "barParent", "fooFunc", "jsonPath"); propertyAccessors = evalContexts.get(2).getPropertyAccessors(); - assertEquals(4, propertyAccessors.size()); + assertThat(propertyAccessors.size()).isEqualTo(4); PropertyAccessor childPropertyAccessor = child.getBean("jsonPropertyAccessor", PropertyAccessor.class); - assertTrue(propertyAccessors.contains(childPropertyAccessor)); - assertTrue(propertyAccessors.contains(parentPropertyAccessor)); - assertFalse(propertyAccessors.contains(parentPropertyAccessorOverride)); - assertTrue(propertyAccessors.indexOf(childPropertyAccessor) < propertyAccessors.indexOf(parentPropertyAccessor)); + assertThat(propertyAccessors.contains(childPropertyAccessor)).isTrue(); + assertThat(propertyAccessors.contains(parentPropertyAccessor)).isTrue(); + assertThat(propertyAccessors.contains(parentPropertyAccessorOverride)).isFalse(); + assertThat(propertyAccessors.indexOf(childPropertyAccessor) < propertyAccessors.indexOf(parentPropertyAccessor)) + .isTrue(); variables = (Map) TestUtils.getPropertyValue(evalContexts.get(2), "variables"); - assertEquals(5, variables.size()); - assertTrue(variables.containsKey("bar")); - assertTrue(variables.containsKey("barParent")); - assertTrue(variables.containsKey("fooFunc")); - assertTrue(variables.containsKey("barChild")); - assertTrue(variables.containsKey("jsonPath")); + assertThat(variables).hasSize(5); + assertThat(variables).containsKeys("bar", "barParent", "fooFunc", "barChild", "jsonPath"); // Test transformer expressions - child.getBean("input", MessageChannel.class).send(new GenericMessage("baz")); + child.getBean("input", MessageChannel.class).send(new GenericMessage<>("baz")); Message out = child.getBean("output", QueueChannel.class).receive(0); - assertNotNull(out); - assertEquals("foobar", out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getPayload()).isEqualTo("foobar"); child.getBean("parentIn", MessageChannel.class).send(MutableMessageBuilder.withPayload("bar").build()); out = child.getBean("parentOut", QueueChannel.class).receive(0); - assertNotNull(out); - assertThat(out, instanceOf(GenericMessage.class)); - assertEquals("foo", out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out).isInstanceOf(GenericMessage.class); + assertThat(out.getPayload()).isEqualTo("foo"); IntegrationEvaluationContextFactoryBean evaluationContextFactoryBean = child.getBean("&" + IntegrationContextUtils.INTEGRATION_EVALUATION_CONTEXT_BEAN_NAME, IntegrationEvaluationContextFactoryBean.class); try { - evaluationContextFactoryBean.setPropertyAccessors(Collections.emptyMap()); + evaluationContextFactoryBean.setPropertyAccessors(Collections.emptyMap()); fail("IllegalArgumentException expected."); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(IllegalArgumentException.class)); + assertThat(e).isInstanceOf(IllegalArgumentException.class); } - parent.getBean("fromParentToChild", MessageChannel.class).send(new GenericMessage("foo")); + parent.getBean("fromParentToChild", MessageChannel.class).send(new GenericMessage<>("foo")); out = child.getBean("output", QueueChannel.class).receive(0); - assertNotNull(out); - assertEquals("org.springframework.integration.support.MutableMessage", out.getClass().getName()); - assertEquals("FOO", out.getPayload()); + assertThat(out).isNotNull(); + assertThat(out.getClass().getName()).isEqualTo("org.springframework.integration.support.MutableMessage"); + assertThat(out.getPayload()).isEqualTo("FOO"); - assertTrue(parent - .containsBean(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME)); + assertThat(parent + .containsBean(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME)) + .isTrue(); - assertTrue(child - .containsBean(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME)); + assertThat(child + .containsBean(IntegrationContextUtils.TO_STRING_FRIENDLY_JSON_NODE_TO_STRING_CONVERTER_BEAN_NAME)) + .isTrue(); Object converterRegistrar = parent.getBean(IntegrationContextUtils.CONVERTER_REGISTRAR_BEAN_NAME); - assertNotNull(converterRegistrar); + assertThat(converterRegistrar).isNotNull(); Set converters = TestUtils.getPropertyValue(converterRegistrar, "converters", Set.class); boolean toStringFriendlyJsonNodeToStringConverterPresent = false; for (Object converter : converters) { @@ -197,7 +185,7 @@ public class ParentContextTests { } } - assertTrue(toStringFriendlyJsonNodeToStringConverterPresent); + assertThat(toStringFriendlyJsonNodeToStringConverterPresent).isTrue(); MessageChannel input = parent.getBean("testJsonNodeToStringConverterInputChannel", MessageChannel.class); PollableChannel output = parent.getBean("testJsonNodeToStringConverterOutputChannel", PollableChannel.class); @@ -208,8 +196,8 @@ public class ParentContextTests { input.send(new GenericMessage(person)); Message result = output.receive(1000); - assertNotNull(result); - assertEquals("JOHN", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("JOHN"); child.close(); parent.close(); @@ -225,7 +213,7 @@ public class ParentContextTests { } @Override - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { evalContexts.add(ExpressionUtils.createStandardEvaluationContext(this.beanFactory)); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java index e7b0c9e448..566b3f4459 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.filter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -52,12 +51,12 @@ public class DynamicExpressionFilterIntegrationTests { this.input.send(new GenericMessage(0)); this.input.send(new GenericMessage(99)); this.input.send(new GenericMessage(-99)); - assertEquals(new Integer(1), positives.receive(0).getPayload()); - assertEquals(new Integer(99), positives.receive(0).getPayload()); - assertEquals(new Integer(0), negatives.receive(0).getPayload()); - assertEquals(new Integer(-99), negatives.receive(0).getPayload()); - assertNull(positives.receive(0)); - assertNull(negatives.receive(0)); + assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(1)); + assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(99)); + assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(0)); + assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(-99)); + assertThat(positives.receive(0)).isNull(); + assertThat(negatives.receive(0)).isNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterAnnotationMethodResolutionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterAnnotationMethodResolutionTests.java index c4d2485b35..dca1b5f881 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterAnnotationMethodResolutionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterAnnotationMethodResolutionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.filter; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -50,9 +48,9 @@ public class FilterAnnotationMethodResolutionTests { QueueChannel replyChannel = new QueueChannel(); handler.handleMessage(MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build()); Message result = replyChannel.receive(0); - assertNotNull(result); - assertTrue(filter.invokedCorrectMethod); - assertFalse(filter.invokedIncorrectMethod); + assertThat(result).isNotNull(); + assertThat(filter.invokedCorrectMethod).isTrue(); + assertThat(filter.invokedIncorrectMethod).isFalse(); testApplicationContext.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterContextTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterContextTests.java index a8ac9183b0..bc6c6747ca 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterContextTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/FilterContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.filter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,20 +54,20 @@ public class FilterContextTests { public void methodInvokingFilterRejects() { this.input.send(new GenericMessage("foo")); Message reply = this.output.receive(0); - assertNull(reply); + assertThat(reply).isNull(); - assertTrue(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isTrue(); this.pojoFilter.stop(); - assertFalse(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isFalse(); this.pojoFilter.start(); - assertTrue(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isTrue(); } @Test public void methodInvokingFilterAccepts() { this.input.send(new GenericMessage("foobar")); Message reply = this.output.receive(0); - assertEquals("foobar", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("foobar"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java index d5db8dc1cd..8adeb02645 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.filter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -43,8 +40,8 @@ public class MessageFilterTests { filter.setOutputChannel(output); filter.handleMessage(message); Message received = output.receive(0); - assertEquals(message.getPayload(), received.getPayload()); - assertEquals(message.getHeaders().getId(), received.getHeaders().getId()); + assertThat(received.getPayload()).isEqualTo(message.getPayload()); + assertThat(received.getHeaders().getId()).isEqualTo(message.getHeaders().getId()); } @Test @@ -53,7 +50,7 @@ public class MessageFilterTests { QueueChannel output = new QueueChannel(); filter.setOutputChannel(output); filter.handleMessage(new GenericMessage("test")); - assertNull(output.receive(0)); + assertThat(output.receive(0)).isNull(); } @Test(expected = MessageRejectedException.class) @@ -74,10 +71,10 @@ public class MessageFilterTests { EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); endpoint.start(); Message message = new GenericMessage("test"); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); Message reply = outputChannel.receive(0); - assertNotNull(reply); - assertEquals(message.getPayload(), reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo(message.getPayload()); } @Test @@ -89,8 +86,8 @@ public class MessageFilterTests { EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); endpoint.start(); Message message = new GenericMessage("test"); - assertTrue(inputChannel.send(message)); - assertNull(outputChannel.receive(0)); + assertThat(inputChannel.send(message)).isTrue(); + assertThat(outputChannel.receive(0)).isNull(); } @Test(expected = MessageRejectedException.class) @@ -103,7 +100,7 @@ public class MessageFilterTests { EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); endpoint.start(); Message message = new GenericMessage("test"); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); } @Test @@ -117,11 +114,11 @@ public class MessageFilterTests { EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); endpoint.start(); Message message = new GenericMessage("test"); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); Message reply = discardChannel.receive(0); - assertNotNull(reply); - assertEquals(message, reply); - assertNull(outputChannel.receive(0)); + assertThat(reply).isNotNull(); + assertThat(reply).isEqualTo(message); + assertThat(outputChannel.receive(0)).isNull(); } @Test(expected = MessageRejectedException.class) @@ -137,16 +134,16 @@ public class MessageFilterTests { endpoint.start(); Message message = new GenericMessage("test"); try { - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); } catch (Exception e) { throw e; } finally { Message reply = discardChannel.receive(0); - assertNotNull(reply); - assertEquals(message, reply); - assertNull(outputChannel.receive(0)); + assertThat(reply).isNotNull(); + assertThat(reply).isEqualTo(message); + assertThat(outputChannel.receive(0)).isNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java index 2941682606..635e9126b8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java @@ -16,8 +16,7 @@ package org.springframework.integration.filter; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; @@ -40,7 +39,7 @@ public class MethodInvokingSelectorTests { public void acceptedWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "acceptString"); selector.setBeanFactory(mock(BeanFactory.class)); - assertTrue(selector.accept(new GenericMessage<>("should accept"))); + assertThat(selector.accept(new GenericMessage<>("should accept"))).isTrue(); } @Test @@ -49,14 +48,14 @@ public class MethodInvokingSelectorTests { Method method = testBean.getClass().getMethod("acceptString", Message.class); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); selector.setBeanFactory(mock(BeanFactory.class)); - assertTrue(selector.accept(new GenericMessage<>("should accept"))); + assertThat(selector.accept(new GenericMessage<>("should accept"))).isTrue(); } @Test public void rejectedWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "acceptString"); selector.setBeanFactory(mock(BeanFactory.class)); - assertFalse(selector.accept(new GenericMessage<>(99))); + assertThat(selector.accept(new GenericMessage<>(99))).isFalse(); } @Test @@ -65,14 +64,14 @@ public class MethodInvokingSelectorTests { Method method = testBean.getClass().getMethod("acceptString", Message.class); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); selector.setBeanFactory(mock(BeanFactory.class)); - assertFalse(selector.accept(new GenericMessage<>(99))); + assertThat(selector.accept(new GenericMessage<>(99))).isFalse(); } @Test public void noArgMethodWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "noArgs"); selector.setBeanFactory(mock(BeanFactory.class)); - assertTrue(selector.accept(new GenericMessage<>("test"))); + assertThat(selector.accept(new GenericMessage<>("test"))).isTrue(); } @Test @@ -81,7 +80,7 @@ public class MethodInvokingSelectorTests { Method method = testBean.getClass().getMethod("noArgs"); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); selector.setBeanFactory(mock(BeanFactory.class)); - assertTrue(selector.accept(new GenericMessage<>("test"))); + assertThat(selector.accept(new GenericMessage<>("test"))).isTrue(); } @Test(expected = IllegalArgumentException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java index f932b0e883..fe83c5dfa1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.filter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -61,12 +60,12 @@ public class SpelFilterIntegrationTests { this.simpleInput.send(new GenericMessage(0)); this.simpleInput.send(new GenericMessage(99)); this.simpleInput.send(new GenericMessage(-99)); - assertEquals(new Integer(1), positives.receive(0).getPayload()); - assertEquals(new Integer(99), positives.receive(0).getPayload()); - assertEquals(new Integer(0), negatives.receive(0).getPayload()); - assertEquals(new Integer(-99), negatives.receive(0).getPayload()); - assertNull(positives.receive(0)); - assertNull(negatives.receive(0)); + assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(1)); + assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(99)); + assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(0)); + assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(-99)); + assertThat(positives.receive(0)).isNull(); + assertThat(negatives.receive(0)).isNull(); } @Test @@ -75,12 +74,12 @@ public class SpelFilterIntegrationTests { this.beanResolvingInput.send(new GenericMessage(2)); this.beanResolvingInput.send(new GenericMessage(9)); this.beanResolvingInput.send(new GenericMessage(22)); - assertEquals(new Integer(1), odds.receive(0).getPayload()); - assertEquals(new Integer(9), odds.receive(0).getPayload()); - assertEquals(new Integer(2), evens.receive(0).getPayload()); - assertEquals(new Integer(22), evens.receive(0).getPayload()); - assertNull(odds.receive(0)); - assertNull(evens.receive(0)); + assertThat(odds.receive(0).getPayload()).isEqualTo(new Integer(1)); + assertThat(odds.receive(0).getPayload()).isEqualTo(new Integer(9)); + assertThat(evens.receive(0).getPayload()).isEqualTo(new Integer(2)); + assertThat(evens.receive(0).getPayload()).isEqualTo(new Integer(22)); + assertThat(odds.receive(0)).isNull(); + assertThat(evens.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java index 60f943da06..148c7fd056 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.time.Duration; @@ -70,8 +67,8 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); Future> f = service.returnMessage("foo"); Object result = f.get(10000, TimeUnit.MILLISECONDS); - assertNotNull(result); - assertEquals("foobar", ((Message) result).getPayload()); + assertThat(result).isNotNull(); + assertThat(((Message) result).getPayload()).isEqualTo("foobar"); } @Test @@ -98,7 +95,7 @@ public class AsyncGatewayTests { fail("Expected Exception"); } catch (ExecutionException e) { - assertEquals(error, e.getCause()); + assertThat(e.getCause()).isEqualTo(error); } } @@ -131,12 +128,12 @@ public class AsyncGatewayTests { } }); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); long elapsed = System.currentTimeMillis() - start; - assertTrue(elapsed >= 200); - assertEquals("foobar", result.get().getPayload()); + assertThat(elapsed >= 200).isTrue(); + assertThat(result.get().getPayload()).isEqualTo("foobar"); Object thread = result.get().getHeaders().get("thread"); - assertNotEquals(Thread.currentThread(), thread); + assertThat(thread).isNotEqualTo(Thread.currentThread()); } @Test @@ -153,8 +150,8 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); CustomFuture f = service.returnCustomFuture("foo"); String result = f.get(10000, TimeUnit.MILLISECONDS); - assertEquals("foobar", result); - assertEquals(Thread.currentThread(), f.thread); + assertThat(result).isEqualTo("foobar"); + assertThat(f.thread).isEqualTo(Thread.currentThread()); } @Test @@ -174,8 +171,8 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); CustomFuture f = (CustomFuture) service.returnCustomFutureWithTypeFuture("foo"); String result = f.get(10000, TimeUnit.MILLISECONDS); - assertEquals("foobar", result); - assertEquals(Thread.currentThread(), f.thread); + assertThat(result).isEqualTo("foobar"); + assertThat(f.thread).isEqualTo(Thread.currentThread()); } protected void addThreadEnricher(QueueChannel requestChannel) { @@ -204,8 +201,8 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); Future f = service.returnString("foo"); Object result = f.get(10000, TimeUnit.MILLISECONDS); - assertNotNull(result); - assertEquals("foobar", result); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("foobar"); } @Test @@ -221,8 +218,8 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); Future f = service.returnSomething("foo"); Object result = f.get(10000, TimeUnit.MILLISECONDS); - assertTrue(result instanceof String); - assertEquals("foobar", result); + assertThat(result instanceof String).isTrue(); + assertThat(result).isEqualTo("foobar"); } @@ -239,7 +236,7 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); Mono> mono = service.returnMessagePromise("foo"); Object result = mono.block(Duration.ofSeconds(10)); - assertEquals("foobar", ((Message) result).getPayload()); + assertThat(((Message) result).getPayload()).isEqualTo("foobar"); } @Test @@ -255,7 +252,7 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); Mono mono = service.returnStringPromise("foo"); Object result = mono.block(Duration.ofSeconds(10)); - assertEquals("foobar", result); + assertThat(result).isEqualTo("foobar"); } @Test @@ -271,8 +268,8 @@ public class AsyncGatewayTests { TestEchoService service = (TestEchoService) proxyFactory.getObject(); Mono mono = service.returnSomethingPromise("foo"); Object result = mono.block(Duration.ofSeconds(10)); - assertNotNull(result); - assertEquals("foobar", result); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("foobar"); } @Test @@ -297,7 +294,7 @@ public class AsyncGatewayTests { }); latch.await(10, TimeUnit.SECONDS); - assertEquals("foobar", result.get()); + assertThat(result.get()).isEqualTo("foobar"); } private static void startResponder(final PollableChannel requestChannel) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java index b795fcfacb..1457cc09c2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,18 +16,7 @@ package org.springframework.integration.gateway; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -169,21 +158,21 @@ public class GatewayInterfaceTests { final Method fooMethod = Foo.class.getMethod("foo", String.class); final AtomicBoolean called = new AtomicBoolean(); MessageHandler handler = message -> { - assertThat(message.getHeaders().get("name"), equalTo("foo")); - assertThat(message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway." + - "GatewayInterfaceTests$Foo.foo(java.lang.String)")); - assertThat(message.getHeaders().get("object"), equalTo(fooMethod)); - assertThat(message.getPayload(), equalTo("hello")); - assertThat(new MessageHeaderAccessor(message).getErrorChannel(), equalTo("errorChannel")); + assertThat(message.getHeaders().get("name")).isEqualTo("foo"); + assertThat(message.getHeaders().get("string")) + .isEqualTo("public abstract void org.springframework.integration.gateway." + + "GatewayInterfaceTests$Foo.foo(java.lang.String)"); + assertThat(message.getHeaders().get("object")).isEqualTo(fooMethod); + assertThat(message.getPayload()).isEqualTo("hello"); + assertThat(new MessageHeaderAccessor(message).getErrorChannel()).isEqualTo("errorChannel"); called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); bar.foo("hello"); - assertTrue(called.get()); + assertThat(called.get()).isTrue(); Map gateways = TestUtils.getPropertyValue(ac.getBean("&sampleGateway"), "gatewayMap", Map.class); - assertEquals(5, gateways.size()); + assertThat(gateways.size()).isEqualTo(5); ac.close(); } @@ -195,18 +184,18 @@ public class GatewayInterfaceTests { final Method fooMethod = Foo.class.getMethod("foo", String.class); final AtomicBoolean called = new AtomicBoolean(); MessageHandler handler = message -> { - assertThat(message.getHeaders().get("name"), equalTo("foo")); - assertThat(message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway." + - "GatewayInterfaceTests$Foo.foo(java.lang.String)")); - assertThat(message.getHeaders().get("object"), equalTo(fooMethod)); - assertThat(message.getPayload(), equalTo("foo")); + assertThat(message.getHeaders().get("name")).isEqualTo("foo"); + assertThat(message.getHeaders().get("string")) + .isEqualTo("public abstract void org.springframework.integration.gateway." + + "GatewayInterfaceTests$Foo.foo(java.lang.String)"); + assertThat(message.getHeaders().get("object")).isEqualTo(fooMethod); + assertThat(message.getPayload()).isEqualTo("foo"); called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); bar.foo("hello"); - assertTrue(called.get()); + assertThat(called.get()).isTrue(); ac.close(); } @@ -231,18 +220,18 @@ public class GatewayInterfaceTests { final Method bazMethod = Foo.class.getMethod("baz", String.class); final AtomicBoolean called = new AtomicBoolean(); MessageHandler handler = message -> { - assertThat(message.getHeaders().get("name"), equalTo("overrideGlobal")); - assertThat(message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway." + - "GatewayInterfaceTests$Foo.baz(java.lang.String)")); - assertThat(message.getHeaders().get("object"), equalTo(bazMethod)); - assertThat(message.getPayload(), equalTo("hello")); + assertThat(message.getHeaders().get("name")).isEqualTo("overrideGlobal"); + assertThat(message.getHeaders().get("string")) + .isEqualTo("public abstract void org.springframework.integration.gateway." + + "GatewayInterfaceTests$Foo.baz(java.lang.String)"); + assertThat(message.getHeaders().get("object")).isEqualTo(bazMethod); + assertThat(message.getPayload()).isEqualTo("hello"); called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); bar.baz("hello"); - assertTrue(called.get()); + assertThat(called.get()).isTrue(); ac.close(); } @@ -254,18 +243,18 @@ public class GatewayInterfaceTests { final Method quxMethod = Bar.class.getMethod("qux", String.class, String.class); final AtomicBoolean called = new AtomicBoolean(); MessageHandler handler = message -> { - assertThat(message.getHeaders().get("name"), equalTo("arg1")); - assertThat(message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway." + - "GatewayInterfaceTests$Bar.qux(java.lang.String,java.lang.String)")); - assertThat(message.getHeaders().get("object"), equalTo(quxMethod)); - assertThat(message.getPayload(), equalTo("hello")); + assertThat(message.getHeaders().get("name")).isEqualTo("arg1"); + assertThat(message.getHeaders().get("string")) + .isEqualTo("public abstract void org.springframework.integration.gateway." + + "GatewayInterfaceTests$Bar.qux(java.lang.String,java.lang.String)"); + assertThat(message.getHeaders().get("object")).isEqualTo(quxMethod); + assertThat(message.getPayload()).isEqualTo("hello"); called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); bar.qux("hello", "arg1"); - assertTrue(called.get()); + assertThat(called.get()).isTrue(); ac.close(); } @@ -303,7 +292,7 @@ public class GatewayInterfaceTests { MessageHandler handler = mock(MessageHandler.class); channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); - assertEquals(bar.hashCode(), ac.getBean(Bar.class).hashCode()); + assertThat(ac.getBean(Bar.class).hashCode()).isEqualTo(bar.hashCode()); verify(handler, times(0)).handleMessage(Mockito.any(Message.class)); ac.close(); } @@ -329,7 +318,7 @@ public class GatewayInterfaceTests { MessageHandler handler = mock(MessageHandler.class); channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); - assertSame(bar, ac.getBean(Bar.class)); + assertThat(ac.getBean(Bar.class)).isSameAs(bar); GatewayProxyFactoryBean fb = new GatewayProxyFactoryBean(Bar.class); DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerSingleton("requestChannelBar", channel); @@ -337,7 +326,7 @@ public class GatewayInterfaceTests { bf.registerSingleton("requestChannelFoo", channel); fb.setBeanFactory(bf); fb.afterPropertiesSet(); - assertNotSame(bar, fb.getObject()); + assertThat(fb.getObject()).isNotSameAs(bar); verify(handler, times(0)).handleMessage(Mockito.any(Message.class)); ac.close(); } @@ -367,13 +356,13 @@ public class GatewayInterfaceTests { DirectChannel channel = ac.getBean("requestChannelBaz", DirectChannel.class); final AtomicBoolean called = new AtomicBoolean(); MessageHandler handler = message -> { - assertThat(message.getPayload(), equalTo("fizbuz")); + assertThat(message.getPayload()).isEqualTo("fizbuz"); called.set(true); }; channel.subscribe(handler); Baz baz = ac.getBean(Baz.class); baz.baz("hello"); - assertTrue(called.get()); + assertThat(called.get()).isTrue(); ac.close(); } @@ -388,13 +377,13 @@ public class GatewayInterfaceTests { Bar baz = ac.getBean(Bar.class); String reply = baz.lateReply("hello", 1000, 0); - assertNull(reply); + assertThat(reply).isNull(); PollableChannel errorChannel = ac.getBean("errorChannel", PollableChannel.class); Message receive = errorChannel.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); MessagingException messagingException = (MessagingException) receive.getPayload(); - assertThat(messagingException.getMessage(), - startsWith("Reply message received but the receiving thread has exited due to a timeout")); + assertThat(messagingException.getMessage()) + .startsWith("Reply message received but the receiving thread has exited due to a timeout"); ac.close(); } @@ -402,10 +391,10 @@ public class GatewayInterfaceTests { public void testInt2634() { Map param = Collections.singletonMap(1, 1); Object result = this.int2634Gateway.test2(param); - assertEquals(param, result); + assertThat(result).isEqualTo(param); result = this.int2634Gateway.test1(param); - assertEquals(param, result); + assertThat(result).isEqualTo(param); } /* @@ -414,19 +403,19 @@ public class GatewayInterfaceTests { */ @Test public void testExecs() throws Exception { - assertSame(exec, TestUtils.getPropertyValue(execGatewayFB, "asyncExecutor")); - assertNull(TestUtils.getPropertyValue(noExecGatewayFB, "asyncExecutor")); + assertThat(TestUtils.getPropertyValue(execGatewayFB, "asyncExecutor")).isSameAs(exec); + assertThat(TestUtils.getPropertyValue(noExecGatewayFB, "asyncExecutor")).isNull(); Future result = this.int2634Gateway.test3(Thread.currentThread()); - assertNotEquals(Thread.currentThread(), result.get()); - assertThat(result.get().getName(), startsWith("SimpleAsync")); + assertThat(result.get()).isNotEqualTo(Thread.currentThread()); + assertThat(result.get().getName()).startsWith("SimpleAsync"); result = this.execGateway.test1(Thread.currentThread()); - assertNotEquals(Thread.currentThread(), result.get()); - assertThat(result.get().getName(), startsWith("exec-")); + assertThat(result.get()).isNotEqualTo(Thread.currentThread()); + assertThat(result.get().getName()).startsWith("exec-"); result = this.noExecGateway.test1(Thread.currentThread()); - assertEquals(Thread.currentThread(), result.get()); + assertThat(result.get()).isEqualTo(Thread.currentThread()); ListenableFuture result2 = this.execGateway.test2(Thread.currentThread()); final CountDownLatch latch = new CountDownLatch(1); @@ -443,56 +432,53 @@ public class GatewayInterfaceTests { public void onFailure(Throwable t) { } }); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertThat(result2.get().getName(), startsWith("exec-")); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(result2.get().getName()).startsWith("exec-"); /* @IntegrationComponentScan(useDefaultFilters = false, includeFilters = @ComponentScan.Filter(TestMessagingGateway.class)) excludes this a candidate */ - assertNull(this.notAGatewayByScanFilter); + assertThat(this.notAGatewayByScanFilter).isNull(); } @Test public void testAutoCreateChannelGateway() { - assertEquals("foo", this.autoCreateChannelService.service("foo")); + assertThat(this.autoCreateChannelService.service("foo")).isEqualTo("foo"); } @Test @SuppressWarnings("rawtypes") public void testAnnotationGatewayProxyFactoryBean() { - assertNotNull(this.gatewayByAnnotationGPFB); - assertNull(this.notActivatedByProfileGateway); + assertThat(this.gatewayByAnnotationGPFB).isNotNull(); + assertThat(this.notActivatedByProfileGateway).isNull(); - assertSame(this.exec, this.annotationGatewayProxyFactoryBean.getAsyncExecutor()); - assertEquals(1111L, - TestUtils.getPropertyValue(this.annotationGatewayProxyFactoryBean, - "defaultRequestTimeout", Expression.class).getValue()); - assertEquals(222L, - TestUtils.getPropertyValue(this.annotationGatewayProxyFactoryBean, - "defaultReplyTimeout", Expression.class).getValue()); + assertThat(this.annotationGatewayProxyFactoryBean.getAsyncExecutor()).isSameAs(this.exec); + assertThat(TestUtils.getPropertyValue(this.annotationGatewayProxyFactoryBean, + "defaultRequestTimeout", Expression.class).getValue()).isEqualTo(1111L); + assertThat(TestUtils.getPropertyValue(this.annotationGatewayProxyFactoryBean, + "defaultReplyTimeout", Expression.class).getValue()).isEqualTo(222L); Collection messagingGateways = this.annotationGatewayProxyFactoryBean.getGateways().values(); - assertEquals(1, messagingGateways.size()); + assertThat(messagingGateways.size()).isEqualTo(1); MessagingGatewaySupport gateway = messagingGateways.iterator().next(); - assertSame(this.gatewayChannel, gateway.getRequestChannel()); - assertSame(this.gatewayChannel, gateway.getReplyChannel()); - assertSame(this.errorChannel, gateway.getErrorChannel()); + assertThat(gateway.getRequestChannel()).isSameAs(this.gatewayChannel); + assertThat(gateway.getReplyChannel()).isSameAs(this.gatewayChannel); + assertThat(gateway.getErrorChannel()).isSameAs(this.errorChannel); Object requestMapper = TestUtils.getPropertyValue(gateway, "requestMapper"); - assertEquals("@foo", - TestUtils.getPropertyValue(requestMapper, "payloadExpression.expression")); + assertThat(TestUtils.getPropertyValue(requestMapper, "payloadExpression.expression")).isEqualTo("@foo"); Map globalHeaderExpressions = TestUtils.getPropertyValue(requestMapper, "globalHeaderExpressions", Map.class); - assertEquals(1, globalHeaderExpressions.size()); + assertThat(globalHeaderExpressions.size()).isEqualTo(1); Object barHeaderExpression = globalHeaderExpressions.get("bar"); - assertNotNull(barHeaderExpression); - assertThat(barHeaderExpression, instanceOf(LiteralExpression.class)); - assertEquals("baz", ((LiteralExpression) barHeaderExpression).getValue()); + assertThat(barHeaderExpression).isNotNull(); + assertThat(barHeaderExpression).isInstanceOf(LiteralExpression.class); + assertThat(((LiteralExpression) barHeaderExpression).getValue()).isEqualTo("baz"); } @Test @@ -509,7 +495,7 @@ public class GatewayInterfaceTests { Message message = messageArgumentCaptor.getValue(); - assertFalse(message.getHeaders().containsKey(IGNORE_HEADER)); + assertThat(message.getHeaders().containsKey(IGNORE_HEADER)).isFalse(); ((SubscribableChannel) this.errorChannel).unsubscribe(messageHandler); } @@ -524,14 +510,14 @@ public class GatewayInterfaceTests { @Override protected Object handleRequestMessage(Message requestMessage) { - assertEquals("foo", requestMessage.getPayload()); + assertThat(requestMessage.getPayload()).isEqualTo("foo"); return "FOO"; } }); NoArgumentsGateway noArgumentsGateway = ac.getBean(NoArgumentsGateway.class); - assertEquals("FOO", noArgumentsGateway.pullData()); + assertThat(noArgumentsGateway.pullData()).isEqualTo("FOO"); ac.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java index fcf2a9a7f8..00c96e79c2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,9 @@ package org.springframework.integration.gateway; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + import org.junit.Test; import org.junit.runner.RunWith; @@ -69,9 +71,9 @@ public class GatewayInvokingMessageHandlerTests { @Test public void validateGatewayInTheChainViaChannel() { output.subscribe(message -> { - Assert.assertEquals("echo:echo:echo:hello", message.getPayload()); - Assert.assertEquals("foo", message.getHeaders().get("foo")); - Assert.assertEquals("oleg", message.getHeaders().get("name")); + assertThat(message.getPayload()).isEqualTo("echo:echo:echo:hello"); + assertThat(message.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(message.getHeaders().get("name")).isEqualTo("oleg"); }); channel.send(new GenericMessage("hello")); } @@ -79,85 +81,74 @@ public class GatewayInvokingMessageHandlerTests { @Test public void validateGatewayInTheChainViaAnotherGateway() { output.subscribe(message -> { - Assert.assertEquals("echo:echo:echo:hello", message.getPayload()); - Assert.assertEquals("foo", message.getHeaders().get("foo")); - Assert.assertEquals("oleg", message.getHeaders().get("name")); + assertThat(message.getPayload()).isEqualTo("echo:echo:echo:hello"); + assertThat(message.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(message.getHeaders().get("name")).isEqualTo("oleg"); }); String result = gateway.process("hello"); - Assert.assertEquals("echo:echo:echo:hello", result); + assertThat(result).isEqualTo("echo:echo:echo:hello"); } @Test public void validateGatewayWithErrorMessageReturned() { - try { - String result = gatewayWithErrorChannelAndTransformer.process("echoWithRuntimeExceptionChannel"); - Assert.assertNotNull(result); - Assert.assertEquals("Error happened in message: echoWithRuntimeExceptionChannel", result); - } - catch (Exception e) { - Assert.fail(); - } + String result = gatewayWithErrorChannelAndTransformer.process("echoWithRuntimeExceptionChannel"); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("Error happened in message: echoWithRuntimeExceptionChannel"); try { gatewayWithError.process("echoWithRuntimeExceptionChannel"); - Assert.fail(); + fail("SampleRuntimeException expected"); } catch (SampleRuntimeException e) { - Assert.assertEquals("echoWithRuntimeExceptionChannel", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("echoWithRuntimeExceptionChannel"); } try { gatewayWithError.process("echoWithMessagingExceptionChannel"); - Assert.fail(); + fail("MessageHandlingException expected"); } catch (MessageHandlingException e) { - Assert.assertEquals("echoWithMessagingExceptionChannel", e.getFailedMessage().getPayload()); + assertThat(e.getFailedMessage().getPayload()).isEqualTo("echoWithMessagingExceptionChannel"); } - try { - String result = gatewayWithErrorChannelAndTransformer.process("echoWithMessagingExceptionChannel"); - Assert.assertNotNull(result); - Assert.assertEquals("Error happened in message: echoWithMessagingExceptionChannel", result); - } - catch (Exception e) { - Assert.fail(); - } + result = gatewayWithErrorChannelAndTransformer.process("echoWithMessagingExceptionChannel"); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("Error happened in message: echoWithMessagingExceptionChannel"); } @Test public void validateGatewayWithErrorAsync() { try { gatewayWithErrorAsync.process("echoWithErrorAsyncChannel"); - Assert.fail(); + fail("SampleRuntimeException expected"); } catch (Exception e) { - Assert.assertEquals(SampleRuntimeException.class, e.getClass()); + assertThat(e.getClass()).isEqualTo(SampleRuntimeException.class); } } @Test public void validateGatewayWithErrorFlowReturningMessage() { - try { - Object result = gatewayWithErrorChannelAndTransformer.process("echoWithErrorAsyncChannel"); - Assert.assertEquals("Error happened in message: echoWithErrorAsyncChannel", result); - } - catch (Exception e) { - Assert.fail(); - } + Object result = gatewayWithErrorChannelAndTransformer.process("echoWithErrorAsyncChannel"); + assertThat(result).isEqualTo("Error happened in message: echoWithErrorAsyncChannel"); } public static class SampleErrorTransformer { - public Message toMessage(Throwable object) throws Exception { + + public Message toMessage(Throwable object) { MessageHandlingException ex = (MessageHandlingException) object; - return MessageBuilder.withPayload("Error happened in message: " + ex.getFailedMessage().getPayload()).build(); + return MessageBuilder.withPayload("Error happened in message: " + ex.getFailedMessage().getPayload()) + .build(); } } public interface SimpleGateway { + String process(String str); + } @@ -172,28 +163,33 @@ public class GatewayInvokingMessageHandlerTests { } public String echoWithMessagingException(String value) { - throw new MessageHandlingException(new GenericMessage(value)); + throw new MessageHandlingException(new GenericMessage<>(value)); } public String echoWithErrorAsync(String value) { throw new SampleRuntimeException(value); } + } @SuppressWarnings("serial") public static class SampleCheckedException extends Exception { + public SampleCheckedException(String message) { super(message); } + } @SuppressWarnings("serial") public static class SampleRuntimeException extends RuntimeException { + public SampleRuntimeException(String message) { super(message); } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java index 1aa5953ba4..fb6b8245ab 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayMethodInboundMessageMapperToMessageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; @@ -49,7 +48,7 @@ public class GatewayMethodInboundMessageMapperToMessageTests { GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); mapper.setBeanFactory(mock(BeanFactory.class)); Message message = mapper.toMessage(new Object[] { "test" }); - assertEquals("test", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("test"); } @Test(expected = IllegalArgumentException.class) @@ -75,8 +74,8 @@ public class GatewayMethodInboundMessageMapperToMessageTests { GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); mapper.setBeanFactory(mock(BeanFactory.class)); Message message = mapper.toMessage(new Object[] { "test", "bar" }); - assertEquals("test", message.getPayload()); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("test"); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } @Test(expected = MessageMappingException.class) @@ -95,8 +94,8 @@ public class GatewayMethodInboundMessageMapperToMessageTests { GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); mapper.setBeanFactory(mock(BeanFactory.class)); Message message = mapper.toMessage(new Object[] { "test", "bar" }); - assertEquals("test", message.getPayload()); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("test"); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -106,8 +105,8 @@ public class GatewayMethodInboundMessageMapperToMessageTests { GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); mapper.setBeanFactory(mock(BeanFactory.class)); Message message = mapper.toMessage(new Object[] { "test", null }); - assertEquals("test", message.getPayload()); - assertNull(message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("test"); + assertThat(message.getHeaders().get("foo")).isNull(); } @Test @@ -120,9 +119,9 @@ public class GatewayMethodInboundMessageMapperToMessageTests { headers.put("abc", 123); headers.put("def", 456); Message message = mapper.toMessage(new Object[] { "test", headers }); - assertEquals("test", message.getPayload()); - assertEquals(123, message.getHeaders().get("abc")); - assertEquals(456, message.getHeaders().get("def")); + assertThat(message.getPayload()).isEqualTo("test"); + assertThat(message.getHeaders().get("abc")).isEqualTo(123); + assertThat(message.getHeaders().get("def")).isEqualTo(456); } @Test @@ -132,7 +131,7 @@ public class GatewayMethodInboundMessageMapperToMessageTests { GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); mapper.setBeanFactory(mock(BeanFactory.class)); Message message = mapper.toMessage(new Object[] { "test", null }); - assertEquals("test", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("test"); } @Test(expected = MessageMappingException.class) @@ -153,7 +152,7 @@ public class GatewayMethodInboundMessageMapperToMessageTests { mapper.setBeanFactory(mock(BeanFactory.class)); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] { inputMessage }); - assertEquals("test message", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("test message"); } @Test @@ -163,8 +162,8 @@ public class GatewayMethodInboundMessageMapperToMessageTests { mapper.setBeanFactory(mock(BeanFactory.class)); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] { inputMessage, "bar" }); - assertEquals("test message", message.getPayload()); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("test message"); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } @Test(expected = MessageMappingException.class) @@ -183,8 +182,8 @@ public class GatewayMethodInboundMessageMapperToMessageTests { mapper.setBeanFactory(mock(BeanFactory.class)); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] { inputMessage, "bar" }); - assertEquals("test message", message.getPayload()); - assertEquals("bar", message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("test message"); + assertThat(message.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -194,8 +193,8 @@ public class GatewayMethodInboundMessageMapperToMessageTests { mapper.setBeanFactory(mock(BeanFactory.class)); Message inputMessage = MessageBuilder.withPayload("test message").build(); Message message = mapper.toMessage(new Object[] { inputMessage, null }); - assertEquals("test message", message.getPayload()); - assertNull(message.getHeaders().get("foo")); + assertThat(message.getPayload()).isEqualTo("test message"); + assertThat(message.getHeaders().get("foo")).isNull(); } @Test(expected = MessageMappingException.class) @@ -224,9 +223,9 @@ public class GatewayMethodInboundMessageMapperToMessageTests { GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method, headers); mapper.setBeanFactory(mock(BeanFactory.class)); Message message = mapper.toMessage(new Object[] { "test" }); - assertEquals("test", message.getPayload()); - assertEquals("foo", message.getHeaders().get("foo")); - assertEquals(42, message.getHeaders().get("bar")); + assertThat(message.getPayload()).isEqualTo("test"); + assertThat(message.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(message.getHeaders().get("bar")).isEqualTo(42); } @Test @@ -239,7 +238,7 @@ public class GatewayMethodInboundMessageMapperToMessageTests { mapper.setBeanFactory(mock(BeanFactory.class)); mapper.setPayloadExpression("'hello'"); Message message = mapper.toMessage(new Object[] { map }); - assertEquals("hello", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("hello"); } @Test @@ -252,7 +251,7 @@ public class GatewayMethodInboundMessageMapperToMessageTests { mapper.setBeanFactory(mock(BeanFactory.class)); mapper.setPayloadExpression("#args[0]"); Message message = mapper.toMessage(new Object[] { map }); - assertEquals(map, message.getPayload()); + assertThat(message.getPayload()).isEqualTo(map); } @Test @@ -264,7 +263,7 @@ public class GatewayMethodInboundMessageMapperToMessageTests { GatewayMethodInboundMessageMapper mapper = new GatewayMethodInboundMessageMapper(method); mapper.setBeanFactory(mock(BeanFactory.class)); Message message = mapper.toMessage(new Object[] { map }); - assertEquals(map, message.getPayload()); + assertThat(message.getPayload()).isEqualTo(map); } @Test @@ -280,9 +279,9 @@ public class GatewayMethodInboundMessageMapperToMessageTests { mapper.setBeanFactory(mock(BeanFactory.class)); mapper.setPayloadExpression("#args[0]"); Message message = mapper.toMessage(new Object[] { mapA, mapB }); - assertEquals(mapA, message.getPayload()); - assertEquals(mapB.get("1"), message.getHeaders().get("1")); - assertEquals(mapB.get("2"), message.getHeaders().get("2")); + assertThat(message.getPayload()).isEqualTo(mapA); + assertThat(message.getHeaders().get("1")).isEqualTo(mapB.get("1")); + assertThat(message.getHeaders().get("2")).isEqualTo(mapB.get("2")); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java index 1158a64f27..bcefd85837 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java @@ -16,14 +16,8 @@ package org.springframework.integration.gateway; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -84,7 +78,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); String result = service.requestReply("foo"); - assertEquals("foobar", result); + assertThat(result).isEqualTo("foobar"); } @Test @@ -115,7 +109,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); byte[] result = service.requestReplyInBytes("foo"); - assertEquals(6, result.length); + assertThat(result.length).isEqualTo(6); Mockito.verify(stringToByteConverter, Mockito.times(1)).convert(Mockito.any(String.class)); } @@ -131,8 +125,8 @@ public class GatewayProxyFactoryBeanTests { TestService service = (TestService) proxyFactory.getObject(); service.oneWay("test"); Message message = requestChannel.receive(1000); - assertNotNull(message); - assertEquals("test", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("test"); } @Test @@ -148,8 +142,8 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); String result = service.solicitResponse(); - assertNotNull(result); - assertEquals("foo", result); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("foo"); } @Test @@ -164,8 +158,8 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); Message message = service.getMessage(); - assertNotNull(message); - assertEquals("foo", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -184,7 +178,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); Integer result = service.requestReplyWithIntegers(123); - assertEquals(new Integer(123456), result); + assertThat(result).isEqualTo(new Integer(123456)); } @Test @@ -193,7 +187,7 @@ public class GatewayProxyFactoryBeanTests { "gatewayWithRendezvousChannel.xml", GatewayProxyFactoryBeanTests.class); TestService service = (TestService) context.getBean("proxy"); String result = service.requestReply("foo"); - assertEquals("foo!!!", result); + assertThat(result).isEqualTo("foo!!!"); context.close(); } @@ -203,10 +197,10 @@ public class GatewayProxyFactoryBeanTests { "gatewayWithResponseCorrelator.xml", GatewayProxyFactoryBeanTests.class); TestService service = (TestService) context.getBean("proxy"); String result = service.requestReply("foo"); - assertEquals("foo!!!", result); + assertThat(result).isEqualTo("foo!!!"); TestChannelInterceptor interceptor = (TestChannelInterceptor) context.getBean("interceptor"); - assertEquals(1, interceptor.getSentCount()); - assertEquals(1, interceptor.getReceivedCount()); + assertThat(interceptor.getSentCount()).isEqualTo(1); + assertThat(interceptor.getReceivedCount()).isEqualTo(1); context.close(); } @@ -233,13 +227,13 @@ public class GatewayProxyFactoryBeanTests { latch.countDown(); }); } - assertTrue(latch.await(30, TimeUnit.SECONDS)); + assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); for (int i = 0; i < numRequests; i++) { - assertEquals("test-" + i + "!!!", results[i]); + assertThat(results[i]).isEqualTo("test-" + i + "!!!"); } TestChannelInterceptor interceptor = (TestChannelInterceptor) context.getBean("interceptor"); - assertEquals(numRequests, interceptor.getSentCount()); - assertEquals(numRequests, interceptor.getReceivedCount()); + assertThat(interceptor.getSentCount()).isEqualTo(numRequests); + assertThat(interceptor.getReceivedCount()).isEqualTo(numRequests); context.close(); executor.shutdownNow(); } @@ -256,7 +250,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); String result = service.requestReplyWithMessageParameter(new GenericMessage<>("foo")); - assertEquals("foobar", result); + assertThat(result).isEqualTo("foobar"); } @Test @@ -271,7 +265,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); String result = service.requestReplyWithPayloadAnnotation(); - assertEquals("requestReplyWithPayloadAnnotation0bar", result); + assertThat(result).isEqualTo("requestReplyWithPayloadAnnotation0bar"); } @Test @@ -290,7 +284,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); Message result = service.requestReplyWithMessageReturnValue("foo"); - assertEquals("foobar", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foobar"); } @Test @@ -306,7 +300,7 @@ public class GatewayProxyFactoryBeanTests { catch (IllegalArgumentException e) { // expected } - assertEquals(1, count); + assertThat(count).isEqualTo(1); } @Test @@ -319,7 +313,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); Object proxy = proxyFactory.getObject(); String expected = "gateway proxy for"; - assertEquals(expected, proxy.toString().substring(0, expected.length())); + assertThat(proxy.toString().substring(0, expected.length())).isEqualTo(expected); } @Test(expected = TestException.class) @@ -368,10 +362,10 @@ public class GatewayProxyFactoryBeanTests { gpfb.afterPropertiesSet(); ((TestEchoService) gpfb.getObject()).echo("foo"); Message message = drc.receive(0); - assertNotNull(message); + assertThat(message).isNotNull(); String bar = (String) message.getHeaders().get("foo"); - assertNotNull(bar); - assertThat(bar, equalTo("bar")); + assertThat(bar).isNotNull(); + assertThat(bar).isEqualTo("bar"); } @Test @@ -388,9 +382,9 @@ public class GatewayProxyFactoryBeanTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), - containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()) + .contains("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers"); } } @@ -405,9 +399,9 @@ public class GatewayProxyFactoryBeanTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), - containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()) + .contains("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers"); } } @@ -422,9 +416,9 @@ public class GatewayProxyFactoryBeanTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), - containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()) + .contains("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers"); } } @@ -477,7 +471,7 @@ public class GatewayProxyFactoryBeanTests { gpfb.setBeanFactory(mock(BeanFactory.class)); gpfb.afterPropertiesSet(); Map gateways = gpfb.getGateways(); - assertThat(gateways.size(), equalTo(2)); + assertThat(gateways.size()).isEqualTo(2); } public static void throwTestException() throws TestException { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java index 3bac5fc2c8..67a71dfd6c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyMessageMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; @@ -73,10 +71,10 @@ public class GatewayProxyMessageMappingTests { m.put("k2", "v2"); gateway.payloadAndHeaderMapWithoutAnnotations("foo", m); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("foo", result.getPayload()); - assertEquals("v1", result.getHeaders().get("k1")); - assertEquals("v2", result.getHeaders().get("k2")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("foo"); + assertThat(result.getHeaders().get("k1")).isEqualTo("v1"); + assertThat(result.getHeaders().get("k2")).isEqualTo("v2"); } @Test @@ -86,20 +84,20 @@ public class GatewayProxyMessageMappingTests { m.put("k2", "v2"); gateway.payloadAndHeaderMapWithAnnotations("foo", m); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("foo", result.getPayload()); - assertEquals("v1", result.getHeaders().get("k1")); - assertEquals("v2", result.getHeaders().get("k2")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("foo"); + assertThat(result.getHeaders().get("k1")).isEqualTo("v1"); + assertThat(result.getHeaders().get("k2")).isEqualTo("v2"); } @Test public void headerValuesAndPayloadWithAnnotations() throws Exception { gateway.headerValuesAndPayloadWithAnnotations("headerValue1", "payloadValue", "headerValue2"); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("payloadValue", result.getPayload()); - assertEquals("headerValue1", result.getHeaders().get("k1")); - assertEquals("headerValue2", result.getHeaders().get("k2")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("payloadValue"); + assertThat(result.getHeaders().get("k1")).isEqualTo("headerValue1"); + assertThat(result.getHeaders().get("k2")).isEqualTo("headerValue2"); } @Test @@ -109,10 +107,10 @@ public class GatewayProxyMessageMappingTests { map.put("k2", "v2"); gateway.mapOnly(map); Message result = channel.receive(0); - assertNotNull(result); - assertEquals(map, result.getPayload()); - assertNull(result.getHeaders().get("k1")); - assertNull(result.getHeaders().get("k2")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(map); + assertThat(result.getHeaders().get("k1")).isNull(); + assertThat(result.getHeaders().get("k2")).isNull(); } @Test @@ -123,18 +121,18 @@ public class GatewayProxyMessageMappingTests { map2.put("k2", "v2"); gateway.twoMapsAndOneAnnotatedWithPayload(map1, map2); Message result = channel.receive(0); - assertNotNull(result); - assertEquals(map1, result.getPayload()); - assertEquals("v2", result.getHeaders().get("k2")); - assertNull(result.getHeaders().get("k1")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(map1); + assertThat(result.getHeaders().get("k2")).isEqualTo("v2"); + assertThat(result.getHeaders().get("k1")).isNull(); } @Test public void payloadAnnotationAtMethodLevel() throws Exception { gateway.payloadAnnotationAtMethodLevel("foo", "bar"); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("foobar!", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("foobar!"); } @Test @@ -151,8 +149,8 @@ public class GatewayProxyMessageMappingTests { TestGateway gateway = context.getBean("testGateway", TestGateway.class); gateway.payloadAnnotationAtMethodLevelUsingBeanResolver("foo"); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("FOO!!!", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("FOO!!!"); context.close(); } @@ -160,8 +158,8 @@ public class GatewayProxyMessageMappingTests { public void payloadAnnotationWithExpression() throws Exception { gateway.payloadAnnotationWithExpression("foo"); Message result = channel.receive(0); - assertNotNull(result); - assertEquals("FOO", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("FOO"); } @Test @@ -179,12 +177,12 @@ public class GatewayProxyMessageMappingTests { gateway.payloadAnnotationWithExpressionUsingBeanResolver("foo"); gateway.payloadAnnotationWithExpressionUsingBeanResolver("bar"); Message fooResult = channel.receive(0); - assertNotNull(fooResult); - assertEquals(324, fooResult.getPayload()); + assertThat(fooResult).isNotNull(); + assertThat(fooResult.getPayload()).isEqualTo(324); Message barResult = channel.receive(0); - assertNotNull(barResult); - assertEquals(309, barResult.getPayload()); - assertNull(channel.receive(0)); + assertThat(barResult).isNotNull(); + assertThat(barResult.getPayload()).isEqualTo(309); + assertThat(channel.receive(0)).isNull(); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayRequiresReplyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayRequiresReplyTests.java index 3140eaf75a..07d4d6ca4e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayRequiresReplyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayRequiresReplyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -47,7 +46,7 @@ public class GatewayRequiresReplyTests { public void replyReceived() { TestService gateway = this.applicationContext.getBean("gateway", TestService.class); String result = gateway.test("foo"); - assertEquals("bar", result); + assertThat(result).isEqualTo("bar"); } @Test(expected = ReplyRequiredException.class) @@ -60,7 +59,7 @@ public class GatewayRequiresReplyTests { public void timedOutGateway() { TestService gateway = this.applicationContext.getBean("timeoutGateway", TestService.class); String result = gateway.test("hello"); - assertNull(result); + assertThat(result).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithHeaderAnnotations.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithHeaderAnnotations.java index 6ad7f10017..8ccc85bf9b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithHeaderAnnotations.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithHeaderAnnotations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -45,7 +45,7 @@ public class GatewayWithHeaderAnnotations { public void priorityAsArgument() { TestService gateway = (TestService) applicationContext.getBean("gateway"); String result = gateway.test("foo", 99, "bar", "qux"); - assertEquals("foo99barqux", result); + assertThat(result).isEqualTo("foo99barqux"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithPayloadExpressionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithPayloadExpressionTests.java index 1b114da8d7..64d3c6d0df 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithPayloadExpressionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayWithPayloadExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,28 +53,28 @@ public class GatewayWithPayloadExpressionTests { public void simpleExpression() { gateway.send1("foo"); Message result = input.receive(0); - assertEquals("foobar", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foobar"); } @Test public void beanResolvingExpression() { gateway.send2("foo"); Message result = input.receive(0); - assertEquals(324, result.getPayload()); + assertThat(result.getPayload()).isEqualTo(324); } @Test public void payloadAnnotationExpression() { annotatedGateway.send("foo", "bar"); Message result = input.receive(0); - assertEquals("foobar", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foobar"); } @Test public void noArgMethodWithPayloadExpression() { gateway.send3(); Message result = input.receive(0); - assertEquals("send3", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("send3"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayXmlAndAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayXmlAndAnnotationTests.java index bd03fbeffa..d7212a787e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayXmlAndAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayXmlAndAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.Map; @@ -46,35 +46,35 @@ public class GatewayXmlAndAnnotationTests { @Test public void test() { - assertEquals(123L, TestUtils.getPropertyValue(gatewayProxyFactoryBean, "defaultReplyTimeout", Expression.class) - .getValue()); + assertThat(TestUtils.getPropertyValue(gatewayProxyFactoryBean, "defaultReplyTimeout", Expression.class) + .getValue()).isEqualTo(123L); @SuppressWarnings("unchecked") Map gatewayMap = TestUtils.getPropertyValue(gatewayProxyFactoryBean, "gatewayMap", Map.class); int assertions = 0; for (Entry entry : gatewayMap.entrySet()) { if (entry.getKey().getName().equals("annotationShouldntOverrideDefault")) { - assertEquals(123L, TestUtils.getPropertyValue(entry.getValue(), - "replyTimeout")); + assertThat(TestUtils.getPropertyValue(entry.getValue(), + "replyTimeout")).isEqualTo(123L); assertions++; } else if (entry.getKey().getName().equals("annotationShouldOverrideDefault")) { - assertEquals(234L, TestUtils.getPropertyValue(entry.getValue(), - "replyTimeout")); + assertThat(TestUtils.getPropertyValue(entry.getValue(), + "replyTimeout")).isEqualTo(234L); assertions++; } else if (entry.getKey().getName().equals("annotationShouldOverrideDefaultToInfinity")) { - assertEquals(-1L, TestUtils.getPropertyValue(entry.getValue(), - "replyTimeout")); + assertThat(TestUtils.getPropertyValue(entry.getValue(), + "replyTimeout")).isEqualTo(-1L); assertions++; } else if (entry.getKey().getName().equals("explicitTimeoutShouldOverrideDefault")) { - assertEquals(456L, TestUtils.getPropertyValue(entry.getValue(), - "replyTimeout")); + assertThat(TestUtils.getPropertyValue(entry.getValue(), + "replyTimeout")).isEqualTo(456L); assertions++; } } - assertEquals(4, assertions); + assertThat(assertions).isEqualTo(4); } public interface AGateway { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/HeaderEnrichedGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/HeaderEnrichedGatewayTests.java index 8adfdaa2af..6e9e45a516 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/HeaderEnrichedGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/HeaderEnrichedGatewayTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -56,26 +55,26 @@ public class HeaderEnrichedGatewayTests { testPayload = "hello"; gatewayWithHeaderValues.sendString((String) testPayload); Message message1 = channel.receive(0); - assertEquals(testPayload, message1.getPayload()); - assertEquals("foo", message1.getHeaders().get("foo")); - assertEquals("bar", message1.getHeaders().get("bar")); - assertNull(message1.getHeaders().get("baz")); + assertThat(message1.getPayload()).isEqualTo(testPayload); + assertThat(message1.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(message1.getHeaders().get("bar")).isEqualTo("bar"); + assertThat(message1.getHeaders().get("baz")).isNull(); testPayload = 123; gatewayWithHeaderValues.sendInteger((Integer) testPayload); Message message2 = channel.receive(0); - assertEquals(testPayload, message2.getPayload()); - assertEquals("foo", message2.getHeaders().get("foo")); - assertEquals("bar", message2.getHeaders().get("bar")); - assertNull(message2.getHeaders().get("baz")); + assertThat(message2.getPayload()).isEqualTo(testPayload); + assertThat(message2.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(message2.getHeaders().get("bar")).isEqualTo("bar"); + assertThat(message2.getHeaders().get("baz")).isNull(); testPayload = "withAnnotatedHeaders"; gatewayWithHeaderValues.sendStringWithParameterHeaders((String) testPayload, "headerA", "headerB"); Message message3 = channel.receive(0); - assertEquals("foo", message3.getHeaders().get("foo")); - assertEquals("bar", message3.getHeaders().get("bar")); - assertEquals("headerA", message3.getHeaders().get("headerA")); - assertEquals("headerB", message3.getHeaders().get("headerB")); + assertThat(message3.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(message3.getHeaders().get("bar")).isEqualTo("bar"); + assertThat(message3.getHeaders().get("headerA")).isEqualTo("headerA"); + assertThat(message3.getHeaders().get("headerB")).isEqualTo("headerB"); } @Test @@ -83,26 +82,26 @@ public class HeaderEnrichedGatewayTests { testPayload = "hello"; gatewayWithHeaderExpressions.sendString((String) testPayload); Message message1 = channel.receive(0); - assertEquals(testPayload, message1.getPayload()); - assertEquals(42, message1.getHeaders().get("foo")); - assertEquals("foobar", message1.getHeaders().get("bar")); - assertNull(message1.getHeaders().get("baz")); + assertThat(message1.getPayload()).isEqualTo(testPayload); + assertThat(message1.getHeaders().get("foo")).isEqualTo(42); + assertThat(message1.getHeaders().get("bar")).isEqualTo("foobar"); + assertThat(message1.getHeaders().get("baz")).isNull(); testPayload = 123; gatewayWithHeaderExpressions.sendInteger((Integer) testPayload); Message message2 = channel.receive(0); - assertEquals(testPayload, message2.getPayload()); - assertEquals(42, message2.getHeaders().get("foo")); - assertEquals("foobar", message2.getHeaders().get("bar")); - assertNull(message2.getHeaders().get("baz")); + assertThat(message2.getPayload()).isEqualTo(testPayload); + assertThat(message2.getHeaders().get("foo")).isEqualTo(42); + assertThat(message2.getHeaders().get("bar")).isEqualTo("foobar"); + assertThat(message2.getHeaders().get("baz")).isNull(); testPayload = "withAnnotatedHeaders"; gatewayWithHeaderExpressions.sendStringWithParameterHeaders((String) testPayload, "headerA", "headerB"); Message message3 = channel.receive(0); - assertEquals(42, message3.getHeaders().get("foo")); - assertEquals("foobar", message3.getHeaders().get("bar")); - assertEquals("headerA", message3.getHeaders().get("headerA")); - assertEquals("headerB", message3.getHeaders().get("headerB")); + assertThat(message3.getHeaders().get("foo")).isEqualTo(42); + assertThat(message3.getHeaders().get("bar")).isEqualTo("foobar"); + assertThat(message3.getHeaders().get("headerA")).isEqualTo("headerA"); + assertThat(message3.getHeaders().get("headerB")).isEqualTo("headerB"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/InnerGatewayWithChainTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/InnerGatewayWithChainTests.java index 04f5d68cee..4c37a89e7c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/InnerGatewayWithChainTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/InnerGatewayWithChainTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -68,19 +67,19 @@ public class InnerGatewayWithChainTests { @Test public void testExceptionHandledByMainGateway() { String reply = testGatewayWithErrorChannelA.echo(5); - assertEquals("ERROR from errorChannelA", reply); + assertThat(reply).isEqualTo("ERROR from errorChannelA"); } @Test public void testExceptionHandledByMainGatewayNoErrorChannelInChain() { String reply = testGatewayWithErrorChannelAA.echo(0); - assertEquals("ERROR from errorChannelA", reply); + assertThat(reply).isEqualTo("ERROR from errorChannelA"); } @Test public void testExceptionHandledByInnerGateway() { String reply = testGatewayWithErrorChannelA.echo(0); - assertEquals("ERROR from errorChannelB", reply); + assertThat(reply).isEqualTo("ERROR from errorChannelB"); } // if no error channels explicitly defined exception is rethrown @@ -94,7 +93,7 @@ public class InnerGatewayWithChainTests { CountDownLatch errorLatch = new CountDownLatch(1); errorChannel.subscribe(message -> errorLatch.countDown()); inboundAdapterDefaultErrorChannel.start(); - assertTrue(errorLatch.await(10, TimeUnit.SECONDS)); + assertThat(errorLatch.await(10, TimeUnit.SECONDS)).isTrue(); inboundAdapterDefaultErrorChannel.stop(); } @@ -103,7 +102,7 @@ public class InnerGatewayWithChainTests { CountDownLatch errorLatch = new CountDownLatch(1); assignedErrorChannel.subscribe(message -> errorLatch.countDown()); inboundAdapterAssignedErrorChannel.start(); - assertTrue(errorLatch.await(10, TimeUnit.SECONDS)); + assertThat(errorLatch.await(10, TimeUnit.SECONDS)).isTrue(); inboundAdapterAssignedErrorChannel.stop(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java index 7e5d0a0bd1..ce0ab6dde2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java @@ -16,10 +16,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.Collections; @@ -96,7 +93,7 @@ public class MessagingGatewayTests { Mockito.when(requestChannel.send(messageMock, 1000L)).thenReturn(true); this.messagingGateway.send(messageMock); Mockito.verify(requestChannel).send(messageMock, 1000L); - assertEquals(1, this.messagingGateway.getMessageCount()); + assertThat(this.messagingGateway.getMessageCount()).isEqualTo(1); } @Test(expected = MessageDeliveryException.class) @@ -109,7 +106,7 @@ public class MessagingGatewayTests { @Test public void sendObject() { Mockito.doAnswer(invocation -> { - assertEquals("test", ((Message) invocation.getArguments()[0]).getPayload()); + assertThat(((Message) invocation.getArguments()[0]).getPayload()).isEqualTo("test"); return true; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.eq(1000L)); @@ -120,7 +117,7 @@ public class MessagingGatewayTests { @Test(expected = MessageDeliveryException.class) public void sendObject_failure() { Mockito.doAnswer(invocation -> { - assertEquals("test", ((Message) invocation.getArguments()[0]).getPayload()); + assertThat(((Message) invocation.getArguments()[0]).getPayload()).isEqualTo("test"); return false; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.eq(1000L)); @@ -138,14 +135,14 @@ public class MessagingGatewayTests { public void receiveMessage() { Mockito.when(replyChannel.receive(1000L)).thenReturn(messageMock); Mockito.when(messageMock.getPayload()).thenReturn("test"); - assertEquals("test", this.messagingGateway.receive()); + assertThat(this.messagingGateway.receive()).isEqualTo("test"); Mockito.verify(replyChannel).receive(1000L); } @Test public void receiveMessage_null() { Mockito.when(replyChannel.receive(1000L)).thenReturn(null); - assertNull(this.messagingGateway.receive()); + assertThat(this.messagingGateway.receive()).isNull(); Mockito.verify(replyChannel).receive(1000L); } @@ -165,7 +162,7 @@ public class MessagingGatewayTests { // TODO: if timeout is 0, this will fail occasionally this.messagingGateway.setReplyTimeout(100); Object test = this.messagingGateway.sendAndReceive("test"); - assertEquals("test", test); + assertThat(test).isEqualTo("test"); } @Test @@ -186,7 +183,7 @@ public class MessagingGatewayTests { this.messagingGateway.setReplyTimeout(0); Object o = this.messagingGateway.sendAndReceive(messageMock); - assertEquals("foo", o); + assertThat(o).isEqualTo("foo"); } @Test(expected = IllegalArgumentException.class) @@ -207,7 +204,7 @@ public class MessagingGatewayTests { this.messagingGateway.setReplyTimeout(100L); Message receiveMessage = this.messagingGateway.sendAndReceiveMessage("test"); - assertSame(messageMock, receiveMessage); + assertThat(receiveMessage).isSameAs(messageMock); } @Test @@ -227,7 +224,7 @@ public class MessagingGatewayTests { }).when(requestChannel).send(Mockito.any(Message.class), Mockito.anyLong()); Message receiveMessage = this.messagingGateway.sendAndReceiveMessage(messageMock); - assertSame(messageMock, receiveMessage); + assertThat(receiveMessage).isSameAs(messageMock); } @Test(expected = IllegalArgumentException.class) @@ -288,7 +285,7 @@ public class MessagingGatewayTests { this.messagingGateway.send("hello"); - assertTrue(myOneWayErrorService.errorReceived.await(10, TimeUnit.SECONDS)); + assertThat(myOneWayErrorService.errorReceived.await(10, TimeUnit.SECONDS)).isTrue(); } public static class MyErrorService { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MultiMethodGatewayConfigTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MultiMethodGatewayConfigTests.java index ad3cbd7c20..365c5b4e59 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MultiMethodGatewayConfigTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MultiMethodGatewayConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.gateway; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.junit.runner.RunWith; @@ -44,12 +45,9 @@ public class MultiMethodGatewayConfigTests { public void validateGatewayMethods() { TestGateway gateway = this.applicationContext.getBean("myGateway", TestGateway.class); String parentClassName = "org.springframework.integration.gateway.MultiMethodGatewayConfigTests"; - Assert.assertEquals(gateway.echo("oleg"), - parentClassName + "$TestBeanA:oleg"); - Assert.assertEquals(gateway.echoUpperCase("oleg"), - parentClassName + "$TestBeanB:oleg"); - Assert.assertEquals(gateway.echoViaDefault("oleg"), - parentClassName + "$TestBeanC:oleg"); + assertThat(parentClassName + "$TestBeanA:oleg").isEqualTo(gateway.echo("oleg")); + assertThat(parentClassName + "$TestBeanB:oleg").isEqualTo(gateway.echoUpperCase("oleg")); + assertThat(parentClassName + "$TestBeanC:oleg").isEqualTo(gateway.echoViaDefault("oleg")); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/NestedGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/NestedGatewayTests.java index 3876fc2291..c253f03976 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/NestedGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/NestedGatewayTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.gateway; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; @@ -59,7 +59,7 @@ public class NestedGatewayTests { outerGateway.setBeanFactory(mock(BeanFactory.class)); outerGateway.afterPropertiesSet(); Message reply = outerGateway.sendAndReceiveMessage("test"); - assertEquals("pre-test-reply-post", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("pre-test-reply-post"); } @Test @@ -79,8 +79,8 @@ public class NestedGatewayTests { Message message = MessageBuilder.withPayload("test") .setReplyChannel(replyChannel).build(); Message reply = gateway.sendAndReceiveMessage(message); - assertEquals("test-reply", reply.getPayload()); - assertEquals(replyChannel, reply.getHeaders().getReplyChannel()); + assertThat(reply.getPayload()).isEqualTo("test-reply"); + assertThat(reply.getHeaders().getReplyChannel()).isEqualTo(replyChannel); } @Test @@ -100,8 +100,8 @@ public class NestedGatewayTests { Message message = MessageBuilder.withPayload("test") .setErrorChannel(errorChannel).build(); Message reply = gateway.sendAndReceiveMessage(message); - assertEquals("test-reply", reply.getPayload()); - assertEquals(errorChannel, reply.getHeaders().getErrorChannel()); + assertThat(reply.getPayload()).isEqualTo("test-reply"); + assertThat(reply.getHeaders().getErrorChannel()).isEqualTo(errorChannel); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandlerTests.java index a268808d00..c71c511da7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,14 +16,8 @@ package org.springframework.integration.handler; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.hamcrest.Matchers.emptyCollectionOf; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; @@ -77,7 +71,7 @@ public class AbstractReplyProducingMessageHandlerTests { fail("Expected a MessagingException"); } catch (MessagingException e) { - assertThat(e.getMessage(), containsString("'testChannel'")); + assertThat(e.getMessage()).contains("'testChannel'"); } } @@ -92,10 +86,10 @@ public class AbstractReplyProducingMessageHandlerTests { } }; - assertThat(handler.getNotPropagatedHeaders(), emptyCollectionOf(String.class)); + assertThat(handler.getNotPropagatedHeaders()).isEmpty(); handler.setNotPropagatedHeaders("f*", "*r"); handler.setOutputChannel(this.channel); - assertThat(handler.getNotPropagatedHeaders(), containsInAnyOrder("f*", "*r")); + assertThat(handler.getNotPropagatedHeaders()).contains("f*", "*r"); ArgumentCaptor> captor = ArgumentCaptor.forClass(Message.class); willReturn(true).given(this.channel).send(captor.capture()); handler.handleMessage(MessageBuilder.withPayload("hello") @@ -104,10 +98,10 @@ public class AbstractReplyProducingMessageHandlerTests { .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")); + assertThat(out).isNotNull(); + assertThat(out.getHeaders().get("foo")).isNull(); + assertThat(out.getHeaders().get("bar")).isEqualTo("RAB"); + assertThat(out.getHeaders().get("baz")).isEqualTo("BAZ"); } @Test @@ -122,7 +116,7 @@ public class AbstractReplyProducingMessageHandlerTests { }; handler.addNotPropagatedHeaders("boom"); - assertThat(handler.getNotPropagatedHeaders(), containsInAnyOrder("boom")); + assertThat(handler.getNotPropagatedHeaders()).contains("boom"); handler.setOutputChannel(this.channel); ArgumentCaptor> captor = ArgumentCaptor.forClass(Message.class); willReturn(true).given(this.channel).send(captor.capture()); @@ -132,10 +126,10 @@ public class AbstractReplyProducingMessageHandlerTests { .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")); + assertThat(out).isNotNull(); + assertThat(out.getHeaders().get("boom")).isNull(); + assertThat(out.getHeaders().get("bar")).isEqualTo("RAB"); + assertThat(out.getHeaders().get("baz")).isEqualTo("BAZ"); } @Test @@ -149,11 +143,11 @@ public class AbstractReplyProducingMessageHandlerTests { } }; - assertThat(handler.getNotPropagatedHeaders(), emptyCollectionOf(String.class)); + assertThat(handler.getNotPropagatedHeaders()).isEmpty(); handler.setNotPropagatedHeaders("foo"); handler.addNotPropagatedHeaders("b*r"); handler.setOutputChannel(this.channel); - assertThat(handler.getNotPropagatedHeaders(), containsInAnyOrder("foo", "b*r")); + assertThat(handler.getNotPropagatedHeaders()).contains("foo", "b*r"); ArgumentCaptor> captor = ArgumentCaptor.forClass(Message.class); willReturn(true).given(this.channel).send(captor.capture()); handler.handleMessage( @@ -163,10 +157,10 @@ public class AbstractReplyProducingMessageHandlerTests { .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")); + assertThat(out).isNotNull(); + assertThat(out.getHeaders().get("foo")).isNull(); + assertThat(out.getHeaders().get("bar")).isEqualTo("RAB"); + assertThat(out.getHeaders().get("baz")).isEqualTo("BAZ"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java index 831ee1d1cf..beacf21124 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,15 +16,7 @@ package org.springframework.integration.handler; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -134,12 +126,12 @@ public class AsyncHandlerTests { public void testGoodResult() { this.whichTest = 0; this.handler.handleMessage(new GenericMessage<>("foo")); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); this.latch.countDown(); Message received = this.output.receive(10000); - assertNotNull(received); - assertEquals("reply", received.getPayload()); - assertNull(this.failedCallbackException); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo("reply"); + assertThat(this.failedCallbackException).isNull(); } @Test @@ -151,12 +143,12 @@ public class AsyncHandlerTests { .setReplyChannel(replyChannel) .build(); this.handler.handleMessage(message); - assertNull(replyChannel.receive(0)); + assertThat(replyChannel.receive(0)).isNull(); this.latch.countDown(); Message received = replyChannel.receive(10000); - assertNotNull(received); - assertEquals("reply", received.getPayload()); - assertNull(this.failedCallbackException); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo("reply"); + assertThat(this.failedCallbackException).isNull(); } @Test @@ -166,16 +158,16 @@ public class AsyncHandlerTests { QueueChannel errorChannel = new QueueChannel(); Message message = MessageBuilder.withPayload("foo").setErrorChannel(errorChannel).build(); this.handler.handleMessage(message); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); this.latch.countDown(); Message errorMessage = errorChannel.receive(10000); - assertNotNull(errorMessage); - assertThat(errorMessage.getPayload(), instanceOf(DestinationResolutionException.class)); - assertEquals("no output-channel or replyChannel header available", - ((Throwable) errorMessage.getPayload()).getMessage()); - assertNull(((MessagingException) errorMessage.getPayload()).getFailedMessage()); - assertNotNull(this.failedCallbackException); - assertThat(this.failedCallbackException.getMessage(), containsString("or replyChannel header")); + assertThat(errorMessage).isNotNull(); + assertThat(errorMessage.getPayload()).isInstanceOf(DestinationResolutionException.class); + assertThat(((Throwable) errorMessage.getPayload()).getMessage()) + .isEqualTo("no output-channel or replyChannel header available"); + assertThat(((MessagingException) errorMessage.getPayload()).getFailedMessage()).isNull(); + assertThat(this.failedCallbackException).isNotNull(); + assertThat(this.failedCallbackException.getMessage()).contains("or replyChannel header"); } @Test @@ -185,15 +177,15 @@ public class AsyncHandlerTests { .setErrorChannel(errorChannel) .build(); this.handler.handleMessage(message); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); this.whichTest = 1; this.latch.countDown(); Message received = errorChannel.receive(10000); - assertNotNull(received); - assertThat(received.getPayload(), instanceOf(MessageHandlingException.class)); - assertEquals("foo", ((Throwable) received.getPayload()).getCause().getMessage()); - assertSame(message, ((MessagingException) received.getPayload()).getFailedMessage()); - assertNull(this.failedCallbackException); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isInstanceOf(MessageHandlingException.class); + assertThat(((Throwable) received.getPayload()).getCause().getMessage()).isEqualTo("foo"); + assertThat(((MessagingException) received.getPayload()).getFailedMessage()).isSameAs(message); + assertThat(this.failedCallbackException).isNull(); } @Test @@ -203,14 +195,14 @@ public class AsyncHandlerTests { .setErrorChannel(errorChannel) .build(); this.handler.handleMessage(message); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); this.whichTest = 2; this.latch.countDown(); Message received = errorChannel.receive(10000); - assertNotNull(received); - assertThat(received.getPayload(), instanceOf(MessagingException.class)); - assertSame(message, ((MessagingException) received.getPayload()).getFailedMessage()); - assertNull(this.failedCallbackException); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isInstanceOf(MessagingException.class); + assertThat(((MessagingException) received.getPayload()).getFailedMessage()).isSameAs(message); + assertThat(this.failedCallbackException).isNull(); } @Test @@ -218,12 +210,12 @@ public class AsyncHandlerTests { Message message = MessageBuilder.withPayload("foo") .build(); this.handler.handleMessage(message); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); this.whichTest = 2; this.latch.countDown(); - assertTrue(this.exceptionLatch.await(10, TimeUnit.SECONDS)); - assertNotNull(this.failedCallbackException); - assertThat(this.failedCallbackMessage, containsString("no 'errorChannel' header")); + assertThat(this.exceptionLatch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(this.failedCallbackException).isNotNull(); + assertThat(this.failedCallbackMessage).contains("no 'errorChannel' header"); } @Test @@ -242,7 +234,7 @@ public class AsyncHandlerTests { consumer.start(); this.latch.countDown(); String result = foo.exchange("foo"); - assertEquals("reply", result); + assertThat(result).isEqualTo("reply"); } @Test @@ -264,8 +256,8 @@ public class AsyncHandlerTests { foo.exchange("foo"); } catch (MessagingException e) { - assertThat(e.getClass().getSimpleName(), equalTo("RuntimeException")); - assertThat(e.getMessage(), equalTo("foo")); + assertThat(e.getClass().getSimpleName()).isEqualTo("RuntimeException"); + assertThat(e.getMessage()).isEqualTo("foo"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java index f06d44a93a..941b6cb529 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,15 @@ package org.springframework.integration.handler; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; -import org.hamcrest.Factory; -import org.hamcrest.Matcher; import org.junit.Test; import org.springframework.integration.channel.QueueChannel; -import org.springframework.integration.message.MessageMatcher; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.predicate.MessagePredicate; import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.core.DestinationResolutionException; import org.springframework.messaging.support.GenericMessage; @@ -43,40 +38,31 @@ public class BridgeHandlerTests { private final BridgeHandler handler = new BridgeHandler(); - @Factory - public static Matcher> sameExceptImmutableHeaders(Message expected) { - return new MessageMatcher(expected); - } - @Test public void simpleBridge() { QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); - Message request = new GenericMessage("test"); + Message request = new GenericMessage<>("test"); handler.handleMessage(request); Message reply = outputChannel.receive(0); - assertNotNull(reply); - assertThat(reply, sameExceptImmutableHeaders(request)); + assertThat(reply).isNotNull(); + assertThat(reply).matches(new MessagePredicate(request)); } @Test public void missingOutputChannelVerifiedAtRuntime() { - Message request = new GenericMessage("test"); - try { - handler.handleMessage(request); - fail("Expected exception"); - } - catch (MessageHandlingException e) { - assertThat(e.getCause(), instanceOf(DestinationResolutionException.class)); - } + Message request = new GenericMessage<>("test"); + + assertThatThrownBy(() -> handler.handleMessage(request)) + .hasCauseInstanceOf(DestinationResolutionException.class); } @Test(timeout = 1000) - public void missingOutputChannelAllowedForReplyChannelMessages() throws Exception { + public void missingOutputChannelAllowedForReplyChannelMessages() { PollableChannel replyChannel = new QueueChannel(); Message request = MessageBuilder.withPayload("tst").setReplyChannel(replyChannel).build(); handler.handleMessage(request); - assertThat(replyChannel.receive(), sameExceptImmutableHeaders(request)); + assertThat(replyChannel.receive()).matches(new MessagePredicate(request)); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/CGLibProxyHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/CGLibProxyHandlerTests.java index afd7043ca7..ccc78a07fc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/CGLibProxyHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/CGLibProxyHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,10 +16,7 @@ package org.springframework.integration.handler; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,13 +50,13 @@ public class CGLibProxyHandlerTests { @Test public void testProxyBridge() { - assertTrue(AopUtils.isCglibProxy(this.bridge)); + assertThat(AopUtils.isCglibProxy(this.bridge)).isTrue(); this.bridge.handleMessage(new GenericMessage<>("foo")); Message received = this.out.receive(0); - assertNotNull(received); - assertNotNull(received.getHeaders().get(MessageHistory.HEADER_NAME)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(MessageHistory.HEADER_NAME)).isNotNull(); MessageHistory history = received.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class); - assertThat(history.size(), equalTo(2)); + assertThat(history.size()).isEqualTo(2); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/CollectionAndArrayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/CollectionAndArrayTests.java index 10eeec0274..2a1cf936f4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/CollectionAndArrayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/CollectionAndArrayTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.handler; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.HashSet; @@ -60,10 +54,10 @@ public class CollectionAndArrayTests { handler.handleMessage(message); Message reply1 = channel.receive(0); Message reply2 = channel.receive(0); - assertNotNull(reply1); - assertNull(reply2); - assertTrue(List.class.isAssignableFrom(reply1.getPayload().getClass())); - assertEquals(2, ((List) reply1.getPayload()).size()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNull(); + assertThat(List.class.isAssignableFrom(reply1.getPayload().getClass())).isTrue(); + assertThat(((List) reply1.getPayload()).size()).isEqualTo(2); } @Test @@ -80,10 +74,10 @@ public class CollectionAndArrayTests { handler.handleMessage(message); Message reply1 = channel.receive(0); Message reply2 = channel.receive(0); - assertNotNull(reply1); - assertNull(reply2); - assertThat(reply1.getPayload(), is(instanceOf(Set.class))); - assertEquals(2, ((Set) reply1.getPayload()).size()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNull(); + assertThat(reply1.getPayload()).isInstanceOf(Set.class); + assertThat(((Set) reply1.getPayload()).size()).isEqualTo(2); } @Test @@ -100,10 +94,10 @@ public class CollectionAndArrayTests { handler.handleMessage(message); Message reply1 = channel.receive(0); Message reply2 = channel.receive(0); - assertNotNull(reply1); - assertNull(reply2); - assertTrue(reply1.getPayload().getClass().isArray()); - assertEquals(2, ((String[]) reply1.getPayload()).length); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNull(); + assertThat(reply1.getPayload().getClass().isArray()).isTrue(); + assertThat(((String[]) reply1.getPayload()).length).isEqualTo(2); } @Test @@ -120,12 +114,12 @@ public class CollectionAndArrayTests { handler.handleMessage(message); Message reply1 = channel.receive(0); Message reply2 = channel.receive(0); - assertNotNull(reply1); - assertNotNull(reply2); - assertEquals(String.class, reply1.getPayload().getClass()); - assertEquals(String.class, reply2.getPayload().getClass()); - assertEquals("foo", reply1.getPayload()); - assertEquals("bar", reply2.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNotNull(); + assertThat(reply1.getPayload().getClass()).isEqualTo(String.class); + assertThat(reply2.getPayload().getClass()).isEqualTo(String.class); + assertThat(reply1.getPayload()).isEqualTo("foo"); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -142,10 +136,10 @@ public class CollectionAndArrayTests { handler.handleMessage(message); Message reply1 = channel.receive(0); Message reply2 = channel.receive(0); - assertNotNull(reply1); - assertNotNull(reply2); - assertEquals(String.class, reply1.getPayload().getClass()); - assertEquals(String.class, reply2.getPayload().getClass()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNotNull(); + assertThat(reply1.getPayload().getClass()).isEqualTo(String.class); + assertThat(reply2.getPayload().getClass()).isEqualTo(String.class); } @Test @@ -162,12 +156,12 @@ public class CollectionAndArrayTests { handler.handleMessage(message); Message reply1 = channel.receive(0); Message reply2 = channel.receive(0); - assertNotNull(reply1); - assertNotNull(reply2); - assertEquals(String.class, reply1.getPayload().getClass()); - assertEquals(String.class, reply2.getPayload().getClass()); - assertEquals("foo", reply1.getPayload()); - assertEquals("bar", reply2.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply2).isNotNull(); + assertThat(reply1.getPayload().getClass()).isEqualTo(String.class); + assertThat(reply2.getPayload().getClass()).isEqualTo(String.class); + assertThat(reply1.getPayload()).isEqualTo("foo"); + assertThat(reply2.getPayload()).isEqualTo("bar"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/CustomConverterMessageProcessingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/CustomConverterMessageProcessingTests.java index c39adb5315..6122d9e937 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/CustomConverterMessageProcessingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/CustomConverterMessageProcessingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.handler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -69,10 +68,10 @@ public class CustomConverterMessageProcessingTests { .setReplyChannel(replyChannel).build(); this.serviceActivatorChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean2.class, result.getPayload().getClass()); - assertEquals("SERVICE-TEST", ((TestBean2) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean2.class); + assertThat(((TestBean2) result.getPayload()).text).isEqualTo("SERVICE-TEST"); } @Test @@ -82,10 +81,10 @@ public class CustomConverterMessageProcessingTests { .setReplyChannel(replyChannel).build(); this.transformerChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean2.class, result.getPayload().getClass()); - assertEquals("TRANSFORMER-TEST", ((TestBean2) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean2.class); + assertThat(((TestBean2) result.getPayload()).text).isEqualTo("TRANSFORMER-TEST"); } @Test @@ -95,10 +94,10 @@ public class CustomConverterMessageProcessingTests { .setReplyChannel(replyChannel).build(); this.splitterChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean2.class, result.getPayload().getClass()); - assertEquals("SPLITTER-TEST", ((TestBean2) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean2.class); + assertThat(((TestBean2) result.getPayload()).text).isEqualTo("SPLITTER-TEST"); } @Test @@ -108,10 +107,10 @@ public class CustomConverterMessageProcessingTests { .setReplyChannel(replyChannel).build(); this.filterChannel.send(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean1.class, result.getPayload().getClass()); - assertEquals("filter-test", ((TestBean1) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean1.class); + assertThat(((TestBean1) result.getPayload()).text).isEqualTo("filter-test"); } @Test @@ -119,10 +118,10 @@ public class CustomConverterMessageProcessingTests { Message message = MessageBuilder.withPayload(new TestBean1("router-test")).build(); this.routerChannel.send(message); Message result = this.routerTargetChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals(TestBean1.class, result.getPayload().getClass()); - assertEquals("router-test", ((TestBean1) result.getPayload()).text); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload().getClass()).isEqualTo(TestBean1.class); + assertThat(((TestBean1) result.getPayload()).text).isEqualTo("router-test"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java index c2cf9c3668..be31c7376f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java @@ -16,14 +16,7 @@ package org.springframework.integration.handler; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.Calendar; @@ -126,8 +119,8 @@ public class DelayHandlerTests { startDelayerHandler(); Message message = MessageBuilder.withPayload("test").build(); input.send(message); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isSameAs(Thread.currentThread()); } @Test @@ -137,8 +130,8 @@ public class DelayHandlerTests { Message message = MessageBuilder.withPayload("test").build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -174,10 +167,10 @@ public class DelayHandlerTests { throw new MessagingException(m); }); input.send(message); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); Thread.sleep(50); - assertThat(count.get(), equalTo(4)); - assertThat(TestUtils.getPropertyValue(this.delayHandler, "deliveries", Map.class).size(), equalTo(0)); + assertThat(count.get()).isEqualTo(4); + assertThat(TestUtils.getPropertyValue(this.delayHandler, "deliveries", Map.class).size()).isEqualTo(0); } @Test @@ -189,8 +182,8 @@ public class DelayHandlerTests { .setHeader("delay", 100).build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -202,8 +195,8 @@ public class DelayHandlerTests { .setHeader("delay", -7000).build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isSameAs(Thread.currentThread()); } @Test @@ -215,8 +208,8 @@ public class DelayHandlerTests { .setHeader("delay", "not a number").build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -228,8 +221,8 @@ public class DelayHandlerTests { .setHeader("delay", new Date(new Date().getTime() + 150)).build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -241,8 +234,8 @@ public class DelayHandlerTests { .setHeader("delay", new Date(new Date().getTime() - 60 * 1000)).build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isSameAs(Thread.currentThread()); } @Test @@ -254,8 +247,8 @@ public class DelayHandlerTests { .setHeader("delay", nullDate).build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isSameAs(Thread.currentThread()); } @Test(expected = TestTimedOutException.class) @@ -278,8 +271,8 @@ public class DelayHandlerTests { .setHeader("delay", "20").build(); input.send(message); waitForLatch(10000); - assertSame(message.getPayload(), resultHandler.lastMessage.getPayload()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -300,7 +293,7 @@ public class DelayHandlerTests { } }).start(); - assertTrue(latch.await(10, TimeUnit.SECONDS)); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test @@ -311,8 +304,8 @@ public class DelayHandlerTests { this.delayHandler.handleMessage(new GenericMessage<>("foo")); this.taskScheduler.destroy(); - assertTrue(this.taskScheduler.getScheduledExecutor().awaitTermination(10, TimeUnit.SECONDS)); - assertTrue(this.latch.await(10, TimeUnit.SECONDS)); + assertThat(this.taskScheduler.getScheduledExecutor().awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + assertThat(this.latch.await(10, TimeUnit.SECONDS)).isTrue(); } @Test(expected = MessageDeliveryException.class) @@ -346,11 +339,11 @@ public class DelayHandlerTests { input.send(message); waitForLatch(10000); Message errorMessage = resultHandler.lastMessage; - assertEquals(MessageDeliveryException.class, errorMessage.getPayload().getClass()); + assertThat(errorMessage.getPayload().getClass()).isEqualTo(MessageDeliveryException.class); MessageDeliveryException exceptionPayload = (MessageDeliveryException) errorMessage.getPayload(); - assertSame(message.getPayload(), exceptionPayload.getFailedMessage().getPayload()); - assertEquals(UnsupportedOperationException.class, exceptionPayload.getCause().getClass()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(exceptionPayload.getFailedMessage().getPayload()).isSameAs(message.getPayload()); + assertThat(exceptionPayload.getCause().getClass()).isEqualTo(UnsupportedOperationException.class); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -378,11 +371,11 @@ public class DelayHandlerTests { input.send(message); waitForLatch(10000); Message errorMessage = resultHandler.lastMessage; - assertEquals(MessageDeliveryException.class, errorMessage.getPayload().getClass()); + assertThat(errorMessage.getPayload().getClass()).isEqualTo(MessageDeliveryException.class); MessageDeliveryException exceptionPayload = (MessageDeliveryException) errorMessage.getPayload(); - assertSame(message.getPayload(), exceptionPayload.getFailedMessage().getPayload()); - assertEquals(UnsupportedOperationException.class, exceptionPayload.getCause().getClass()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(exceptionPayload.getFailedMessage().getPayload()).isSameAs(message.getPayload()); + assertThat(exceptionPayload.getCause().getClass()).isEqualTo(UnsupportedOperationException.class); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test @@ -408,11 +401,11 @@ public class DelayHandlerTests { input.send(message); waitForLatch(10000); Message errorMessage = resultHandler.lastMessage; - assertEquals(MessageDeliveryException.class, errorMessage.getPayload().getClass()); + assertThat(errorMessage.getPayload().getClass()).isEqualTo(MessageDeliveryException.class); MessageDeliveryException exceptionPayload = (MessageDeliveryException) errorMessage.getPayload(); - assertSame(message.getPayload(), exceptionPayload.getFailedMessage().getPayload()); - assertEquals(UnsupportedOperationException.class, exceptionPayload.getCause().getClass()); - assertNotSame(Thread.currentThread(), resultHandler.lastThread); + assertThat(exceptionPayload.getFailedMessage().getPayload()).isSameAs(message.getPayload()); + assertThat(exceptionPayload.getCause().getClass()).isEqualTo(UnsupportedOperationException.class); + assertThat(resultHandler.lastThread).isNotSameAs(Thread.currentThread()); } @Test //INT-1132 @@ -430,15 +423,15 @@ public class DelayHandlerTests { // emulate restart this.taskScheduler.destroy(); - assertEquals(1, messageGroupStore.getMessageGroupCount()); - assertEquals(DELAYER_MESSAGE_GROUP_ID, messageGroupStore.iterator().next().getGroupId()); - assertEquals(1, messageGroupStore.messageGroupSize(DELAYER_MESSAGE_GROUP_ID)); - assertEquals(1, messageGroupStore.getMessageCountForAllMessageGroups()); + assertThat(messageGroupStore.getMessageGroupCount()).isEqualTo(1); + assertThat(messageGroupStore.iterator().next().getGroupId()).isEqualTo(DELAYER_MESSAGE_GROUP_ID); + assertThat(messageGroupStore.messageGroupSize(DELAYER_MESSAGE_GROUP_ID)).isEqualTo(1); + assertThat(messageGroupStore.getMessageCountForAllMessageGroups()).isEqualTo(1); MessageGroup messageGroup = messageGroupStore.getMessageGroup(DELAYER_MESSAGE_GROUP_ID); Message messageInStore = messageGroup.getMessages().iterator().next(); Object payload = messageInStore.getPayload(); - assertEquals("DelayedMessageWrapper", payload.getClass().getSimpleName()); - assertEquals(message.getPayload(), TestUtils.getPropertyValue(payload, "original.payload")); + assertThat(payload.getClass().getSimpleName()).isEqualTo("DelayedMessageWrapper"); + assertThat(TestUtils.getPropertyValue(payload, "original.payload")).isEqualTo(message.getPayload()); this.taskScheduler.afterPropertiesSet(); this.delayHandler = new DelayHandler(DELAYER_MESSAGE_GROUP_ID, this.taskScheduler); @@ -450,10 +443,10 @@ public class DelayHandlerTests { waitForLatch(10000); - assertSame(message.getPayload(), this.resultHandler.lastMessage.getPayload()); - assertNotSame(Thread.currentThread(), this.resultHandler.lastThread); - assertEquals(1, messageGroupStore.getMessageGroupCount()); - assertEquals(0, messageGroupStore.messageGroupSize(DELAYER_MESSAGE_GROUP_ID)); + assertThat(this.resultHandler.lastMessage.getPayload()).isSameAs(message.getPayload()); + assertThat(this.resultHandler.lastThread).isNotSameAs(Thread.currentThread()); + assertThat(messageGroupStore.getMessageGroupCount()).isEqualTo(1); + assertThat(messageGroupStore.messageGroupSize(DELAYER_MESSAGE_GROUP_ID)).isEqualTo(0); } @Test //INT-1132 @@ -493,9 +486,9 @@ public class DelayHandlerTests { this.input.send(new GenericMessage<>("foo")); this.delayHandler.reschedulePersistedMessages(); Message message = results.receive(10000); - assertNotNull(message); + assertThat(message).isNotNull(); message = results.receive(50); - assertNull(message); + assertThat(message).isNull(); } @Test @@ -528,7 +521,7 @@ public class DelayHandlerTests { while (n++ < 2000 && works.size() == 0) { Thread.sleep(10); } - assertEquals(1, works.size()); + assertThat(works.size()).isEqualTo(1); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java index 30bdd368a4..c39da42987 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,14 @@ package org.springframework.integration.handler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import java.util.Arrays; import java.util.UUID; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; @@ -61,21 +55,15 @@ import org.springframework.messaging.support.GenericMessage; */ public class ExpressionEvaluatingMessageProcessorTests { - private static final Log logger = LogFactory.getLog(ExpressionEvaluatingMessageProcessorTests.class); - private static final ExpressionParser expressionParser = new SpelExpressionParser(); - - @Rule - public ExpectedException expected = ExpectedException.none(); - - @Test public void testProcessMessage() { Expression expression = expressionParser.parseExpression("payload"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); + assertThat(processor.processMessage(new GenericMessage<>("foo"))).isEqualTo("foo"); } @Test @@ -86,15 +74,17 @@ public class ExpressionEvaluatingMessageProcessorTests { public String stringify(int number) { return number + ""; } + } Expression expression = expressionParser.parseExpression("#target.stringify(payload)"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); processor.afterPropertiesSet(); EvaluationContext evaluationContext = TestUtils.getPropertyValue(processor, "evaluationContext", EvaluationContext.class); evaluationContext.setVariable("target", new TestTarget()); - assertEquals("2", processor.processMessage(new GenericMessage<>("2"))); + assertThat(processor.processMessage(new GenericMessage<>("2"))).isEqualTo("2"); } @Test @@ -104,16 +94,18 @@ public class ExpressionEvaluatingMessageProcessorTests { public void ping(String input) { } + } Expression expression = expressionParser.parseExpression("#target.ping(payload)"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); processor.afterPropertiesSet(); EvaluationContext evaluationContext = TestUtils.getPropertyValue(processor, "evaluationContext", EvaluationContext.class); evaluationContext.setVariable("target", new TestTarget()); - assertEquals(null, processor.processMessage(new GenericMessage<>("2"))); + assertThat(processor.processMessage(new GenericMessage<>("2"))).isEqualTo(null); } @Test @@ -127,7 +119,8 @@ public class ExpressionEvaluatingMessageProcessorTests { } Expression expression = expressionParser.parseExpression("#target.find(payload)"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); AbstractApplicationContext applicationContext = new GenericApplicationContext(); processor.setBeanFactory(applicationContext); IntegrationEvaluationContextFactoryBean factoryBean = new IntegrationEvaluationContextFactoryBean(); @@ -142,25 +135,27 @@ public class ExpressionEvaluatingMessageProcessorTests { TestUtils.getPropertyValue(processor, "evaluationContext", EvaluationContext.class); evaluationContext.setVariable("target", new TestTarget()); String result = processor.processMessage(new GenericMessage<>("classpath*:*-test.xml")); - assertTrue("Wrong result: " + result, result.contains("log4j2-test.xml")); + assertThat(result.contains("log4j2-test.xml")).as("Wrong result: " + result).isTrue(); } @Test public void testProcessMessageWithDollarInBrackets() { Expression expression = expressionParser.parseExpression("headers['$foo_id']"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").setHeader("$foo_id", "abc").build(); - assertEquals("abc", processor.processMessage(message)); + assertThat(processor.processMessage(message)).isEqualTo("abc"); } @Test public void testProcessMessageWithDollarPropertyAccess() { Expression expression = expressionParser.parseExpression("headers.$foo_id"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").setHeader("$foo_id", "xyz").build(); - assertEquals("xyz", processor.processMessage(message)); + assertThat(processor.processMessage(message)).isEqualTo("xyz"); } @Test @@ -169,7 +164,7 @@ public class ExpressionEvaluatingMessageProcessorTests { ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); GenericMessage message = new GenericMessage<>("foo"); - assertEquals(message.getHeaders().getId(), processor.processMessage(message)); + assertThat(processor.processMessage(message)).isEqualTo(message.getHeaders().getId()); } @Test @@ -183,11 +178,12 @@ public class ExpressionEvaluatingMessageProcessorTests { context.refresh(); Expression expression = expressionParser.parseExpression("payload.concat(@testString)"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(context); processor.afterPropertiesSet(); GenericMessage message = new GenericMessage<>("foo"); - assertEquals("foobar", processor.processMessage(message)); + assertThat(processor.processMessage(message)).isEqualTo("foobar"); } @Test @@ -201,83 +197,42 @@ public class ExpressionEvaluatingMessageProcessorTests { context.refresh(); Expression expression = expressionParser.parseExpression("@testString.concat(payload)"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(context); processor.afterPropertiesSet(); GenericMessage message = new GenericMessage<>("foo"); - assertEquals("barfoo", processor.processMessage(message)); + assertThat(processor.processMessage(message)).isEqualTo("barfoo"); } @Test public void testProcessMessageBadExpression() { - expected.expect(new TypeSafeMatcher(Exception.class) { - - private Throwable cause; - - @Override - public boolean matchesSafely(Exception item) { - logger.debug(item); - cause = item.getCause(); - return cause instanceof EvaluationException; - } - - @Override - public void describeTo(Description description) { - description.appendText("cause to be EvaluationException but was ").appendValue(cause); - } - }); Expression expression = expressionParser.parseExpression("payload.fixMe()"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); + assertThatThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) + .hasCauseInstanceOf(EvaluationException.class); } @Test public void testProcessMessageExpressionThrowsRuntimeException() { - expected.expect(new TypeSafeMatcher(Exception.class) { - - private Throwable cause; - - @Override - public boolean matchesSafely(Exception item) { - logger.debug(item); - cause = item.getCause(); - return cause instanceof UnsupportedOperationException; - } - - @Override - public void describeTo(Description description) { - description.appendText("cause to be UnsupportedOperationException but was ").appendValue(cause); - } - }); Expression expression = expressionParser.parseExpression("payload.throwRuntimeException()"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", processor.processMessage(new GenericMessage<>(new TestPayload()))); + assertThatThrownBy(() -> processor.processMessage(new GenericMessage<>(new TestPayload()))) + .hasCauseInstanceOf(UnsupportedOperationException.class); } @Test public void testProcessMessageExpressionThrowsCheckedException() { - expected.expect(new TypeSafeMatcher(Exception.class) { - - private Throwable cause; - - @Override - public boolean matchesSafely(Exception item) { - logger.debug(item); - cause = item.getCause(); - return cause instanceof CheckedException; - } - - @Override - public void describeTo(Description description) { - description.appendText("cause to be CheckedException but was ").appendValue(cause); - } - }); Expression expression = expressionParser.parseExpression("payload.throwCheckedException()"); - ExpressionEvaluatingMessageProcessor processor = new ExpressionEvaluatingMessageProcessor<>(expression); + ExpressionEvaluatingMessageProcessor processor = + new ExpressionEvaluatingMessageProcessor<>(expression); processor.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", processor.processMessage(new GenericMessage<>(new TestPayload()))); + assertThatThrownBy(() -> processor.processMessage(new GenericMessage<>(new TestPayload()))) + .hasCauseInstanceOf(CheckedException.class); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java index eadfe6d436..a5f973e3c5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/HeaderAnnotationTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.handler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import org.junit.Test; @@ -52,9 +50,9 @@ public class HeaderAnnotationTransformerTests { handler.setOutputChannel(outputChannel); handler.handleMessage(MessageBuilder.withPayload("test").setCorrelationId("abc").build()); Message result = outputChannel.receive(0); - assertNotNull(result); - assertEquals("testabc", result.getPayload()); - assertEquals("abc", new IntegrationMessageHeaderAccessor(result).getCorrelationId()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("testabc"); + assertThat(new IntegrationMessageHeaderAccessor(result).getCorrelationId()).isEqualTo("abc"); } @Test // INT-1082 @@ -68,9 +66,9 @@ public class HeaderAnnotationTransformerTests { handler.setOutputChannel(outputChannel); handler.handleMessage(MessageBuilder.withPayload("test").setCorrelationId("abc").build()); Message result = outputChannel.receive(0); - assertNotNull(result); - assertEquals("ABC", result.getPayload()); - assertEquals("abc", new IntegrationMessageHeaderAccessor(result).getCorrelationId()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("ABC"); + assertThat(new IntegrationMessageHeaderAccessor(result).getCorrelationId()).isEqualTo("abc"); } @Test @@ -84,9 +82,9 @@ public class HeaderAnnotationTransformerTests { handler.setOutputChannel(outputChannel); handler.handleMessage(MessageBuilder.withPayload("test").setHeader("foo", "bar").build()); Message result = outputChannel.receive(0); - assertNotNull(result); - assertEquals("testbar", result.getPayload()); - assertEquals("bar", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("testbar"); + assertThat(result.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -100,9 +98,9 @@ public class HeaderAnnotationTransformerTests { handler.setOutputChannel(outputChannel); handler.handleMessage(MessageBuilder.withPayload("test").setHeader("foo", "bar").build()); Message result = outputChannel.receive(0); - assertNotNull(result); - assertEquals("BAR", result.getPayload()); - assertEquals("bar", result.getHeaders().get("foo")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("BAR"); + assertThat(result.getHeaders().get("foo")).isEqualTo("bar"); } @@ -122,9 +120,9 @@ public class HeaderAnnotationTransformerTests { .setHeader("foo", "bar") .build()); Message result = outputChannel.receive(0); - assertNotNull(result); - assertEquals("BAR", result.getPayload()); - assertFalse(result.getHeaders().containsKey(IntegrationMessageHeaderAccessor.CORRELATION_ID)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("BAR"); + assertThat(result.getHeaders().containsKey(IntegrationMessageHeaderAccessor.CORRELATION_ID)).isFalse(); } public static class TestTransformer { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java index 56fcb23285..969d3045d5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/LoggingHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.handler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -71,7 +71,7 @@ public class LoggingHandlerTests { fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { - assertEquals("Cannot set both 'expression' AND 'shouldLogFullMessage' properties", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Cannot set both 'expression' AND 'shouldLogFullMessage' properties"); } loggingHandler = new LoggingHandler("INFO"); @@ -81,7 +81,7 @@ public class LoggingHandlerTests { fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { - assertEquals("Cannot set both 'expression' AND 'shouldLogFullMessage' properties", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Cannot set both 'expression' AND 'shouldLogFullMessage' properties"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java index 0e155bac95..a146201122 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java @@ -16,11 +16,8 @@ package org.springframework.integration.handler; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.util.Collections; @@ -57,8 +54,8 @@ public class MethodInvokingHeaderEnricherTests { enricher.setDefaultOverwrite(true); Message message = MessageBuilder.withPayload("test").build(); Message result = enricher.transform(message); - assertEquals("TEST", result.getHeaders().get("foo")); - assertEquals("ABC", result.getHeaders().get("bar")); + assertThat(result.getHeaders().get("foo")).isEqualTo("TEST"); + assertThat(result.getHeaders().get("bar")).isEqualTo("ABC"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -71,8 +68,8 @@ public class MethodInvokingHeaderEnricherTests { enricher.setMessageProcessor(processor); Message message = MessageBuilder.withPayload("test").setHeader("bar", "XYZ").build(); Message result = enricher.transform(message); - assertEquals("TEST", result.getHeaders().get("foo")); - assertEquals("XYZ", result.getHeaders().get("bar")); + assertThat(result.getHeaders().get("foo")).isEqualTo("TEST"); + assertThat(result.getHeaders().get("bar")).isEqualTo("XYZ"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -86,8 +83,8 @@ public class MethodInvokingHeaderEnricherTests { enricher.setDefaultOverwrite(false); Message message = MessageBuilder.withPayload("test").setHeader("bar", "XYZ").build(); Message result = enricher.transform(message); - assertEquals("TEST", result.getHeaders().get("foo")); - assertEquals("XYZ", result.getHeaders().get("bar")); + assertThat(result.getHeaders().get("foo")).isEqualTo("TEST"); + assertThat(result.getHeaders().get("bar")).isEqualTo("XYZ"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -101,8 +98,8 @@ public class MethodInvokingHeaderEnricherTests { enricher.setDefaultOverwrite(true); Message message = MessageBuilder.withPayload("test").setHeader("bar", "XYZ").build(); Message result = enricher.transform(message); - assertEquals("TEST", result.getHeaders().get("foo")); - assertEquals("ABC", result.getHeaders().get("bar")); + assertThat(result.getHeaders().get("foo")).isEqualTo("TEST"); + assertThat(result.getHeaders().get("bar")).isEqualTo("ABC"); } @Test @@ -116,8 +113,9 @@ public class MethodInvokingHeaderEnricherTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), containsString("HeaderEnricher cannot override 'id' and 'timestamp' read-only headers.")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()) + .contains("HeaderEnricher cannot override 'id' and 'timestamp' read-only headers."); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java index 874bba8faf..2ff14ca6d9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java @@ -16,11 +16,7 @@ package org.springframework.integration.handler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; @@ -36,7 +32,6 @@ import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; @@ -79,13 +74,13 @@ public class MethodInvokingMessageProcessorAnnotationTests { public void run() { Object result = processor.processMessage(new GenericMessage<>("foo")); - assertNotNull(result); + assertThat(result).isNotNull(); } }); } exec.shutdown(); - assertTrue(exec.awaitTermination(10, TimeUnit.SECONDS)); - assertEquals(0, concurrencyFailures); + assertThat(exec.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + assertThat(concurrencyFailures).isEqualTo(0); } @Test @@ -94,7 +89,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage<>("foo")); - assertNull(result); + assertThat(result).isNull(); } @Test(expected = MessageHandlingException.class) @@ -126,7 +121,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(message); - assertEquals(123, result); + assertThat(result).isEqualTo(123); } @Test(expected = MessageHandlingException.class) @@ -147,7 +142,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { Message message = MessageBuilder.withPayload("foo") .setHeader("num", 123).build(); Object result = processor.processMessage(message); - assertEquals("null123", result); + assertThat(result).isEqualTo("null123"); } @Test @@ -160,7 +155,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { .setHeader("prop", "bar") .build(); Object result = processor.processMessage(message); - assertEquals("bar123", result); + assertThat(result).isEqualTo("bar123"); } @Test @@ -170,21 +165,22 @@ public class MethodInvokingMessageProcessorAnnotationTests { processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); - assertFalse(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)); + assertThat(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)).isFalse(); for (int i = 0; i < 99; i++) { Object result = processor.processMessage(message); Properties props = (Properties) result; - assertEquals("foo", props.getProperty("prop1")); - assertEquals("bar", props.getProperty("prop2")); - assertFalse(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)); + assertThat(props.getProperty("prop1")).isEqualTo("foo"); + assertThat(props.getProperty("prop2")).isEqualTo("bar"); + assertThat(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)) + .isFalse(); } Object result = processor.processMessage(message); Properties props = (Properties) result; - assertEquals("foo", props.getProperty("prop1")); - assertEquals("bar", props.getProperty("prop2")); + assertThat(props.getProperty("prop1")).isEqualTo("foo"); + assertThat(props.getProperty("prop2")).isEqualTo("bar"); - assertTrue(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)); + assertThat(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)).isTrue(); } @Test @@ -196,9 +192,9 @@ public class MethodInvokingMessageProcessorAnnotationTests { .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); Object result = processor.processMessage(message); Properties props = (Properties) result; - assertEquals("foo", props.getProperty("prop1")); - assertEquals("bar", props.getProperty("prop2")); - assertEquals("test", props.getProperty("payload")); + assertThat(props.getProperty("prop1")).isEqualTo("foo"); + assertThat(props.getProperty("prop2")).isEqualTo("bar"); + assertThat(props.getProperty("payload")).isEqualTo("test"); } @Test @@ -209,12 +205,12 @@ public class MethodInvokingMessageProcessorAnnotationTests { Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); Map result = (Map) processor.processMessage(message); - assertEquals(5, result.size()); - assertTrue(result.containsKey(MessageHeaders.ID)); - assertTrue(result.containsKey(MessageHeaders.TIMESTAMP)); - assertEquals("foo", result.get("prop1")); - assertEquals("bar", result.get("prop2")); - assertEquals("test", result.get("payload")); + assertThat(result.size()).isEqualTo(5); + assertThat(result.containsKey(MessageHeaders.ID)).isTrue(); + assertThat(result.containsKey(MessageHeaders.TIMESTAMP)).isTrue(); + assertThat(result.get("prop1")).isEqualTo("foo"); + assertThat(result.get("prop2")).isEqualTo("bar"); + assertThat(result.get("payload")).isEqualTo("test"); } @Test @@ -228,9 +224,9 @@ public class MethodInvokingMessageProcessorAnnotationTests { Message message = MessageBuilder.withPayload(payload) .setHeader("prop1", "not").setHeader("prop2", "these").build(); Properties result = (Properties) processor.processMessage(message); - assertEquals(2, result.size()); - assertEquals("foo", result.getProperty("prop1")); - assertEquals("bar", result.getProperty("prop2")); + assertThat(result.size()).isEqualTo(2); + assertThat(result.getProperty("prop1")).isEqualTo("foo"); + assertThat(result.getProperty("prop2")).isEqualTo("bar"); } @Test @@ -242,8 +238,8 @@ public class MethodInvokingMessageProcessorAnnotationTests { .setHeader("attrib1", 123) .setHeader("attrib2", 456).build(); Map result = (Map) processor.processMessage(message); - assertEquals(123, result.get("attrib1")); - assertEquals(456, result.get("attrib2")); + assertThat(result.get("attrib1")).isEqualTo(123); + assertThat(result.get("attrib2")).isEqualTo(456); } @Test @@ -258,9 +254,9 @@ public class MethodInvokingMessageProcessorAnnotationTests { .setHeader("attrib1", 123) .setHeader("attrib2", 456).build(); Map result = (Map) processor.processMessage(message); - assertEquals(2, result.size()); - assertEquals(new Integer(88), result.get("attrib1")); - assertEquals(new Integer(99), result.get("attrib2")); + assertThat(result.size()).isEqualTo(2); + assertThat(result.get("attrib1")).isEqualTo(new Integer(88)); + assertThat(result.get("attrib2")).isEqualTo(new Integer(99)); } @Test @@ -270,7 +266,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(message); - Assert.assertEquals("monday", result); + assertThat(result).isEqualTo("monday"); } @Test @@ -280,7 +276,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(message); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test @@ -295,13 +291,13 @@ public class MethodInvokingMessageProcessorAnnotationTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); processor.setBeanFactory(mock(BeanFactory.class)); Object[] parameters = (Object[]) processor.processMessage(message); - assertNotNull(parameters); - assertEquals(5, parameters.length); - assertEquals("monday", parameters[0]); - assertEquals("September", parameters[1]); - assertEquals(parameters[2], employee); - assertEquals("oleg", parameters[3]); - assertTrue(parameters[4] instanceof Map); + assertThat(parameters).isNotNull(); + assertThat(parameters.length).isEqualTo(5); + assertThat(parameters[0]).isEqualTo("monday"); + assertThat(parameters[1]).isEqualTo("September"); + assertThat(employee).isEqualTo(parameters[2]); + assertThat(parameters[3]).isEqualTo("oleg"); + assertThat(parameters[4] instanceof Map).isTrue(); } @Test @@ -311,8 +307,8 @@ public class MethodInvokingMessageProcessorAnnotationTests { processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); - Assert.assertTrue(result instanceof Map); - Assert.assertEquals("jkl", ((Map) result).get("number")); + assertThat(result instanceof Map).isTrue(); + assertThat(((Map) result).get("number")).isEqualTo("jkl"); } @Test @@ -322,8 +318,8 @@ public class MethodInvokingMessageProcessorAnnotationTests { processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); - Assert.assertTrue(result instanceof String); - Assert.assertEquals("oleg", result); + assertThat(result instanceof String).isTrue(); + assertThat(result).isEqualTo("oleg"); } @Test @@ -333,7 +329,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); - Assert.assertEquals("oleg zhurakousky", result); + assertThat(result).isEqualTo("oleg zhurakousky"); } @Test @@ -343,7 +339,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("day", "monday").build(); Object result = processor.processMessage(message); - Assert.assertEquals("olegmonday", result); + assertThat(result).isEqualTo("olegmonday"); } @Test(expected = MessagingException.class) @@ -363,7 +359,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { Employee employee = new Employee("John", "Doe"); Message message = MessageBuilder.withPayload("payload").setHeader("emp", employee).build(); Object result = processor.processMessage(message); - assertEquals("DOE, John", result); + assertThat(result).isEqualTo("DOE, John"); } @Test @@ -373,7 +369,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("payload").setHeader("foo-bar", "abc").build(); Object result = processor.processMessage(message); - assertEquals("ABC", result); + assertThat(result).isEqualTo("ABC"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java index dc765e84da..1a933bfba8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java @@ -16,15 +16,9 @@ package org.springframework.integration.handler; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -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.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.willAnswer; @@ -48,12 +42,7 @@ import java.util.stream.Collectors; import org.aopalliance.intercept.MethodInterceptor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hamcrest.Description; -import org.hamcrest.Matchers; -import org.hamcrest.TypeSafeMatcher; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.DirectFieldAccessor; @@ -113,9 +102,6 @@ public class MethodInvokingMessageProcessorTests { private static final Log logger = LogFactory.getLog(MethodInvokingMessageProcessorTests.class); - @Rule - public ExpectedException expected = ExpectedException.none(); - @Test public void testMessageHandlerMethodFactoryOverride() { try (AnnotationConfigApplicationContext context = @@ -123,7 +109,7 @@ public class MethodInvokingMessageProcessorTests { MessageChannel channel = context.getBean("foo", MessageChannel.class); channel.send(MessageBuilder.withPayload("Bob Smith").build()); PollableChannel out = context.getBean("out", PollableChannel.class); - assertEquals("Person: Bob Smith", out.receive().getPayload()); + assertThat(out.receive().getPayload()).isEqualTo("Person: Bob Smith"); } } @@ -201,7 +187,7 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new B(), "myMethod"); processor.setBeanFactory(mock(BeanFactory.class)); Message message = (Message) processor.processMessage(new GenericMessage<>("")); - assertEquals("A", message.getHeaders().get("A")); + assertThat(message.getHeaders().get("A")).isEqualTo("A"); } @Test @@ -232,7 +218,7 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new B(), "myMethod"); processor.setBeanFactory(mock(BeanFactory.class)); Message message = (Message) processor.processMessage(new GenericMessage<>("")); - assertEquals("B", message.getHeaders().get("B")); + assertThat(message.getHeaders().get("B")).isEqualTo("B"); } public void testHandlerInheritanceMethodImplInSubClass() { @@ -265,7 +251,7 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new C(), "myMethod"); Message message = (Message) processor.processMessage(new GenericMessage<>("")); - assertEquals("C", message.getHeaders().get("C")); + assertThat(message.getHeaders().get("C")).isEqualTo("C"); } public void testHandlerInheritanceMethodImplInSubClassAndSuper() { @@ -293,7 +279,7 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new C(), "myMethod"); Message message = (Message) processor.processMessage(new GenericMessage<>("")); - assertEquals("C", message.getHeaders().get("C")); + assertThat(message.getHeaders().get("C")).isEqualTo("C"); } @Test @@ -302,7 +288,7 @@ public class MethodInvokingMessageProcessorTests { "acceptPayloadAndReturnObject"); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage("testing")); - assertEquals("testing-1", result); + assertThat(result).isEqualTo("testing-1"); } @Test @@ -311,7 +297,7 @@ public class MethodInvokingMessageProcessorTests { "acceptPayloadAndReturnObject"); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage(123456789)); - assertEquals("123456789-1", result); + assertThat(result).isEqualTo("123456789-1"); } @Test @@ -320,7 +306,7 @@ public class MethodInvokingMessageProcessorTests { "acceptPayloadAndReturnMessage"); processor.setBeanFactory(mock(BeanFactory.class)); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); - assertEquals("testing-2", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("testing-2"); } @Test @@ -329,7 +315,7 @@ public class MethodInvokingMessageProcessorTests { "acceptMessageAndReturnObject"); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage("testing")); - assertEquals("testing-3", result); + assertThat(result).isEqualTo("testing-3"); } @Test @@ -338,7 +324,7 @@ public class MethodInvokingMessageProcessorTests { "acceptMessageAndReturnMessage"); processor.setBeanFactory(mock(BeanFactory.class)); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); - assertEquals("testing-4", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("testing-4"); } @Test @@ -347,7 +333,7 @@ public class MethodInvokingMessageProcessorTests { "acceptMessageSubclassAndReturnMessage"); processor.setBeanFactory(mock(BeanFactory.class)); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); - assertEquals("testing-5", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("testing-5"); } @Test @@ -356,7 +342,7 @@ public class MethodInvokingMessageProcessorTests { "acceptMessageSubclassAndReturnMessageSubclass"); processor.setBeanFactory(mock(BeanFactory.class)); Message result = (Message) processor.processMessage(new GenericMessage("testing")); - assertEquals("testing-6", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("testing-6"); } @Test @@ -366,7 +352,7 @@ public class MethodInvokingMessageProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); Message request = MessageBuilder.withPayload("testing").setHeader("number", 123).build(); Object result = processor.processMessage(request); - assertEquals("testing-123", result); + assertThat(result).isEqualTo("testing-123"); } @Test @@ -374,8 +360,8 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "testVoidReturningMethods"); processor.setBeanFactory(mock(BeanFactory.class)); - assertNull(processor.processMessage(MessageBuilder.withPayload("Something").build())); - assertEquals(12, processor.processMessage(MessageBuilder.withPayload(12).build())); + assertThat(processor.processMessage(MessageBuilder.withPayload("Something").build())).isNull(); + assertThat(processor.processMessage(MessageBuilder.withPayload(12).build())).isEqualTo(12); } @Test @@ -385,7 +371,7 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage<>("foo")); - assertEquals("foo", result); + assertThat(result).isEqualTo("foo"); } @Test @@ -395,7 +381,7 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage<>(123)); - assertEquals(123, result); + assertThat(result).isEqualTo(123); } @Test @@ -405,7 +391,7 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage<>("456")); - assertEquals(456, result); + assertThat(result).isEqualTo(456); } @Test(expected = MessageHandlingException.class) @@ -423,50 +409,50 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, ServiceActivator.class); processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(MessageBuilder.withPayload(123).build()); - assertNotNull(bean.lastArg); - assertEquals(String.class, bean.lastArg.getClass()); - assertEquals("123", bean.lastArg); + assertThat(bean.lastArg).isNotNull(); + assertThat(bean.lastArg.getClass()).isEqualTo(String.class); + assertThat(bean.lastArg).isEqualTo("123"); } @Test public void testProcessMessageBadExpression() throws Exception { - expected.expect(MessageHandlingException.class); AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); + assertThatThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) + .isInstanceOf(MessageHandlingException.class); } @Test public void testProcessMessageRuntimeException() throws Exception { - expected.expect(new ExceptionCauseMatcher(UnsupportedOperationException.class)); TestErrorService service = new TestErrorService(); Method method = service.getClass().getMethod("error", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); + assertThatThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) + .hasCauseInstanceOf(UnsupportedOperationException.class); } @Test public void testProcessMessageCheckedException() throws Exception { - expected.expect(new ExceptionCauseMatcher(CheckedException.class)); TestErrorService service = new TestErrorService(); Method method = service.getClass().getMethod("checked", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); + assertThatThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) + .hasCauseInstanceOf(CheckedException.class); } @Test public void testProcessMessageMethodNotFound() throws Exception { - expected.expect(new ExceptionCauseMatcher(SpelEvaluationException.class)); TestDifferentErrorService service = new TestDifferentErrorService(); Method method = TestErrorService.class.getMethod("checked", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); processor.setBeanFactory(mock(BeanFactory.class)); - processor.processMessage(new GenericMessage<>("foo")); + assertThatThrownBy(() -> processor.processMessage(new GenericMessage<>("foo"))) + .hasCauseInstanceOf(SpelEvaluationException.class); } @Test @@ -477,7 +463,7 @@ public class MethodInvokingMessageProcessorTests { processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").setHeader("number", 42).build(); Object result = processor.processMessage(message); - assertEquals("foo-42", result); + assertThat(result).isEqualTo("foo-42"); } @Test @@ -492,7 +478,7 @@ public class MethodInvokingMessageProcessorTests { .setHeader("number", 42) .build(); Object result = processor.processMessage(message); - assertEquals("bar-42", result); + assertThat(result).isEqualTo("bar-42"); } @Test @@ -512,7 +498,7 @@ public class MethodInvokingMessageProcessorTests { processor.setUseSpelInvoker(true); DirectFieldAccessor compilerConfigAccessor = compileImmediate(processor); optionalAndRequiredWithAnnotatedMethodGuts(processor, true); - assertNotNull(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.expression.compiledAst")); + assertThat(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.expression.compiledAst")).isNotNull(); optionalAndRequiredWithAnnotatedMethodGuts(processor, true); compilerConfigAccessor.setPropertyValue("compilerMode", SpelCompilerMode.OFF); } @@ -525,13 +511,13 @@ public class MethodInvokingMessageProcessorTests { .setHeader("num", 42) .build(); Object result = processor.processMessage(message); - assertEquals("null42", result); + assertThat(result).isEqualTo("null42"); message = MessageBuilder.withPayload("foo") .setHeader("prop", "bar") .setHeader("num", 42) .build(); result = processor.processMessage(message); - assertEquals("bar42", result); + assertThat(result).isEqualTo("bar42"); message = MessageBuilder.withPayload("foo") .setHeader("prop", "bar") .build(); @@ -541,10 +527,10 @@ public class MethodInvokingMessageProcessorTests { } catch (MessageHandlingException e) { if (compiled) { - assertThat(e.getCause().getMessage(), equalTo("required header not available: num")); + assertThat(e.getCause().getMessage()).isEqualTo("required header not available: num"); } else { - assertThat(e.getCause().getCause().getMessage(), equalTo("required header not available: num")); + assertThat(e.getCause().getCause().getMessage()).isEqualTo("required header not available: num"); } } } @@ -566,7 +552,7 @@ public class MethodInvokingMessageProcessorTests { processor.setUseSpelInvoker(true); DirectFieldAccessor compilerConfigAccessor = compileImmediate(processor); optionalAndRequiredDottedWithAnnotatedMethodGuts(processor, true); - assertNotNull(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.expression.compiledAst")); + assertThat(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.expression.compiledAst")).isNotNull(); optionalAndRequiredDottedWithAnnotatedMethodGuts(processor, true); compilerConfigAccessor.setPropertyValue("compilerMode", SpelCompilerMode.OFF); } @@ -579,13 +565,13 @@ public class MethodInvokingMessageProcessorTests { .setHeader("dot2", new DotBean()) .build(); Object result = processor.processMessage(message); - assertEquals("null42", result); + assertThat(result).isEqualTo("null42"); message = MessageBuilder.withPayload("hello") .setHeader("dot1", new DotBean()) .setHeader("dot2", new DotBean()) .build(); result = processor.processMessage(message); - assertEquals("bar42", result); + assertThat(result).isEqualTo("bar42"); message = MessageBuilder.withPayload("hello") .setHeader("dot1", new DotBean()) .build(); @@ -595,10 +581,10 @@ public class MethodInvokingMessageProcessorTests { } catch (MessageHandlingException e) { if (compiled) { - assertThat(e.getCause().getMessage(), equalTo("required header not available: dot2")); + assertThat(e.getCause().getMessage()).isEqualTo("required header not available: dot2"); } else { // interpreted - assertThat(e.getCause().getCause().getMessage(), equalTo("required header not available: dot2")); + assertThat(e.getCause().getCause().getMessage()).isEqualTo("required header not available: dot2"); } } } @@ -609,9 +595,9 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, "foo"); processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(MessageBuilder.withPayload("true").build()); - assertNotNull(bean.lastArg); - assertEquals(String.class, bean.lastArg.getClass()); - assertEquals("true", bean.lastArg); + assertThat(bean.lastArg).isNotNull(); + assertThat(bean.lastArg.getClass()).isEqualTo(String.class); + assertThat(bean.lastArg).isEqualTo("true"); } @Test @@ -626,7 +612,7 @@ public class MethodInvokingMessageProcessorTests { Method method = MessagingMethodInvokerHelper.class.getDeclaredMethod("getTargetClass", Object.class); method.setAccessible(true); Object result = method.invoke(helper, target); - assertSame(RequestReplyExchanger.class, result); + assertThat(result).isSameAs(RequestReplyExchanger.class); } @Test @@ -653,9 +639,9 @@ public class MethodInvokingMessageProcessorTests { MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(new Foo(), (String) null, false); helper.setBeanFactory(mock(BeanFactory.class)); - assertEquals("4", helper.process(new GenericMessage(2L))); - assertEquals("1", helper.process(new GenericMessage(1))); - assertEquals("foo", helper.process(new GenericMessage(new Date()))); + assertThat(helper.process(new GenericMessage(2L))).isEqualTo("4"); + assertThat(helper.process(new GenericMessage(1))).isEqualTo("1"); + assertThat(helper.process(new GenericMessage(new Date()))).isEqualTo("foo"); } @Test @@ -680,8 +666,8 @@ public class MethodInvokingMessageProcessorTests { fail("IllegalArgumentException expected"); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(IllegalArgumentException.class)); - assertEquals("Found more than one method match for empty parameter for 'payload'", e.getMessage()); + assertThat(e).isInstanceOf(IllegalArgumentException.class); + assertThat(e.getMessage()).isEqualTo("Found more than one method match for empty parameter for 'payload'"); } } @@ -711,9 +697,9 @@ public class MethodInvokingMessageProcessorTests { MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); helper.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", helper.process(new GenericMessage("foo"))); - assertEquals(1, helper.process(new GenericMessage(1))); - assertEquals(targetObject, helper.process(new GenericMessage(targetObject))); + assertThat(helper.process(new GenericMessage("foo"))).isEqualTo("foo"); + assertThat(helper.process(new GenericMessage(1))).isEqualTo(1); + assertThat(helper.process(new GenericMessage(targetObject))).isEqualTo(targetObject); } @Test @@ -742,9 +728,9 @@ public class MethodInvokingMessageProcessorTests { MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); helper.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", helper.process(new GenericMessage("foo"))); - assertEquals(1, helper.process(new GenericMessage(1))); - assertEquals(targetObject, helper.process(new GenericMessage(targetObject))); + assertThat(helper.process(new GenericMessage("foo"))).isEqualTo("foo"); + assertThat(helper.process(new GenericMessage(1))).isEqualTo(1); + assertThat(helper.process(new GenericMessage(targetObject))).isEqualTo(targetObject); } @Test @@ -774,8 +760,8 @@ public class MethodInvokingMessageProcessorTests { MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); helper.setBeanFactory(mock(BeanFactory.class)); - assertEquals("foo", helper.process(new GenericMessage("foo"))); - assertEquals("FOO", helper.process(new GenericMessage(targetObject))); + assertThat(helper.process(new GenericMessage("foo"))).isEqualTo("foo"); + assertThat(helper.process(new GenericMessage(targetObject))).isEqualTo("FOO"); } @Test @@ -784,9 +770,9 @@ public class MethodInvokingMessageProcessorTests { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, "foo"); processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(MessageBuilder.withPayload("true").build()); - assertNotNull(bean.lastArg); - assertEquals(String.class, bean.lastArg.getClass()); - assertEquals("true", bean.lastArg); + assertThat(bean.lastArg).isNotNull(); + assertThat(bean.lastArg.getClass()).isEqualTo(String.class); + assertThat(bean.lastArg).isEqualTo("true"); } @Test @@ -811,14 +797,14 @@ public class MethodInvokingMessageProcessorTests { helper.setBeanFactory(mock(BeanFactory.class)); helper.process(new GenericMessage<>(Optional.empty())); - assertNull(targetObject.arguments.get("foo")); - assertNull(targetObject.arguments.get("foo1")); - assertNull(targetObject.arguments.get("foo2")); + assertThat(targetObject.arguments.get("foo")).isNull(); + assertThat(targetObject.arguments.get("foo1")).isNull(); + assertThat(targetObject.arguments.get("foo2")).isNull(); helper.process(MessageBuilder.withPayload("foo").setHeader("foo", "FOO").build()); - assertEquals("foo", targetObject.arguments.get("foo")); - assertEquals("FOO", targetObject.arguments.get("foo1")); - assertEquals("FOO", targetObject.arguments.get("foo2")); + assertThat(targetObject.arguments.get("foo")).isEqualTo("foo"); + assertThat(targetObject.arguments.get("foo1")).isEqualTo("FOO"); + assertThat(targetObject.arguments.get("foo2")).isEqualTo("FOO"); } @Test @@ -836,8 +822,8 @@ public class MethodInvokingMessageProcessorTests { new MessagingMethodInvokerHelper(new Foo(), ServiceActivator.class, false); helper.setBeanFactory(mock(BeanFactory.class)); - assertEquals("FOO", helper.process(new GenericMessage<>("foo"))); - assertEquals("BAR", helper.process(new GenericMessage<>("bar"))); + assertThat(helper.process(new GenericMessage<>("foo"))).isEqualTo("FOO"); + assertThat(helper.process(new GenericMessage<>("bar"))).isEqualTo("BAR"); } @Test @@ -904,13 +890,12 @@ public class MethodInvokingMessageProcessorTests { processor.processMessage(new GenericMessage<>("foo")); } catch (Exception e) { - assertThat(e.getCause(), instanceOf(IllegalStateException.class)); - assertThat(e.getCause().getCause(), instanceOf(IllegalArgumentException.class)); - assertEquals(A.class.getName(), e.getCause().getStackTrace()[0].getClassName()); + assertThat(e.getCause()).isInstanceOf(IllegalStateException.class); + assertThat(e.getCause().getCause()).isInstanceOf(IllegalArgumentException.class); + assertThat(e.getCause().getStackTrace()[0].getClassName()).isEqualTo(A.class.getName()); } - assertEquals(0, - TestUtils.getPropertyValue(processor, "delegate.handlerMethod.failedAttempts")); + assertThat(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.failedAttempts")).isEqualTo(0); } @@ -941,8 +926,8 @@ public class MethodInvokingMessageProcessorTests { processor.processMessage(new GenericMessage<>("foo")); - assertEquals("foo", result.get()); - assertTrue(adviceCalled.get()); + assertThat(result.get()).isEqualTo("foo"); + assertThat(adviceCalled.get()).isTrue(); } @Test @@ -977,9 +962,9 @@ public class MethodInvokingMessageProcessorTests { processor.processMessage(testMessage); - assertEquals(testMessage.getPayload(), payloadReference.get()); - assertEquals(testMessage.getHeaders().getId(), idReference.get()); - assertTrue(adviceCalled.get()); + assertThat(payloadReference.get()).isEqualTo(testMessage.getPayload()); + assertThat(idReference.get()).isEqualTo(testMessage.getHeaders().getId()); + assertThat(adviceCalled.get()).isTrue(); } @Test @@ -991,29 +976,29 @@ public class MethodInvokingMessageProcessorTests { helper.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage<>("Test"); helper.process(message); - assertEquals(SpelCompilerMode.OFF, - TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); + assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) + .isEqualTo(SpelCompilerMode.OFF); helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("bar", String.class), false); helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); - assertEquals(SpelCompilerMode.IMMEDIATE, - TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); + assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) + .isEqualTo(SpelCompilerMode.IMMEDIATE); helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("baz", String.class), false); helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); - assertEquals(SpelCompilerMode.MIXED, - TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); + assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) + .isEqualTo(SpelCompilerMode.MIXED); helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("qux", String.class), false); helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); - assertEquals(SpelCompilerMode.OFF, - TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); + assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) + .isEqualTo(SpelCompilerMode.OFF); helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("fiz", String.class), false); @@ -1022,8 +1007,8 @@ public class MethodInvokingMessageProcessorTests { helper.process(message); } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), - equalTo("No enum constant org.springframework.expression.spel.SpelCompilerMode.JUNK")); + assertThat(e.getMessage()) + .isEqualTo("No enum constant org.springframework.expression.spel.SpelCompilerMode.JUNK"); } helper = new MessagingMethodInvokerHelper<>(bean, @@ -1035,23 +1020,22 @@ public class MethodInvokingMessageProcessorTests { helper.process(message); } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), equalTo( - "UseSpelInvoker.compilerMode: Object of class [java.lang.Object] " - + "must be an instance of class java.lang.String")); + assertThat(e.getMessage()).isEqualTo("UseSpelInvoker.compilerMode: Object of class [java.lang.Object] " + + "must be an instance of class java.lang.String"); } // Check other CTORs helper = new MessagingMethodInvokerHelper<>(bean, "bar", false); helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); - assertEquals(SpelCompilerMode.IMMEDIATE, - TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); + assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) + .isEqualTo(SpelCompilerMode.IMMEDIATE); helper = new MessagingMethodInvokerHelper<>(bean, ServiceActivator.class, false); helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); - assertEquals(SpelCompilerMode.MIXED, - TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); + assertThat(TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")) + .isEqualTo(SpelCompilerMode.MIXED); } @Test @@ -1067,7 +1051,7 @@ public class MethodInvokingMessageProcessorTests { Message message = new GenericMessage<>("{\"bar\":\"bar\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); - assertThat(bean.foo.bar, equalTo("bar")); + assertThat(bean.foo.bar).isEqualTo("bar"); } @Test @@ -1079,7 +1063,7 @@ public class MethodInvokingMessageProcessorTests { Message message = new GenericMessage<>("baz", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); - assertThat(bean.foo.getPayload(), equalTo("baz")); + assertThat(bean.foo.getPayload()).isEqualTo("baz"); } @Test @@ -1092,7 +1076,7 @@ public class MethodInvokingMessageProcessorTests { Message message = new GenericMessage<>("{\"bar\":\"bar\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); - assertThat(bean.foo.getPayload().bar, equalTo("bar")); + assertThat(bean.foo.getPayload().bar).isEqualTo("bar"); } @Test @@ -1105,8 +1089,8 @@ public class MethodInvokingMessageProcessorTests { Message message = new GenericMessage<>("{\"bar\":\"baz\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); - assertThat(bean.foo.getPayload(), instanceOf(Map.class)); - assertThat(((Map) bean.foo.getPayload()).get("bar"), equalTo("baz")); + assertThat(bean.foo.getPayload()).isInstanceOf(Map.class); + assertThat(((Map) bean.foo.getPayload()).get("bar")).isEqualTo("baz"); } @Test @@ -1126,7 +1110,7 @@ public class MethodInvokingMessageProcessorTests { expression.getValue(evaluationContext, "foo", String.class); // Twice to make a compiler to work String result = expression.getValue(evaluationContext, "foo", String.class); - assertEquals("FOO", result); + assertThat(result).isEqualTo("FOO"); } @@ -1165,7 +1149,7 @@ public class MethodInvokingMessageProcessorTests { String result = (String) processor.processMessage(testMessage); - assertEquals("Foo,Bar", result); + assertThat(result).isEqualTo("Foo,Bar"); } public static class Employee { @@ -1240,30 +1224,6 @@ public class MethodInvokingMessageProcessorTests { return accessor; } - private static class ExceptionCauseMatcher extends TypeSafeMatcher { - - private Throwable cause; - - private final Class type; - - ExceptionCauseMatcher(Class type) { - this.type = type; - } - - @Override - public boolean matchesSafely(Exception item) { - cause = item.getCause(); - assertNotNull("There is no cause for " + item, cause); - return type.isAssignableFrom(cause.getClass()); - } - - @Override - public void describeTo(Description description) { - description.appendText("cause to be ").appendValue(type).appendText("but was ").appendValue(cause); - } - - } - @SuppressWarnings("unused") private static class TestErrorService { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MockHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MockHandlerTests.java index 06f7299d78..7639160ec9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MockHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MockHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.handler; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -54,7 +54,7 @@ public class MockHandlerTests { Mockito.when(mock.test("foo")).thenReturn("bar"); input.send(MessageBuilder.withPayload("foo").setReplyChannel(output).build()); Message result = output.receive(0); - assertEquals("bar", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("bar"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/SendTimeoutConfigurationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/SendTimeoutConfigurationTests.java index bb885c41ce..c2bd70cff6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/SendTimeoutConfigurationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/SendTimeoutConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.handler; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -40,27 +40,27 @@ public class SendTimeoutConfigurationTests { @Test public void serviceActivator() { - assertEquals(123, this.getTimeout("serviceActivator")); + assertThat(this.getTimeout("serviceActivator")).isEqualTo(123); } @Test public void filter() { - assertEquals(123, this.getTimeout("filter")); + assertThat(this.getTimeout("filter")).isEqualTo(123); } @Test public void transformer() { - assertEquals(123, this.getTimeout("transformer")); + assertThat(this.getTimeout("transformer")).isEqualTo(123); } @Test public void splitter() { - assertEquals(123, this.getTimeout("splitter")); + assertThat(this.getTimeout("splitter")).isEqualTo(123); } @Test public void router() { - assertEquals(123, this.getTimeout("router")); + assertThat(this.getTimeout("router")).isEqualTo(123); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/ServiceActivatorDefaultFrameworkMethodTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/ServiceActivatorDefaultFrameworkMethodTests.java index 981caca168..ad725283d2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/ServiceActivatorDefaultFrameworkMethodTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/ServiceActivatorDefaultFrameworkMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,24 +16,12 @@ package org.springframework.integration.handler; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeaderKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -118,8 +106,8 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.gatewayTestInputChannel.send(message); Message reply = replyChannel.receive(0); - assertEquals("gatewayTestInputChannel,gatewayTestService,gateway,requestChannel,replyChannel", - reply.getHeaders().get("history").toString()); + assertThat(reply.getHeaders().get("history").toString()) + .isEqualTo("gatewayTestInputChannel,gatewayTestService,gateway,requestChannel,replyChannel"); message = MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build(); try { @@ -127,12 +115,12 @@ public class ServiceActivatorDefaultFrameworkMethodTests { fail("Exception expected"); } catch (Exception e) { - assertThat(e, instanceOf(MessageHandlingException.class)); - assertThat(e.getCause(), instanceOf(MessageTransformationException.class)); - assertThat(e.getCause().getCause(), instanceOf(MessageHandlingException.class)); - assertThat(e.getCause().getCause().getCause(), instanceOf(java.lang.IllegalStateException.class)); - assertThat(e.getMessage(), containsString("Expression evaluation failed")); - assertThat(e.getMessage(), containsString("Wrong payload")); + assertThat(e).isInstanceOf(MessageHandlingException.class); + assertThat(e.getCause()).isInstanceOf(MessageTransformationException.class); + assertThat(e.getCause().getCause()).isInstanceOf(MessageHandlingException.class); + assertThat(e.getCause().getCause().getCause()).isInstanceOf(IllegalStateException.class); + assertThat(e.getMessage()).contains("Expression evaluation failed"); + assertThat(e.getMessage()).contains("Wrong payload"); } } @@ -142,12 +130,12 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.replyingHandlerTestInputChannel.send(message); Message reply = replyChannel.receive(0); - assertEquals("TEST", reply.getPayload()); - assertEquals("replyingHandlerTestInputChannel,replyingHandlerTestService", - reply.getHeaders().get("history").toString()); + assertThat(reply.getPayload()).isEqualTo("TEST"); + assertThat(reply.getHeaders().get("history").toString()) + .isEqualTo("replyingHandlerTestInputChannel,replyingHandlerTestService"); StackTraceElement[] st = (StackTraceElement[]) reply.getHeaders().get("callStack"); - assertTrue(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", - "MethodInvokerHelper", st)); // close to the metal + assertThat(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", + "MethodInvokerHelper", st)).isTrue(); // close to the metal } @Test @@ -156,12 +144,12 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.optimizedRefReplyingHandlerTestInputChannel.send(message); Message reply = replyChannel.receive(0); - assertEquals("TEST", reply.getPayload()); - assertEquals("optimizedRefReplyingHandlerTestInputChannel,optimizedRefReplyingHandlerTestService", - reply.getHeaders().get("history").toString()); + assertThat(reply.getPayload()).isEqualTo("TEST"); + assertThat(reply.getHeaders().get("history").toString()) + .isEqualTo("optimizedRefReplyingHandlerTestInputChannel,optimizedRefReplyingHandlerTestService"); StackTraceElement[] st = (StackTraceElement[]) reply.getHeaders().get("callStack"); - assertTrue(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", - "MethodInvokerHelper", st)); // close to the metal + assertThat(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", + "MethodInvokerHelper", st)).isTrue(); // close to the metal } @Test @@ -170,12 +158,13 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.replyingHandlerWithStandardMethodTestInputChannel.send(message); Message reply = replyChannel.receive(0); - assertEquals("TEST", reply.getPayload()); - assertEquals("replyingHandlerWithStandardMethodTestInputChannel,replyingHandlerWithStandardMethodTestService", - reply.getHeaders().get("history").toString()); + assertThat(reply.getPayload()).isEqualTo("TEST"); + assertThat(reply.getHeaders().get("history").toString()) + .isEqualTo("replyingHandlerWithStandardMethodTestInputChannel," + + "replyingHandlerWithStandardMethodTestService"); StackTraceElement[] st = (StackTraceElement[]) reply.getHeaders().get("callStack"); - assertTrue(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", - "MethodInvokerHelper", st)); // close to the metal + assertThat(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", + "MethodInvokerHelper", st)).isTrue(); // close to the metal } @Test @@ -184,9 +173,9 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.replyingHandlerWithOtherMethodTestInputChannel.send(message); Message reply = replyChannel.receive(0); - assertEquals("bar", reply.getPayload()); - assertEquals("replyingHandlerWithOtherMethodTestInputChannel,replyingHandlerWithOtherMethodTestService", - reply.getHeaders().get("history").toString()); + assertThat(reply.getPayload()).isEqualTo("bar"); + assertThat(reply.getHeaders().get("history").toString()) + .isEqualTo("replyingHandlerWithOtherMethodTestInputChannel,replyingHandlerWithOtherMethodTestService"); } @Test @@ -199,7 +188,7 @@ public class ServiceActivatorDefaultFrameworkMethodTests { @Test public void testMessageProcessor() { Object processor = TestUtils.getPropertyValue(processorTestService, "handler.processor"); - assertSame(testMessageProcessor, processor); + assertThat(processor).isSameAs(testMessageProcessor); QueueChannel replyChannel = new QueueChannel(); Message message = MessageBuilder.withPayload("bar") @@ -208,8 +197,8 @@ public class ServiceActivatorDefaultFrameworkMethodTests { .build(); this.processorTestInputChannel.send(message); Message reply = replyChannel.receive(0); - assertEquals("foo:bar", reply.getPayload()); - assertThat(reply, not(hasHeaderKey("foo"))); + assertThat(reply.getPayload()).isEqualTo("foo:bar"); + assertThat(reply.getHeaders()).doesNotContainKey("foo"); } @Test @@ -220,11 +209,11 @@ public class ServiceActivatorDefaultFrameworkMethodTests { fail("Expected exception due to 2 endpoints referencing the same bean"); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(BeanCreationException.class)); - assertThat(e.getCause(), Matchers.instanceOf(BeanCreationException.class)); - assertThat(e.getCause().getCause(), Matchers.instanceOf(IllegalArgumentException.class)); - assertThat(e.getCause().getCause().getMessage(), - Matchers.containsString("An AbstractMessageProducingMessageHandler may only be referenced once")); + assertThat(e).isInstanceOf(BeanCreationException.class); + assertThat(e.getCause()).isInstanceOf(BeanCreationException.class); + assertThat(e.getCause().getCause()).isInstanceOf(IllegalArgumentException.class); + assertThat(e.getCause().getCause().getMessage()) + .contains("An AbstractMessageProducingMessageHandler may only be referenced once"); } } @@ -235,11 +224,11 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.asyncIn.send(message); Message reply = replyChannel.receive(0); - assertNull(reply); + assertThat(reply).isNull(); this.asyncService.future.set(this.asyncService.payload.toUpperCase()); reply = replyChannel.receive(0); - assertNotNull(reply); - assertEquals("TEST", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("TEST"); } @Test @@ -250,10 +239,10 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("testing").setReplyChannel(replyChannel).build(); this.asyncIn.send(message); - assertNull(reply.get()); + assertThat(reply.get()).isNull(); this.asyncService.future.set(this.asyncService.payload.toUpperCase()); - assertNotNull(reply.get()); - assertEquals("TESTING", reply.get().getPayload()); + assertThat(reply.get()).isNotNull(); + assertThat(reply.get().getPayload()).isEqualTo("TESTING"); } @Test @@ -263,12 +252,12 @@ public class ServiceActivatorDefaultFrameworkMethodTests { this.asyncIn.send(message); this.asyncService.future.setException(new RuntimeException("intended")); Message error = errorChannel.receive(0); - assertNotNull(error); - assertThat(error, instanceOf(ErrorMessage.class)); - assertThat(error.getPayload(), instanceOf(MessagingException.class)); - assertThat(((MessagingException) error.getPayload()).getCause(), instanceOf(RuntimeException.class)); - assertThat(((MessagingException) error.getPayload()).getCause().getMessage(), equalTo("intended")); - assertEquals("test", ((MessagingException) error.getPayload()).getFailedMessage().getPayload()); + assertThat(error).isNotNull(); + assertThat(error).isInstanceOf(ErrorMessage.class); + assertThat(error.getPayload()).isInstanceOf(MessagingException.class); + assertThat(((MessagingException) error.getPayload()).getCause()).isInstanceOf(RuntimeException.class); + assertThat(((MessagingException) error.getPayload()).getCause().getMessage()).isEqualTo("intended"); + assertThat(((MessagingException) error.getPayload()).getFailedMessage().getPayload()).isEqualTo("test"); } @Test @@ -277,12 +266,12 @@ public class ServiceActivatorDefaultFrameworkMethodTests { this.asyncIn.send(message); this.asyncService.future.setException(new RuntimeException("intended")); Message error = this.errorChannel.receive(0); - assertNotNull(error); - assertThat(error, instanceOf(ErrorMessage.class)); - assertThat(error.getPayload(), instanceOf(MessagingException.class)); - assertThat(((MessagingException) error.getPayload()).getCause(), instanceOf(RuntimeException.class)); - assertThat(((MessagingException) error.getPayload()).getCause().getMessage(), equalTo("intended")); - assertEquals("test", ((MessagingException) error.getPayload()).getFailedMessage().getPayload()); + assertThat(error).isNotNull(); + assertThat(error).isInstanceOf(ErrorMessage.class); + assertThat(error.getPayload()).isInstanceOf(MessagingException.class); + assertThat(((MessagingException) error.getPayload()).getCause()).isInstanceOf(RuntimeException.class); + assertThat(((MessagingException) error.getPayload()).getCause().getMessage()).isEqualTo("intended"); + assertThat(((MessagingException) error.getPayload()).getFailedMessage().getPayload()).isEqualTo("test"); } @Test @@ -291,8 +280,8 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Message message = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build(); this.processorViaFunctionChannel.send(message); Message reply = replyChannel.receive(0); - assertNotNull(reply); - assertEquals("TEST", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("TEST"); } public static void throwIllegalStateException(String message) { @@ -314,8 +303,8 @@ public class ServiceActivatorDefaultFrameworkMethodTests { Exception e = new RuntimeException(); StackTraceElement[] st = e.getStackTrace(); // use this to test that StackTraceUtils works as expected and returns false - assertFalse(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", - "MethodInvokerHelper", st)); + assertThat(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", + "MethodInvokerHelper", st)).isFalse(); return "bar"; } @@ -328,8 +317,8 @@ public class ServiceActivatorDefaultFrameworkMethodTests { public void handleMessage(Message requestMessage) { Exception e = new RuntimeException(); StackTraceElement[] st = e.getStackTrace(); - assertTrue(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", - "MethodInvokerHelper", st)); // close to the metal + assertThat(StackTraceUtils.isFrameContainingXBeforeFrameContainingY("AbstractSubscribableChannel", + "MethodInvokerHelper", st)).isTrue(); // close to the metal } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java index 691c9f090f..0546ab82d6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.handler.advice; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -49,7 +40,6 @@ import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -105,14 +95,14 @@ public class AdvisedMessageHandlerTests { fail("expected exception"); } catch (MessageHandlingException e) { - assertThat(e.getCause(), Matchers.instanceOf(ArithmeticException.class)); + assertThat(e.getCause()).isInstanceOf(ArithmeticException.class); } try { input.send(message); fail("expected exception"); } catch (RuntimeException e) { - assertThat(e.getMessage(), containsString("Circuit Breaker is Open for")); + assertThat(e.getMessage()).contains("Circuit Breaker is Open for"); } } @@ -138,8 +128,8 @@ public class AdvisedMessageHandlerTests { // no advice handler.handleMessage(message); Message reply = replies.receive(1000); - assertNotNull(reply); - assertEquals("baz", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("baz"); PollableChannel successChannel = new QueueChannel(); PollableChannel failureChannel = new QueueChannel(); @@ -170,15 +160,15 @@ public class AdvisedMessageHandlerTests { // advice with success handler.handleMessage(message); reply = replies.receive(1000); - assertNotNull(reply); - assertEquals("baz", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("baz"); - assertEquals(componentName, compName.get()); + assertThat(compName.get()).isEqualTo(componentName); Message success = successChannel.receive(1000); - assertNotNull(success); - assertEquals("Hello, world!", ((AdviceMessage) success).getInputMessage().getPayload()); - assertEquals("foo", success.getPayload()); + assertThat(success).isNotNull(); + assertThat(((AdviceMessage) success).getInputMessage().getPayload()).isEqualTo("Hello, world!"); + assertThat(success.getPayload()).isEqualTo("foo"); // advice with failure, not trapped doFail.set(true); @@ -187,34 +177,40 @@ public class AdvisedMessageHandlerTests { fail("Expected exception"); } catch (Exception e) { - assertEquals("qux", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("qux"); } Message failure = failureChannel.receive(1000); - assertNotNull(failure); - assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload()); - assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult()); + assertThat(failure).isNotNull(); + assertThat(((MessagingException) failure.getPayload()).getFailedMessage().getPayload()) + .isEqualTo("Hello, world!"); + assertThat(((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult()) + .isEqualTo("bar:qux"); // advice with failure, trapped advice.setTrapException(true); handler.handleMessage(message); failure = failureChannel.receive(1000); - assertNotNull(failure); - assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload()); - assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult()); - assertNull(replies.receive(1)); + assertThat(failure).isNotNull(); + assertThat(((MessagingException) failure.getPayload()).getFailedMessage().getPayload()) + .isEqualTo("Hello, world!"); + assertThat(((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult()) + .isEqualTo("bar:qux"); + assertThat(replies.receive(1)).isNull(); // advice with failure, eval is result advice.setReturnFailureExpressionResult(true); handler.handleMessage(message); failure = failureChannel.receive(1000); - assertNotNull(failure); - assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload()); - assertEquals("bar:qux", ((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult()); + assertThat(failure).isNotNull(); + assertThat(((MessagingException) failure.getPayload()).getFailedMessage().getPayload()) + .isEqualTo("Hello, world!"); + assertThat(((MessageHandlingExpressionEvaluatingAdviceException) failure.getPayload()).getEvaluationResult()) + .isEqualTo("bar:qux"); reply = replies.receive(1000); - assertNotNull(reply); - assertEquals("bar:qux", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("bar:qux"); } @@ -253,14 +249,14 @@ public class AdvisedMessageHandlerTests { // failing advice with success handler.handleMessage(message); Message reply = replies.receive(1000); - assertNotNull(reply); - assertEquals("baz", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("baz"); Message success = successChannel.receive(1000); - assertNotNull(success); - assertEquals("Hello, world!", ((AdviceMessage) success).getInputMessage().getPayload()); - assertEquals(ArithmeticException.class, success.getPayload().getClass()); - assertEquals("/ by zero", ((Exception) success.getPayload()).getMessage()); + assertThat(success).isNotNull(); + assertThat(((AdviceMessage) success).getInputMessage().getPayload()).isEqualTo("Hello, world!"); + assertThat(success.getPayload().getClass()).isEqualTo(ArithmeticException.class); + assertThat(((Exception) success.getPayload()).getMessage()).isEqualTo("/ by zero"); // propagate failing advice with success advice.setPropagateEvaluationFailures(true); @@ -269,16 +265,16 @@ public class AdvisedMessageHandlerTests { fail("Expected Exception"); } catch (MessageHandlingException e) { - assertEquals("/ by zero", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("/ by zero"); } reply = replies.receive(1); - assertNull(reply); + assertThat(reply).isNull(); success = successChannel.receive(1000); - assertNotNull(success); - assertEquals("Hello, world!", ((AdviceMessage) success).getInputMessage().getPayload()); - assertEquals(ArithmeticException.class, success.getPayload().getClass()); - assertEquals("/ by zero", ((Exception) success.getPayload()).getMessage()); + assertThat(success).isNotNull(); + assertThat(((AdviceMessage) success).getInputMessage().getPayload()).isEqualTo("Hello, world!"); + assertThat(success.getPayload().getClass()).isEqualTo(ArithmeticException.class); + assertThat(((Exception) success.getPayload()).getMessage()).isEqualTo("/ by zero"); } @@ -320,16 +316,17 @@ public class AdvisedMessageHandlerTests { fail("Expected exception"); } catch (Exception e) { - assertEquals("qux", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("qux"); } Message reply = replies.receive(1); - assertNull(reply); + assertThat(reply).isNull(); Message failure = failureChannel.receive(10000); - assertNotNull(failure); - assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload()); - assertEquals(MessageHandlingExpressionEvaluatingAdviceException.class, failure.getPayload().getClass()); - assertEquals("qux", ((Exception) failure.getPayload()).getCause().getMessage()); + assertThat(failure).isNotNull(); + assertThat(((MessagingException) failure.getPayload()).getFailedMessage().getPayload()) + .isEqualTo("Hello, world!"); + assertThat(failure.getPayload().getClass()).isEqualTo(MessageHandlingExpressionEvaluatingAdviceException.class); + assertThat(((Exception) failure.getPayload()).getCause().getMessage()).isEqualTo("qux"); // propagate failing advice with failure; expect original exception advice.setPropagateEvaluationFailures(true); @@ -338,16 +335,17 @@ public class AdvisedMessageHandlerTests { fail("Expected Exception"); } catch (MessageHandlingException e) { - assertEquals("qux", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("qux"); } reply = replies.receive(1); - assertNull(reply); + assertThat(reply).isNull(); failure = failureChannel.receive(10000); - assertNotNull(failure); - assertEquals("Hello, world!", ((MessagingException) failure.getPayload()).getFailedMessage().getPayload()); - assertEquals(MessageHandlingExpressionEvaluatingAdviceException.class, failure.getPayload().getClass()); - assertEquals("qux", ((Exception) failure.getPayload()).getCause().getMessage()); + assertThat(failure).isNotNull(); + assertThat(((MessagingException) failure.getPayload()).getFailedMessage().getPayload()) + .isEqualTo("Hello, world!"); + assertThat(failure.getPayload().getClass()).isEqualTo(MessageHandlingExpressionEvaluatingAdviceException.class); + assertThat(((Exception) failure.getPayload()).getCause().getMessage()).isEqualTo("qux"); } @@ -390,22 +388,22 @@ public class AdvisedMessageHandlerTests { fail("Expected failure"); } catch (Exception e) { - assertEquals("foo", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("foo"); } try { handler.handleMessage(message); fail("Expected failure"); } catch (Exception e) { - assertEquals("foo", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("foo"); } try { handler.handleMessage(message); fail("Expected failure"); } catch (Exception e) { - assertEquals("Circuit Breaker is Open for baz", e.getMessage()); - assertSame(message, ((MessagingException) e).getFailedMessage()); + assertThat(e.getMessage()).isEqualTo("Circuit Breaker is Open for baz"); + assertThat(((MessagingException) e).getFailedMessage()).isSameAs(message); } Map metadataMap = TestUtils.getPropertyValue(advice, "metadataMap", Map.class); @@ -421,14 +419,14 @@ public class AdvisedMessageHandlerTests { fail("Expected failure"); } catch (Exception e) { - assertEquals("foo", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("foo"); } try { handler.handleMessage(message); fail("Expected failure"); } catch (Exception e) { - assertEquals("Circuit Breaker is Open for baz", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Circuit Breaker is Open for baz"); } // Simulate some timeout in between requests @@ -442,21 +440,21 @@ public class AdvisedMessageHandlerTests { fail("Expected failure"); } catch (Exception e) { - assertEquals("foo", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("foo"); } try { handler.handleMessage(message); fail("Expected failure"); } catch (Exception e) { - assertEquals("foo", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("foo"); } try { handler.handleMessage(message); fail("Expected failure"); } catch (Exception e) { - assertEquals("Circuit Breaker is Open for baz", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("Circuit Breaker is Open for baz"); } } @@ -485,10 +483,10 @@ public class AdvisedMessageHandlerTests { Message message = new GenericMessage<>("Hello, world!"); handler.handleMessage(message); - assertTrue(counter.get() == -1); + assertThat(counter.get() == -1).isTrue(); Message reply = replies.receive(10000); - assertNotNull(reply); - assertEquals("bar", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("bar"); } @@ -523,13 +521,13 @@ public class AdvisedMessageHandlerTests { handler.handleMessage(message); } catch (Exception e) { - assertTrue(i < 2); + assertThat(i < 2).isTrue(); } } - assertTrue(counter.get() == -1); + assertThat(counter.get() == -1).isTrue(); Message reply = replies.receive(10000); - assertNotNull(reply); - assertEquals("bar", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("bar"); } @@ -597,10 +595,10 @@ public class AdvisedMessageHandlerTests { catch (Exception e) { } } - assertTrue(counter.get() == 0); + assertThat(counter.get() == 0).isTrue(); Message reply = replies.receive(10000); - assertNotNull(reply); - assertEquals("baz", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("baz"); } @Test @@ -626,8 +624,8 @@ public class AdvisedMessageHandlerTests { Message message = new GenericMessage<>("Hello, world!"); handler.handleMessage(message); Message error = errors.receive(10000); - assertNotNull(error); - assertEquals("fooException", ((Exception) error.getPayload()).getCause().getMessage()); + assertThat(error).isNotNull(); + assertThat(((Exception) error.getPayload()).getCause().getMessage()).isEqualTo("fooException"); } @@ -667,10 +665,11 @@ public class AdvisedMessageHandlerTests { Message message = new GenericMessage<>("Hello, world!"); handler.handleMessage(message); Message error = errors.receive(10000); - assertNotNull(error); - assertTrue(error.getPayload() instanceof ErrorMessageSendingRecoverer.RetryExceptionNotAvailableException); - assertNotNull(((MessagingException) error.getPayload()).getFailedMessage()); - assertSame(message, ((MessagingException) error.getPayload()).getFailedMessage()); + assertThat(error).isNotNull(); + assertThat(error.getPayload() instanceof ErrorMessageSendingRecoverer.RetryExceptionNotAvailableException) + .isTrue(); + assertThat(((MessagingException) error.getPayload()).getFailedMessage()).isNotNull(); + assertThat(((MessagingException) error.getPayload()).getFailedMessage()).isSameAs(message); } @Test @@ -702,11 +701,11 @@ public class AdvisedMessageHandlerTests { } catch (Exception e) { Throwable cause = e.getCause(); - assertEquals(RuntimeException.class, cause.getClass()); - assertEquals("intentional", cause.getMessage()); + assertThat(cause.getClass()).isEqualTo(RuntimeException.class); + assertThat(cause.getMessage()).isEqualTo("intentional"); } - assertTrue(counter.get() == 0); + assertThat(counter.get() == 0).isTrue(); } @Test @@ -752,9 +751,9 @@ public class AdvisedMessageHandlerTests { handler.handleMessage(new GenericMessage<>("test")); Message receive = replies.receive(10000); - assertNotNull(receive); - assertEquals("intentional: 3", receive.getPayload()); - assertEquals(1, outerCounter.get()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("intentional: 3"); + assertThat(outerCounter.get()).isEqualTo(1); } @@ -793,17 +792,17 @@ public class AdvisedMessageHandlerTests { handler.handleMessage(new GenericMessage<>("test")); } catch (Exception e) { - assertEquals("intentional: 3", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("intentional: 3"); } for (int i = 1; i <= 3; i++) { Message receive = errors.receive(10000); - assertNotNull(receive); - assertEquals("intentional: " + i, - ((MessageHandlingExpressionEvaluatingAdviceException) receive.getPayload()).getEvaluationResult()); + assertThat(receive).isNotNull(); + assertThat(((MessageHandlingExpressionEvaluatingAdviceException) receive.getPayload()) + .getEvaluationResult()).isEqualTo("intentional: " + i); } - assertNull(errors.receive(1)); + assertThat(errors.receive(1)).isNull(); } @@ -842,7 +841,7 @@ public class AdvisedMessageHandlerTests { fail("Expected throwable"); } catch (Throwable t) { - assertSame(theThrowable, t); + assertThat(t).isSameAs(theThrowable); } } @@ -870,10 +869,10 @@ public class AdvisedMessageHandlerTests { fail("Expected throwable"); } catch (Throwable t) { - assertSame(theThrowable, t); + assertThat(t).isSameAs(theThrowable); ErrorMessage error = (ErrorMessage) errors.receive(10000); - assertNotNull(error); - assertSame(theThrowable, error.getPayload().getCause()); + assertThat(error).isNotNull(); + assertThat(error.getPayload().getCause()).isSameAs(theThrowable); } } @@ -899,7 +898,7 @@ public class AdvisedMessageHandlerTests { consumer.start(); Callable pollingTask = TestUtils.getPropertyValue(consumer, "pollingTask", Callable.class); - assertTrue(AopUtils.isAopProxy(pollingTask)); + assertThat(AopUtils.isAopProxy(pollingTask)).isTrue(); Log logger = TestUtils.getPropertyValue(advice, "logger", Log.class); logger = spy(logger); when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE); @@ -912,11 +911,11 @@ public class AdvisedMessageHandlerTests { accessor.setPropertyValue("logger", logger); pollingTask.call(); - assertFalse(called.get()); - assertNotNull(logMessage.get()); - assertThat(logMessage.get(), Matchers.containsString("can only be used for MessageHandlers; " + + assertThat(called.get()).isFalse(); + assertThat(logMessage.get()).isNotNull(); + assertThat(logMessage.get()).contains("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in " + - "'org.springframework.integration.endpoint.AbstractPollingEndpoint")); + "'org.springframework.integration.endpoint.AbstractPollingEndpoint"); consumer.stop(); exec.shutdownNow(); } @@ -926,7 +925,7 @@ public class AdvisedMessageHandlerTests { QueueChannel discardChannel = new QueueChannel(); filter.setDiscardChannel(discardChannel); filter.handleMessage(new GenericMessage<>("foo")); - assertNotNull(discardChannel.receive(0)); + assertThat(discardChannel.receive(0)).isNotNull(); } @Test @@ -949,8 +948,8 @@ public class AdvisedMessageHandlerTests { filter.setBeanFactory(mock(BeanFactory.class)); filter.afterPropertiesSet(); filter.handleMessage(new GenericMessage<>("foo")); - assertNotNull(discardedWithinAdvice.get()); - assertNull(discardChannel.receive(0)); + assertThat(discardedWithinAdvice.get()).isNotNull(); + assertThat(discardChannel.receive(0)).isNull(); } @Test @@ -976,9 +975,9 @@ public class AdvisedMessageHandlerTests { filter.setBeanFactory(mock(BeanFactory.class)); filter.afterPropertiesSet(); filter.handleMessage(new GenericMessage<>("foo")); - assertTrue(adviceCalled.get()); - assertNull(discardedWithinAdvice.get()); - assertNotNull(discardChannel.receive(0)); + assertThat(adviceCalled.get()).isTrue(); + assertThat(discardedWithinAdvice.get()).isNull(); + assertThat(discardChannel.receive(0)).isNotNull(); } @Test @@ -1034,11 +1033,11 @@ public class AdvisedMessageHandlerTests { fail("MessagingException expected."); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(MessagingException.class)); - assertThat(e.getCause(), Matchers.instanceOf(MyException.class)); + assertThat(e).isInstanceOf(MessagingException.class); + assertThat(e.getCause()).isInstanceOf(MyException.class); } - assertEquals(expected, counter.get()); + assertThat(counter.get()).isEqualTo(expected); } @Test @@ -1047,13 +1046,13 @@ public class AdvisedMessageHandlerTests { ErrorMessageSendingRecoverer recoverer = new ErrorMessageSendingRecoverer(channel); recoverer.publish(new GenericMessage<>("foo"), new GenericMessage<>("bar"), new RuntimeException("baz")); Message error = channel.receive(0); - assertThat(error, instanceOf(ErrorMessage.class)); - assertThat(error.getPayload(), instanceOf(MessagingException.class)); + assertThat(error).isInstanceOf(ErrorMessage.class); + assertThat(error.getPayload()).isInstanceOf(MessagingException.class); MessagingException payload = (MessagingException) error.getPayload(); - assertThat(payload.getCause(), instanceOf(RuntimeException.class)); - assertThat(payload.getCause().getMessage(), equalTo("baz")); - assertThat(payload.getFailedMessage().getPayload(), equalTo("bar")); - assertThat(((ErrorMessage) error).getOriginalMessage().getPayload(), equalTo("foo")); + assertThat(payload.getCause()).isInstanceOf(RuntimeException.class); + assertThat(payload.getCause().getMessage()).isEqualTo("baz"); + assertThat(payload.getFailedMessage().getPayload()).isEqualTo("bar"); + assertThat(((ErrorMessage) error).getOriginalMessage().getPayload()).isEqualTo("foo"); } private interface Bar { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/ExpressionEvaluatingRequestHandlerAdviceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/ExpressionEvaluatingRequestHandlerAdviceTests.java index f59fc01845..d9b09aeb3a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/ExpressionEvaluatingRequestHandlerAdviceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/ExpressionEvaluatingRequestHandlerAdviceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,10 +16,7 @@ package org.springframework.integration.handler.advice; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.aopalliance.aop.Advice; import org.junit.Test; @@ -59,12 +56,12 @@ public class ExpressionEvaluatingRequestHandlerAdviceTests { public void test() { this.in.send(new GenericMessage<>("good")); this.in.send(new GenericMessage<>("junk")); - assertThat(config.successful, instanceOf(AdviceMessage.class)); - assertThat(config.successful.getPayload(), equalTo("good was successful")); - assertThat(config.failed, instanceOf(ErrorMessage.class)); + assertThat(config.successful).isInstanceOf(AdviceMessage.class); + assertThat(config.successful.getPayload()).isEqualTo("good was successful"); + assertThat(config.failed).isInstanceOf(ErrorMessage.class); Object evaluationResult = ((MessageHandlingExpressionEvaluatingAdviceException) config.failed.getPayload()) .getEvaluationResult(); - assertThat((String) evaluationResult, startsWith("junk was bad, with reason:")); + assertThat((String) evaluationResult).startsWith("junk was bad, with reason:"); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java index 1d7267c71c..56bbcf8a62 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/IdempotentReceiverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2019 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,12 +16,8 @@ package org.springframework.integration.handler.advice; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -101,22 +97,22 @@ public class IdempotentReceiverTests { idempotentReceiver = (MessageHandler) proxyFactory.getProxy(); idempotentReceiver.handleMessage(new GenericMessage<>("foo")); - assertEquals(1, TestUtils.getPropertyValue(store, "metadata", Map.class).size()); - assertNotNull(store.get("foo")); + assertThat(TestUtils.getPropertyValue(store, "metadata", Map.class).size()).isEqualTo(1); + assertThat(store.get("foo")).isNotNull(); try { idempotentReceiver.handleMessage(new GenericMessage<>("foo")); fail("MessageRejectedException expected"); } catch (Exception e) { - assertThat(e, instanceOf(MessageRejectedException.class)); + assertThat(e).isInstanceOf(MessageRejectedException.class); } idempotentReceiverInterceptor.setThrowExceptionOnRejection(false); idempotentReceiver.handleMessage(new GenericMessage<>("foo")); - assertTrue(handled.get().getHeaders().get(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE, - Boolean.class)); - assertEquals(1, TestUtils.getPropertyValue(store, "metadata", Map.class).size()); + assertThat(handled.get().getHeaders().get(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE, + Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(store, "metadata", Map.class).size()).isEqualTo(1); } @Test @@ -124,38 +120,40 @@ public class IdempotentReceiverTests { Message message = new GenericMessage<>("foo"); this.input.send(message); Message receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(1, this.fooAdvice.adviceCalled); - assertEquals(1, TestUtils.getPropertyValue(this.store, "metadata", Map.class).size()); - assertNotNull(this.store.get("foo")); + assertThat(receive).isNotNull(); + assertThat(this.fooAdvice.adviceCalled).isEqualTo(1); + assertThat(TestUtils.getPropertyValue(this.store, "metadata", Map.class).size()).isEqualTo(1); + assertThat(this.store.get("foo")).isNotNull(); try { this.input.send(message); fail("MessageRejectedException expected"); } catch (Exception e) { - assertThat(e, instanceOf(MessageRejectedException.class)); + assertThat(e).isInstanceOf(MessageRejectedException.class); } this.idempotentReceiverInterceptor.setThrowExceptionOnRejection(false); this.input.send(message); receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(2, this.fooAdvice.adviceCalled); - assertTrue(receive.getHeaders().get(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE, Boolean.class)); - assertEquals(1, TestUtils.getPropertyValue(this.store, "metadata", Map.class).size()); + assertThat(receive).isNotNull(); + assertThat(this.fooAdvice.adviceCalled).isEqualTo(2); + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE, Boolean.class)) + .isTrue(); + assertThat(TestUtils.getPropertyValue(this.store, "metadata", Map.class).size()).isEqualTo(1); message = new GenericMessage<>("bar"); for (int i = 0; i < 2; i++) { this.input2.send(message); receive = this.output.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); } - assertTrue(receive.getHeaders().get(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE, Boolean.class)); - assertEquals(2, TestUtils.getPropertyValue(this.store, "metadata", Map.class).size()); - assertNotNull(this.store.get("bar")); - assertEquals(1, TestUtils.getPropertyValue(this.store2, "metadata", Map.class).size()); - assertNotNull(this.store2.get("BAR")); + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.DUPLICATE_MESSAGE, Boolean.class)) + .isTrue(); + assertThat(TestUtils.getPropertyValue(this.store, "metadata", Map.class).size()).isEqualTo(2); + assertThat(this.store.get("bar")).isNotNull(); + assertThat(TestUtils.getPropertyValue(this.store2, "metadata", Map.class).size()).isEqualTo(1); + assertThat(this.store2.get("BAR")).isNotNull(); } public static class FooAdvice extends AbstractRequestHandlerAdvice { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests.java index 798f9a4913..2fe05913c0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/SpelExpressionRetryStateGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.handler.advice; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,17 +55,17 @@ public class SpelExpressionRetryStateGeneratorTests { SpelExpressionRetryStateGenerator generator = new SpelExpressionRetryStateGenerator("headers['foo']"); RetryState state = generator.determineRetryState(message); - assertEquals("bar", state.getKey()); - assertFalse(state.isForceRefresh()); - assertTrue(state.rollbackFor(new RuntimeException())); + assertThat(state.getKey()).isEqualTo("bar"); + assertThat(state.isForceRefresh()).isFalse(); + assertThat(state.rollbackFor(new RuntimeException())).isTrue(); } @Test public void testBasicConfig() { RetryState state = configGenerator.determineRetryState(message); - assertEquals("bar", state.getKey()); - assertFalse(state.isForceRefresh()); - assertTrue(state.rollbackFor(new RuntimeException())); + assertThat(state.getKey()).isEqualTo("bar"); + assertThat(state.isForceRefresh()).isFalse(); + assertThat(state.rollbackFor(new RuntimeException())).isTrue(); } @Test @@ -75,9 +73,9 @@ public class SpelExpressionRetryStateGeneratorTests { SpelExpressionRetryStateGenerator generator = new SpelExpressionRetryStateGenerator("headers['foo']", "headers['trueHeader']"); RetryState state = generator.determineRetryState(message); - assertEquals("bar", state.getKey()); - assertTrue(state.isForceRefresh()); - assertTrue(state.rollbackFor(new RuntimeException())); + assertThat(state.getKey()).isEqualTo("bar"); + assertThat(state.isForceRefresh()).isTrue(); + assertThat(state.rollbackFor(new RuntimeException())).isTrue(); } @Test @@ -85,9 +83,9 @@ public class SpelExpressionRetryStateGeneratorTests { SpelExpressionRetryStateGenerator generator = new SpelExpressionRetryStateGenerator("headers['foo']", "headers['falseHeader']"); RetryState state = generator.determineRetryState(message); - assertEquals("bar", state.getKey()); - assertFalse(state.isForceRefresh()); - assertTrue(state.rollbackFor(new RuntimeException())); + assertThat(state.getKey()).isEqualTo("bar"); + assertThat(state.isForceRefresh()).isFalse(); + assertThat(state.rollbackFor(new RuntimeException())).isTrue(); } @Test @@ -95,9 +93,9 @@ public class SpelExpressionRetryStateGeneratorTests { SpelExpressionRetryStateGenerator generator = new SpelExpressionRetryStateGenerator("headers['foo']", "headers['noHeader']?:true"); RetryState state = generator.determineRetryState(message); - assertEquals("bar", state.getKey()); - assertTrue(state.isForceRefresh()); - assertTrue(state.rollbackFor(new RuntimeException())); + assertThat(state.getKey()).isEqualTo("bar"); + assertThat(state.isForceRefresh()).isTrue(); + assertThat(state.rollbackFor(new RuntimeException())).isTrue(); } @Test @@ -106,9 +104,9 @@ public class SpelExpressionRetryStateGeneratorTests { new SpelExpressionRetryStateGenerator("headers['foo']"); generator.setClassifier(new ClassifierSupport<>(false)); RetryState state = generator.determineRetryState(message); - assertEquals("bar", state.getKey()); - assertFalse(state.isForceRefresh()); - assertFalse(state.rollbackFor(new RuntimeException())); + assertThat(state.getKey()).isEqualTo("bar"); + assertThat(state.isForceRefresh()).isFalse(); + assertThat(state.rollbackFor(new RuntimeException())).isFalse(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedTests.java b/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedTests.java index 8de80ad379..94ebf37649 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.history; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -54,8 +54,8 @@ public class AnnotatedTests { public void onApplicationEvent(ApplicationEvent event) { MessageHistory history = MessageHistory.read((Message) event.getSource()); Properties adapterHistory = history.get(1); - assertEquals("myAdapter", adapterHistory.get("name")); - assertEquals("outbound-channel-adapter", adapterHistory.get("type")); + assertThat(adapterHistory.get("name")).isEqualTo("myAdapter"); + assertThat(adapterHistory.get("type")).isEqualTo("outbound-channel-adapter"); } }; listener = spy(listener); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java index f1b5cf1df2..f2ebfdb891 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.history; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Iterator; import java.util.Map; @@ -61,8 +57,8 @@ public class MessageHistoryIntegrationTests { for (ConsumerEndpointFactoryBean cefBean : cefBeans.values()) { DirectFieldAccessor bridgeAccessor = new DirectFieldAccessor(cefBean); String handlerClassName = bridgeAccessor.getPropertyValue("handler").getClass().getName(); - assertFalse("org.springframework.integration.config.MessageHistoryWritingMessageHandler" - .equals(handlerClassName)); + assertThat("org.springframework.integration.config.MessageHistoryWritingMessageHandler" + .equals(handlerClassName)).isFalse(); } ac.close(); } @@ -81,65 +77,66 @@ public class MessageHistoryIntegrationTests { .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator(); Properties event = historyIterator.next(); - assertEquals("sampleGateway", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("gateway", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("sampleGateway"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("gateway"); event = historyIterator.next(); - assertEquals("bridgeInChannel", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("bridgeInChannel"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("channel"); event = historyIterator.next(); - assertEquals("testBridge", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("bridge", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("testBridge"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("bridge"); event = historyIterator.next(); - assertEquals("headerEnricherChannel", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("headerEnricherChannel"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("channel"); event = historyIterator.next(); - assertEquals("testHeaderEnricher", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("header-enricher", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("testHeaderEnricher"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("header-enricher"); event = historyIterator.next(); - assertEquals("chainChannel", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("chainChannel"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("channel"); event = historyIterator.next(); - assertEquals("sampleChain", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("chain", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("sampleChain"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("chain"); event = historyIterator.next(); - assertEquals("sampleChain$child.service-activator-within-chain", event - .getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("service-activator", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event + .getProperty(MessageHistory.NAME_PROPERTY)) + .isEqualTo("sampleChain$child.service-activator-within-chain"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("service-activator"); event = historyIterator.next(); - assertEquals("filterChannel", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("filterChannel"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("channel"); event = historyIterator.next(); - assertEquals("testFilter", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("filter", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("testFilter"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("filter"); event = historyIterator.next(); - assertEquals("splitterChannel", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("splitterChannel"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("channel"); event = historyIterator.next(); - assertEquals("testSplitter", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("splitter", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("testSplitter"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("splitter"); event = historyIterator.next(); - assertEquals("aggregatorChannel", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("aggregatorChannel"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("channel"); event = historyIterator.next(); - assertEquals("testAggregator", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("aggregator", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("testAggregator"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("aggregator"); event = historyIterator.next(); - assertEquals("endOfThePipeChannel", event.getProperty(MessageHistory.NAME_PROPERTY)); - assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY)); + assertThat(event.getProperty(MessageHistory.NAME_PROPERTY)).isEqualTo("endOfThePipeChannel"); + assertThat(event.getProperty(MessageHistory.TYPE_PROPERTY)).isEqualTo("channel"); MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); replyChannel.send(message); @@ -148,7 +145,7 @@ public class MessageHistoryIntegrationTests { endOfThePipeChannel.subscribe(handler); Message result = gateway.echo("hello"); Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class)); - assertNotNull(result); + assertThat(result).isNotNull(); //assertEquals("hello", result); ac.close(); } @@ -163,7 +160,7 @@ public class MessageHistoryIntegrationTests { @Override public void handleMessage(Message message) { - assertNull(message.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class)); + assertThat(message.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class)).isNull(); MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); replyChannel.send(message); } @@ -186,7 +183,7 @@ public class MessageHistoryIntegrationTests { public void handleMessage(Message message) { Iterator historyIterator = message.getHeaders() .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator(); - assertTrue(historyIterator.hasNext()); + assertThat(historyIterator.hasNext()).isTrue(); MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); replyChannel.send(message); } @@ -209,13 +206,13 @@ public class MessageHistoryIntegrationTests { public void handleMessage(Message message) { Iterator historyIterator = message.getHeaders() .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator(); - assertTrue(historyIterator.hasNext()); + assertThat(historyIterator.hasNext()).isTrue(); Properties gatewayHistory = historyIterator.next(); - assertEquals("sampleGateway", gatewayHistory.get("name")); - assertTrue(historyIterator.hasNext()); + assertThat(gatewayHistory.get("name")).isEqualTo("sampleGateway"); + assertThat(historyIterator.hasNext()).isTrue(); Properties chainHistory = historyIterator.next(); - assertEquals("sampleChain", chainHistory.get("name")); - assertFalse(historyIterator.hasNext()); + assertThat(chainHistory.get("name")).isEqualTo("sampleChain"); + assertThat(historyIterator.hasNext()).isFalse(); MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); replyChannel.send(message); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonInboundMessageMapperTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonInboundMessageMapperTests.java index a93217508e..99c16d0b0d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonInboundMessageMapperTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonInboundMessageMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.lang.reflect.Type; import java.util.Arrays; @@ -27,17 +26,15 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import org.hamcrest.Factory; -import org.hamcrest.Matcher; import org.junit.Test; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.integration.message.MessageMatcher; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.json.JsonInboundMessageMapper; import org.springframework.integration.support.json.JsonInboundMessageMapper.JsonMessageParser; import org.springframework.integration.support.json.JsonObjectMapper; import org.springframework.integration.support.json.JsonObjectMapperProvider; +import org.springframework.integration.test.predicate.MessagePredicate; import org.springframework.messaging.Message; /** @@ -51,12 +48,6 @@ public abstract class AbstractJsonInboundMessageMapperTests { private final JsonObjectMapper mapper = JsonObjectMapperProvider.newInstance(); - @Factory - public static Matcher> sameExceptImmutableHeaders(Message operand) { - return new MessageMatcher(operand); - } - - @Test public void testToMessageWithHeadersAndStringPayload() throws Exception { UUID id = UUID.randomUUID(); @@ -68,7 +59,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { .build(); JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(String.class, getParser()); Message result = mapper.toMessage(jsonMessage); - assertThat(result, sameExceptImmutableHeaders(expected)); + assertThat(result).matches(new MessagePredicate(expected)); } @Test @@ -78,7 +69,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(String.class, getParser()); mapper.setMapToPayload(true); Message result = mapper.toMessage(jsonMessage); - assertEquals(expected, result.getPayload()); + assertThat(result.getPayload()).isEqualTo(expected); } @Test @@ -93,7 +84,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { .build(); JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(TestBean.class, getParser()); Message result = mapper.toMessage(jsonMessage); - assertThat(result, sameExceptImmutableHeaders(expected)); + assertThat(result).matches(new MessagePredicate(expected)); } @Test @@ -103,7 +94,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(TestBean.class, getParser()); mapper.setMapToPayload(true); Message result = mapper.toMessage(jsonMessage); - assertEquals(expected, result.getPayload()); + assertThat(result.getPayload()).isEqualTo(expected); } @Test @@ -116,11 +107,11 @@ public abstract class AbstractJsonInboundMessageMapperTests { .setHeader("myHeader", bean) .build(); JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(String.class, getParser()); - Map> headerTypes = new HashMap>(); + Map> headerTypes = new HashMap<>(); headerTypes.put("myHeader", TestBean.class); mapper.setHeaderTypes(headerTypes); Message result = mapper.toMessage(jsonMessage); - assertThat(result, sameExceptImmutableHeaders(expected)); + assertThat(result).matches(new MessagePredicate(expected)); } @Test @@ -139,7 +130,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { }.getType(); JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(type, getParser()); Message result = mapper.toMessage(jsonMessage); - assertThat(result, sameExceptImmutableHeaders(expected)); + assertThat(result).matches(new MessagePredicate(expected)); } @Test @@ -160,7 +151,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { }.getType(); JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(type, getParser()); Message result = mapper.toMessage(jsonMessage); - assertThat(result, sameExceptImmutableHeaders(expected)); + assertThat(result).matches(new MessagePredicate(expected)); } @Test @@ -174,7 +165,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { .build(); JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(String.class, getParser()); Message result = mapper.toMessage(jsonMessage); - assertThat(result, sameExceptImmutableHeaders(expected)); + assertThat(result).matches(new MessagePredicate(expected)); } @Test @@ -183,7 +174,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(String.class, getParser()); try { mapper.toMessage(jsonMessage); - fail(); + fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { //Expected @@ -197,7 +188,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(String.class, getParser()); try { mapper.toMessage(jsonMessage); - fail(); + fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { //Expected @@ -212,7 +203,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { mapper.setMapToPayload(true); try { mapper.toMessage(jsonMessage); - fail(); + fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { //Expected @@ -228,7 +219,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(TestBean.class, getParser()); mapper.setMapToPayload(true); Message message = mapper.toMessage(jsonMessage); - assertEquals(bean, message.getPayload()); + assertThat(message.getPayload()).isEqualTo(bean); } @Test @@ -240,7 +231,7 @@ public abstract class AbstractJsonInboundMessageMapperTests { JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(Long.class, getParser()); try { mapper.toMessage(jsonMessage); - fail(); + fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { //Expected @@ -254,12 +245,12 @@ public abstract class AbstractJsonInboundMessageMapperTests { String jsonMessage = "{\"headers\":{\"$timestamp\":1,\"$id\":\"" + id + "\",\"myHeader\":" + getBeanAsJson(bean) + "},\"payload\":\"myPayloadStuff\"}"; JsonInboundMessageMapper mapper = new JsonInboundMessageMapper(String.class, getParser()); - Map> headerTypes = new HashMap>(); + Map> headerTypes = new HashMap<>(); headerTypes.put("myHeader", Long.class); mapper.setHeaderTypes(headerTypes); try { mapper.toMessage(jsonMessage); - fail(); + fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { //Expected diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java index 4b9806f8d1..9bfe2a93a0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,33 +16,27 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; -import org.hamcrest.Factory; -import org.hamcrest.Matcher; import org.junit.Test; import org.springframework.integration.history.MessageHistory; -import org.springframework.integration.message.MessageMatcher; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.context.NamedComponent; import org.springframework.integration.support.json.JsonInboundMessageMapper; import org.springframework.integration.support.json.JsonInboundMessageMapper.JsonMessageParser; import org.springframework.integration.support.json.JsonOutboundMessageMapper; +import org.springframework.integration.test.predicate.MessagePredicate; import org.springframework.messaging.Message; /** * @author Jeremy Grelle * @author Gary Russell + * @author Artem Bilan */ public abstract class AbstractJsonSymmetricalMessageMappingTests { - @Factory - public static Matcher> sameExceptImmutableHeaders(Message operand) { - return new MessageMatcher(operand); - } - @Test public void testSymmetricalMappingWithHistory() throws Exception { Message testMessage = MessageBuilder.withPayload("myPayloadStuff").build(); @@ -56,7 +50,7 @@ public abstract class AbstractJsonSymmetricalMessageMappingTests { JsonInboundMessageMapper inboundMapper = new JsonInboundMessageMapper(String.class, getParser()); Message result = inboundMapper.toMessage(outboundJson); - assertThat(result, sameExceptImmutableHeaders(testMessage)); + assertThat(result).matches(new MessagePredicate(testMessage)); } protected abstract JsonMessageParser getParser(); @@ -80,4 +74,5 @@ public abstract class AbstractJsonSymmetricalMessageMappingTests { } } + } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/ContentTypeConversionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/ContentTypeConversionTests.java index 0bce64fabe..d4b61f9684 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/ContentTypeConversionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/ContentTypeConversionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Map; @@ -63,13 +63,13 @@ public class ContentTypeConversionTests { String json = "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":42}"; TestPerson testPerson = this.serviceGateway.convertJsonToPerson(json); - assertEquals(json, this.sendData.get()); - assertEquals("John", testPerson.getFirstName()); - assertEquals(42, testPerson.getAge()); + assertThat(this.sendData.get()).isEqualTo(json); + assertThat(testPerson.getFirstName()).isEqualTo("John"); + assertThat(testPerson.getAge()).isEqualTo(42); Map map = Collections.singletonMap("foo", "bar"); String result = this.serviceGateway.mapToString(map); - assertEquals(map.toString(), result); + assertThat(result).isEqualTo(map.toString()); } @MessagingGateway diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonInboundMessageMapperTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonInboundMessageMapperTests.java index cc8cf50125..9726889cd9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonInboundMessageMapperTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonInboundMessageMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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. diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonSymmetricalMessageMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonSymmetricalMessageMappingTests.java index 8572eb7e26..4e3b1baaf0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonSymmetricalMessageMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/Jackson2JsonSymmetricalMessageMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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. diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java index 66d82804de..2a0125ff66 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; @@ -51,10 +50,10 @@ public class JsonOutboundMessageMapperTests { Message testMessage = MessageBuilder.withPayload("myPayloadStuff").build(); JsonOutboundMessageMapper mapper = new JsonOutboundMessageMapper(); String result = mapper.fromMessage(testMessage); - assertTrue(result.contains("\"headers\":{")); - assertTrue(result.contains("\"timestamp\":" + testMessage.getHeaders().getTimestamp())); - assertTrue(result.contains("\"id\":\"" + testMessage.getHeaders().getId() + "\"")); - assertTrue(result.contains("\"payload\":\"myPayloadStuff\"")); + assertThat(result.contains("\"headers\":{")).isTrue(); + assertThat(result.contains("\"timestamp\":" + testMessage.getHeaders().getTimestamp())).isTrue(); + assertThat(result.contains("\"id\":\"" + testMessage.getHeaders().getId() + "\"")).isTrue(); + assertThat(result.contains("\"payload\":\"myPayloadStuff\"")).isTrue(); } @Test @@ -65,17 +64,17 @@ public class JsonOutboundMessageMapperTests { testMessage = MessageHistory.write(testMessage, new TestNamedComponent(3)); JsonOutboundMessageMapper mapper = new JsonOutboundMessageMapper(); String result = mapper.fromMessage(testMessage); - assertTrue(result.contains("\"headers\":{")); - assertTrue(result.contains("\"timestamp\":" + testMessage.getHeaders().getTimestamp())); - assertTrue(result.contains("\"id\":\"" + testMessage.getHeaders().getId() + "\"")); - assertTrue(result.contains("\"payload\":\"myPayloadStuff\"")); - assertTrue(result.contains("\"history\":")); - assertTrue(result.contains("testName-1")); - assertTrue(result.contains("testType-1")); - assertTrue(result.contains("testName-2")); - assertTrue(result.contains("testType-2")); - assertTrue(result.contains("testName-3")); - assertTrue(result.contains("testType-3")); + assertThat(result.contains("\"headers\":{")).isTrue(); + assertThat(result.contains("\"timestamp\":" + testMessage.getHeaders().getTimestamp())).isTrue(); + assertThat(result.contains("\"id\":\"" + testMessage.getHeaders().getId() + "\"")).isTrue(); + assertThat(result.contains("\"payload\":\"myPayloadStuff\"")).isTrue(); + assertThat(result.contains("\"history\":")).isTrue(); + assertThat(result.contains("testName-1")).isTrue(); + assertThat(result.contains("testType-1")).isTrue(); + assertThat(result.contains("testName-2")).isTrue(); + assertThat(result.contains("testType-2")).isTrue(); + assertThat(result.contains("testName-3")).isTrue(); + assertThat(result.contains("testType-3")).isTrue(); } @Test @@ -85,7 +84,7 @@ public class JsonOutboundMessageMapperTests { JsonOutboundMessageMapper mapper = new JsonOutboundMessageMapper(); mapper.setShouldExtractPayload(true); String result = mapper.fromMessage(testMessage); - assertEquals(expected, result); + assertThat(result).isEqualTo(expected); } @Test @@ -94,11 +93,11 @@ public class JsonOutboundMessageMapperTests { Message testMessage = MessageBuilder.withPayload(payload).build(); JsonOutboundMessageMapper mapper = new JsonOutboundMessageMapper(); String result = mapper.fromMessage(testMessage); - assertTrue(result.contains("\"headers\":{")); - assertTrue(result.contains("\"timestamp\":" + testMessage.getHeaders().getTimestamp())); - assertTrue(result.contains("\"id\":\"" + testMessage.getHeaders().getId() + "\"")); + assertThat(result.contains("\"headers\":{")).isTrue(); + assertThat(result.contains("\"timestamp\":" + testMessage.getHeaders().getTimestamp())).isTrue(); + assertThat(result.contains("\"id\":\"" + testMessage.getHeaders().getId() + "\"")).isTrue(); TestBean parsedPayload = extractJsonPayloadToTestBean(result); - assertEquals(payload, parsedPayload); + assertThat(parsedPayload).isEqualTo(payload); } @Test @@ -108,9 +107,9 @@ public class JsonOutboundMessageMapperTests { JsonOutboundMessageMapper mapper = new JsonOutboundMessageMapper(); mapper.setShouldExtractPayload(true); String result = mapper.fromMessage(testMessage); - assertTrue(!result.contains("headers")); + assertThat(!result.contains("headers")).isTrue(); TestBean parsedPayload = objectMapper.readValue(result, TestBean.class); - assertEquals(payload, parsedPayload); + assertThat(parsedPayload).isEqualTo(payload); } private TestBean extractJsonPayloadToTestBean(String json) throws IOException { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java index 88dfdafbe0..75ce57e2e4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 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,19 +16,14 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Scanner; -import org.hamcrest.Matchers; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; @@ -126,19 +121,19 @@ public class JsonPathTests { public void testInt3139JsonPathTransformer() throws IOException { this.transformerInput.send(testMessage); Message receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals("Nigel Rees", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("Nigel Rees"); this.transformerInput.send(new GenericMessage<>(JSON.getBytes())); receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals("Nigel Rees", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("Nigel Rees"); this.transformerInput.send(new GenericMessage(JSON_FILE)); receive = this.output.receive(1000); - assertNotNull(receive); + assertThat(receive).isNotNull(); - assertEquals("Nigel Rees", receive.getPayload()); + assertThat(receive.getPayload()).isEqualTo("Nigel Rees"); try { this.transformerInput.send(new GenericMessage(new Object())); fail("IllegalArgumentException expected"); @@ -146,7 +141,7 @@ public class JsonPathTests { catch (Exception e) { //MessageTransformationException / MessageHandlingException / InvocationTargetException / IllegalArgumentException Throwable cause = e.getCause().getCause().getCause(); - assertTrue(cause instanceof PathNotFoundException); + assertThat(cause instanceof PathNotFoundException).isTrue(); } } @@ -154,36 +149,36 @@ public class JsonPathTests { public void testInt3139JsonPathFilter() { this.filterInput1.send(testMessage); Message receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(JSON, receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(JSON); this.filterInput2.send(testMessage); receive = this.output.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); Message message = MessageBuilder.withPayload(JSON) .setHeader("price", 10) .build(); this.filterInput3.send(message); receive = this.output.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); this.filterInput4.send(testMessage); receive = this.output.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); try { this.filterInput1.send(new GenericMessage("{foo:{}}")); fail("MessageRejectedException is expected."); } catch (Exception e) { - assertThat(e, Matchers.instanceOf(MessageRejectedException.class)); + assertThat(e).isInstanceOf(MessageRejectedException.class); } receive = this.output.receive(0); - assertNull(receive); + assertThat(receive).isNull(); receive = this.discardChannel.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); } @@ -192,8 +187,8 @@ public class JsonPathTests { this.splitterInput.send(testMessage); for (int i = 0; i < 4; i++) { Message receive = this.splitterOutput.receive(10000); - assertNotNull(receive); - assertTrue(receive.getPayload() instanceof Map); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload() instanceof Map).isTrue(); } } @@ -204,18 +199,18 @@ public class JsonPathTests { .build(); this.routerInput.send(message); Message receive = this.routerOutput1.receive(10000); - assertNotNull(receive); - assertEquals(JSON, receive.getPayload()); - assertNull(this.routerOutput2.receive(10)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(JSON); + assertThat(this.routerOutput2.receive(10)).isNull(); message = MessageBuilder.withPayload(JSON) .setHeader("jsonPath", "$.store.book[2].category") .build(); this.routerInput.send(message); receive = this.routerOutput2.receive(10000); - assertNotNull(receive); - assertEquals(JSON, receive.getPayload()); - assertNull(this.routerOutput1.receive(10)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo(JSON); + assertThat(this.routerOutput1.receive(10)).isNull(); } @Autowired @@ -233,14 +228,15 @@ public class JsonPathTests { Message receive = replyChannel.receive(10_000); - assertNotNull(receive); - assertEquals("Nigel Rees", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("Nigel Rees"); } @Test public void testJsonInByteArray() throws Exception { byte[] json = "{\"foo\":\"bar\"}".getBytes(); - assertEquals("bar", JsonPathUtils.evaluate(json, "$.foo")); + Object result = JsonPathUtils.evaluate(json, "$.foo"); + assertThat(result).isEqualTo("bar"); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPropertyAccessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPropertyAccessorTests.java index 9e3a858376..05b67b3c8d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPropertyAccessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPropertyAccessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 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,14 +16,10 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; @@ -61,13 +57,13 @@ public class JsonPropertyAccessorTests { public void testSimpleLookup() throws Exception { Object json = mapper.readTree("{\"foo\": \"bar\"}"); Object value = evaluate(json, "foo", Object.class); - assertThat(value, Matchers.instanceOf(JsonPropertyAccessor.ToStringFriendlyJsonNode.class)); - assertEquals("bar", value.toString()); + assertThat(value).isInstanceOf(JsonPropertyAccessor.ToStringFriendlyJsonNode.class); + assertThat(value.toString()).isEqualTo("bar"); Object json2 = mapper.readTree("{\"foo\": \"bar\"}"); Object value2 = evaluate(json2, "foo", Object.class); - assertThat(value2, Matchers.instanceOf(JsonPropertyAccessor.ToStringFriendlyJsonNode.class)); - assertTrue(value.equals(value2)); - assertEquals(value.hashCode(), value2.hashCode()); + assertThat(value2).isInstanceOf(JsonPropertyAccessor.ToStringFriendlyJsonNode.class); + assertThat(value.equals(value2)).isTrue(); + assertThat(value2.hashCode()).isEqualTo(value.hashCode()); } @Test(expected = SpelEvaluationException.class) @@ -88,13 +84,13 @@ public class JsonPropertyAccessorTests { // JsonNode actual = evaluate("1", json, JsonNode.class); // Does not work // Have to wrap the root array because ArrayNode itself is not a container Object actual = evaluate(JsonPropertyAccessor.wrap(json), "[1]", Object.class); - assertEquals("4", actual.toString()); + assertThat(actual.toString()).isEqualTo("4"); } @Test public void testArrayNegativeIndex() throws Exception { JsonNode json = mapper.readTree("{\"foo\":[3, 4, 5]}"); - assertNull(evaluate(json, "foo[-1]", Object.class)); + assertThat(evaluate(json, "foo[-1]", Object.class)).isNull(); } @Test(expected = SpelEvaluationException.class) @@ -108,7 +104,7 @@ public class JsonPropertyAccessorTests { Object json = mapper.readTree("[3, 4, 5]"); // JsonNode actual = evaluate("'1'", json, JsonNode.class); // Does not work Object actual = evaluate(json, "['1']", Object.class); - assertEquals("4", actual.toString()); + assertThat(actual.toString()).isEqualTo("4"); } @Test @@ -116,7 +112,7 @@ public class JsonPropertyAccessorTests { ArrayNode json = (ArrayNode) mapper.readTree("[[3], [4, 5], []]"); // JsonNode actual = evaluate("1.1", json, JsonNode.class); // Does not work Object actual = evaluate(JsonPropertyAccessor.wrap(json), "[1][1]", Object.class); - assertEquals("5", actual.toString()); + assertThat(actual.toString()).isEqualTo("5"); } @Test @@ -124,7 +120,7 @@ public class JsonPropertyAccessorTests { Object json = mapper.readTree("[[3], [4, 5], []]"); // JsonNode actual = evaluate("1.1", json, JsonNode.class); // Does not work Object actual = evaluate(json, "['1']['1']", Object.class); - assertEquals("5", actual.toString()); + assertThat(actual.toString()).isEqualTo("5"); } @Test @@ -134,10 +130,10 @@ public class JsonPropertyAccessorTests { // Filter the bar array to return only the fizz value of each element (to prove that SPeL considers bar // an array/list) List actualArray = evaluate(json, "foo.bar.![fizz]", List.class); - assertEquals("Array size", 3, actualArray.size()); - assertEquals("[0]", "5", evaluate(actualArray, "[0]", Object.class).toString()); - assertEquals("[1]", "7", evaluate(actualArray, "[1]", Object.class).toString()); - assertEquals("[2]", "8", evaluate(actualArray, "[2]", Object.class).toString()); + assertThat(actualArray.size()).as("Array size").isEqualTo(3); + assertThat(evaluate(actualArray, "[0]", Object.class).toString()).as("[0]").isEqualTo("5"); + assertThat(evaluate(actualArray, "[1]", Object.class).toString()).as("[1]").isEqualTo("7"); + assertThat(evaluate(actualArray, "[2]", Object.class).toString()).as("[2]").isEqualTo("8"); } @Test @@ -146,21 +142,21 @@ public class JsonPropertyAccessorTests { "{\"foo\": {\"bar\": [ { \"fizz\": 5, \"buzz\": 6 }, {\"fizz\": 7}, {\"fizz\": 8} ] } }"); // Filter bar objects so that none match List actualArray = evaluate(json, "foo.bar.?[fizz=='0']", List.class); - assertEquals(0, actualArray.size()); + assertThat(actualArray.size()).isEqualTo(0); } @Test public void testNestedHashConstruct() throws Exception { Object json = mapper.readTree("{\"foo\": {\"bar\": 4, \"fizz\": 5} }"); Object actual = evaluate(json, "foo.fizz", Object.class); - assertEquals("5", actual.toString()); + assertThat(actual.toString()).isEqualTo("5"); } @Test public void testImplicitStringConversion() throws Exception { String json = "{\"foo\": {\"bar\": 4, \"fizz\": 5} }"; Object actual = evaluate(json, "foo.fizz", Object.class); - assertEquals("5", actual.toString()); + assertThat(actual.toString()).isEqualTo("5"); } @Test(expected = SpelEvaluationException.class) @@ -180,11 +176,11 @@ public class JsonPropertyAccessorTests { Expression expression = parser.parseExpression("foo"); Object json = mapper.readTree("{\"foo\": \"bar\"}"); Object value = expression.getValue(this.context, json); - assertThat(value, Matchers.instanceOf(JsonPropertyAccessor.ToStringFriendlyJsonNode.class)); - assertEquals("bar", value.toString()); + assertThat(value).isInstanceOf(JsonPropertyAccessor.ToStringFriendlyJsonNode.class); + assertThat(value.toString()).isEqualTo("bar"); Object json2 = mapper.readTree("{}"); Object value2 = expression.getValue(this.context, json2); - assertNull(value2); + assertThat(value2).isNull(); } private T evaluate(Object target, String expression, Class expectedType) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerParserTests.java index c9985793f8..10d6362713 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -68,8 +66,8 @@ public class JsonToObjectTransformerParserTests { public void defaultObjectMapper() { Object jsonToObjectTransformer = TestUtils.getPropertyValue(this.defaultJacksonMapperTransformer, "transformer"); - assertEquals(Jackson2JsonObjectMapper.class, - TestUtils.getPropertyValue(jsonToObjectTransformer, "jsonObjectMapper").getClass()); + assertThat(TestUtils.getPropertyValue(jsonToObjectTransformer, "jsonObjectMapper").getClass()) + .isEqualTo(Jackson2JsonObjectMapper.class); String jsonString = "{\"firstName\":\"John\",\"lastName\":\"Doe\",\"age\":42," + @@ -78,32 +76,32 @@ public class JsonToObjectTransformerParserTests { Message message = MessageBuilder.withPayload(jsonString).setReplyChannel(replyChannel).build(); this.defaultObjectMapperInput.send(message); Message reply = replyChannel.receive(0); - assertNotNull(reply); - assertNotNull(reply.getPayload()); - assertEquals(TestPerson.class, reply.getPayload().getClass()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isNotNull(); + assertThat(reply.getPayload().getClass()).isEqualTo(TestPerson.class); TestPerson person = (TestPerson) reply.getPayload(); - assertEquals("John", person.getFirstName()); - assertEquals("Doe", person.getLastName()); - assertEquals(42, person.getAge()); - assertEquals("123 Main Street", person.getAddress().toString()); + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(person.getLastName()).isEqualTo("Doe"); + assertThat(person.getAge()).isEqualTo(42); + assertThat(person.getAddress().toString()).isEqualTo("123 Main Street"); } @Test public void testInt2831CustomJsonObjectMapper() { Object jsonToObjectTransformer = TestUtils.getPropertyValue(this.customJsonMapperTransformer, "transformer"); - assertSame(this.jsonObjectMapper, - TestUtils.getPropertyValue(jsonToObjectTransformer, "jsonObjectMapper", JsonObjectMapper.class)); + assertThat(TestUtils.getPropertyValue(jsonToObjectTransformer, "jsonObjectMapper", JsonObjectMapper.class)) + .isSameAs(this.jsonObjectMapper); String jsonString = "{firstName:'John', lastName:'Doe', age:42, address:{number:123, street:'Main Street'}}"; QueueChannel replyChannel = new QueueChannel(); Message message = MessageBuilder.withPayload(jsonString).setReplyChannel(replyChannel).build(); this.customJsonObjectMapperInput.send(message); Message reply = replyChannel.receive(0); - assertNotNull(reply); - assertNotNull(reply.getPayload()); - assertEquals(TestJsonContainer.class, reply.getPayload().getClass()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isNotNull(); + assertThat(reply.getPayload().getClass()).isEqualTo(TestJsonContainer.class); TestJsonContainer result = (TestJsonContainer) reply.getPayload(); - assertEquals(jsonString, result.getJson()); + assertThat(result.getJson()).isEqualTo(jsonString); } @SuppressWarnings("rawtypes") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerTests.java index abd6e78725..7683d12e06 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonToObjectTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -45,10 +45,10 @@ public class JsonToObjectTransformerTests { "\"address\":{\"number\":123,\"street\":\"Main Street\"}, \"foo\":\"bar\"}"; Message message = transformer.transform(new GenericMessage<>(jsonString)); TestPerson person = (TestPerson) message.getPayload(); - assertEquals("John", person.getFirstName()); - assertEquals("Doe", person.getLastName()); - assertEquals(42, person.getAge()); - assertEquals("123 Main Street", person.getAddress().toString()); + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(person.getLastName()).isEqualTo("Doe"); + assertThat(person.getAge()).isEqualTo(42); + assertThat(person.getAddress().toString()).isEqualTo("123 Main Street"); } @Test @@ -61,10 +61,10 @@ public class JsonToObjectTransformerTests { String jsonString = "{firstName:'John', lastName:'Doe', age:42, address:{number:123, street:'Main Street'}}"; Message message = transformer.transform(new GenericMessage(jsonString)); TestPerson person = (TestPerson) message.getPayload(); - assertEquals("John", person.getFirstName()); - assertEquals("Doe", person.getLastName()); - assertEquals(42, person.getAge()); - assertEquals("123 Main Street", person.getAddress().toString()); + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(person.getLastName()).isEqualTo("Doe"); + assertThat(person.getAge()).isEqualTo(42); + assertThat(person.getAddress().toString()).isEqualTo("123 Main Street"); } @@ -75,10 +75,10 @@ public class JsonToObjectTransformerTests { "\"address\":{\"number\":123,\"street\":\"Main Street\"}}"; Message message = transformer.transform(new GenericMessage(jsonString)); TestPerson person = (TestPerson) message.getPayload(); - assertEquals("John", person.getFirstName()); - assertEquals("Doe", person.getLastName()); - assertEquals(42, person.getAge()); - assertEquals("123 Main Street", person.getAddress().toString()); + assertThat(person.getFirstName()).isEqualTo("John"); + assertThat(person.getLastName()).isEqualTo("Doe"); + assertThat(person.getAge()).isEqualTo(42); + assertThat(person.getAddress().toString()).isEqualTo("123 Main Street"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonTransformersSymmetricalTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonTransformersSymmetricalTests.java index 2d6ba002ca..73400f9e51 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonTransformersSymmetricalTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonTransformersSymmetricalTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2019 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,11 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.integration.support.json.BoonJsonObjectMapper; @@ -50,8 +48,8 @@ public class JsonTransformersSymmetricalTests { JsonToObjectTransformer jsonToObjectTransformer = new JsonToObjectTransformer(); Object result = jsonToObjectTransformer.transform(jsonMessage).getPayload(); - assertThat(result, Matchers.instanceOf(List.class)); - assertEquals(person, ((List) result).get(0)); + assertThat(result).isInstanceOf(List.class); + assertThat(((List) result).get(0)).isEqualTo(person); } @Test @@ -68,8 +66,8 @@ public class JsonTransformersSymmetricalTests { JsonToObjectTransformer jsonToObjectTransformer = new JsonToObjectTransformer(new BoonJsonObjectMapper()); Object result = jsonToObjectTransformer.transform(jsonMessage).getPayload(); - assertThat(result, Matchers.instanceOf(List.class)); - assertEquals(person, ((List) result).get(0)); + assertThat(result).isInstanceOf(List.class); + assertThat(((List) result).get(0)).isEqualTo(person); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerParserTests.java index 37f3c37d52..07c3a7b4d1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,12 @@ package org.springframework.integration.json; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -84,15 +79,15 @@ public class ObjectToJsonTransformerParserTests { ObjectToJsonTransformer transformer = TestUtils.getPropertyValue(context.getBean("defaultTransformer"), "handler.transformer", ObjectToJsonTransformer.class); - assertEquals("application/json", TestUtils.getPropertyValue(transformer, "contentType")); + assertThat(TestUtils.getPropertyValue(transformer, "contentType")).isEqualTo("application/json"); - assertEquals(Jackson2JsonObjectMapper.class, - TestUtils.getPropertyValue(transformer, "jsonObjectMapper").getClass()); + assertThat(TestUtils.getPropertyValue(transformer, "jsonObjectMapper").getClass()) + .isEqualTo(Jackson2JsonObjectMapper.class); Message transformed = transformer.transform(MessageBuilder.withPayload("foo").build()); // spring.integration.readOnly.headers=contentType, so no 'contentType' - assertFalse(transformed.getHeaders().containsKey(MessageHeaders.CONTENT_TYPE)); + assertThat(transformed.getHeaders().containsKey(MessageHeaders.CONTENT_TYPE)).isFalse(); // Reset readOnlyHeaders to defaults. Therefore the 'contentType' should be presented in subsequent tests this.defaultMessageBuilderFactory.setReadOnlyHeaders(); @@ -100,20 +95,20 @@ public class ObjectToJsonTransformerParserTests { transformer = TestUtils.getPropertyValue(context.getBean("emptyContentTypeTransformer"), "handler.transformer", ObjectToJsonTransformer.class); - assertEquals("", TestUtils.getPropertyValue(transformer, "contentType")); + assertThat(TestUtils.getPropertyValue(transformer, "contentType")).isEqualTo(""); transformed = transformer.transform(MessageBuilder.withPayload("foo").build()); - assertFalse(transformed.getHeaders().containsKey(MessageHeaders.CONTENT_TYPE)); + assertThat(transformed.getHeaders().containsKey(MessageHeaders.CONTENT_TYPE)).isFalse(); transformed = transformer.transform(MessageBuilder.withPayload("foo").setHeader(MessageHeaders.CONTENT_TYPE, "foo").build()); - assertNotNull(transformed.getHeaders().get(MessageHeaders.CONTENT_TYPE)); - assertEquals("foo", transformed.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(transformed.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isNotNull(); + assertThat(transformed.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo("foo"); transformer = TestUtils.getPropertyValue(context.getBean("overriddenContentTypeTransformer"), "handler.transformer", ObjectToJsonTransformer.class); - assertEquals("text/xml", TestUtils.getPropertyValue(transformer, "contentType")); + assertThat(TestUtils.getPropertyValue(transformer, "contentType")).isEqualTo("text/xml"); } @@ -131,19 +126,19 @@ public class ObjectToJsonTransformerParserTests { Message message = MessageBuilder.withPayload(person).setReplyChannel(replyChannel).build(); this.defaultObjectMapperInput.send(message); Message reply = replyChannel.receive(0); - assertNotNull(reply); - assertNotNull(reply.getPayload()); - assertEquals(String.class, reply.getPayload().getClass()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isNotNull(); + assertThat(reply.getPayload().getClass()).isEqualTo(String.class); String resultString = (String) reply.getPayload(); - assertTrue(resultString.contains("\"firstName\":\"John\"")); - assertTrue(resultString.contains("\"lastName\":\"Doe\"")); - assertTrue(resultString.contains("\"age\":42")); + assertThat(resultString.contains("\"firstName\":\"John\"")).isTrue(); + assertThat(resultString.contains("\"lastName\":\"Doe\"")).isTrue(); + assertThat(resultString.contains("\"age\":42")).isTrue(); Pattern addressPattern = Pattern.compile("(\"address\":\\{.*?\\})"); Matcher matcher = addressPattern.matcher(resultString); - assertTrue(matcher.find()); + assertThat(matcher.find()).isTrue(); String addressResult = matcher.group(1); - assertTrue(addressResult.contains("\"number\":123")); - assertTrue(addressResult.contains("\"street\":\"Main Street\"")); + assertThat(addressResult.contains("\"number\":123")).isTrue(); + assertThat(addressResult.contains("\"street\":\"Main Street\"")).isTrue(); } @Test @@ -156,11 +151,11 @@ public class ObjectToJsonTransformerParserTests { Message message = MessageBuilder.withPayload(person).setReplyChannel(replyChannel).build(); this.customJsonObjectMapperInput.send(message); Message reply = replyChannel.receive(0); - assertNotNull(reply); - assertNotNull(reply.getPayload()); - assertEquals(String.class, reply.getPayload().getClass()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isNotNull(); + assertThat(reply.getPayload().getClass()).isEqualTo(String.class); String resultString = (String) reply.getPayload(); - assertEquals("{" + person.toString() + "}", resultString); + assertThat(resultString).isEqualTo("{" + person.toString() + "}"); } @Test @@ -173,15 +168,15 @@ public class ObjectToJsonTransformerParserTests { Message message = MessageBuilder.withPayload(person).setReplyChannel(replyChannel).build(); this.jsonNodeInput.send(message); Message reply = replyChannel.receive(0); - assertNotNull(reply); + assertThat(reply).isNotNull(); Object payload = reply.getPayload(); - assertThat(payload, Matchers.instanceOf(JsonNode.class)); + assertThat(payload).isInstanceOf(JsonNode.class); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); evaluationContext.addPropertyAccessor(new JsonPropertyAccessor()); Expression expression = new SpelExpressionParser() .parseExpression("firstName.toString() == 'John' and age.toString() == '42'"); - assertTrue(expression.getValue(evaluationContext, payload, Boolean.class)); + assertThat(expression.getValue(evaluationContext, payload, Boolean.class)).isTrue(); } @Test @@ -194,13 +189,13 @@ public class ObjectToJsonTransformerParserTests { Message message = MessageBuilder.withPayload(person).setReplyChannel(replyChannel).build(); this.boonJsonNodeInput.send(message); Message reply = replyChannel.receive(0); - assertNotNull(reply); + assertThat(reply).isNotNull(); Object payload = reply.getPayload(); - assertThat(payload, Matchers.instanceOf(Map.class)); - assertEquals(TestPerson.class, reply.getHeaders().get(JsonHeaders.TYPE_ID)); + assertThat(payload).isInstanceOf(Map.class); + assertThat(reply.getHeaders().get(JsonHeaders.TYPE_ID)).isEqualTo(TestPerson.class); Expression expression = new SpelExpressionParser().parseExpression("[firstName] == 'John' and [age] == 42"); - assertTrue(expression.getValue(new StandardEvaluationContext(), payload, Boolean.class)); + assertThat(expression.getValue(new StandardEvaluationContext(), payload, Boolean.class)).isTrue(); } static class CustomJsonObjectMapper extends JsonObjectMapperAdapter { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerTests.java index cd2d2a76f5..262929356c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/ObjectToJsonTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.json; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.List; @@ -63,14 +57,15 @@ public class ObjectToJsonTransformerTests { public void simpleStringPayload() { ObjectToJsonTransformer transformer = new ObjectToJsonTransformer(); String result = (String) transformer.transform(new GenericMessage<>("foo")).getPayload(); - assertEquals("\"foo\"", result); + assertThat(result).isEqualTo("\"foo\""); } @Test public void withDefaultContentType() { ObjectToJsonTransformer transformer = new ObjectToJsonTransformer(); Message result = transformer.transform(new GenericMessage<>("foo")); - assertEquals(ObjectToJsonTransformer.JSON_CONTENT_TYPE, result.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(result.getHeaders().get(MessageHeaders.CONTENT_TYPE)) + .isEqualTo(ObjectToJsonTransformer.JSON_CONTENT_TYPE); } @Test @@ -80,7 +75,7 @@ public class ObjectToJsonTransformerTests { .setHeader(MessageHeaders.CONTENT_TYPE, "text/xml") .build(); Message result = transformer.transform(message); - assertEquals("text/xml", result.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(result.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo("text/xml"); } @Test @@ -91,7 +86,8 @@ public class ObjectToJsonTransformerTests { .setHeader(MessageHeaders.CONTENT_TYPE, "text/xml") .build(); Message result = transformer.transform(message); - assertEquals(ObjectToJsonTransformer.JSON_CONTENT_TYPE, result.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(result.getHeaders().get(MessageHeaders.CONTENT_TYPE)) + .isEqualTo(ObjectToJsonTransformer.JSON_CONTENT_TYPE); } @Test @@ -100,7 +96,7 @@ public class ObjectToJsonTransformerTests { transformer.setContentType(""); Message message = MessageBuilder.withPayload("foo").build(); Message result = transformer.transform(message); - assertFalse(result.getHeaders().containsKey(MessageHeaders.CONTENT_TYPE)); + assertThat(result.getHeaders().containsKey(MessageHeaders.CONTENT_TYPE)).isFalse(); } @Test @@ -111,7 +107,7 @@ public class ObjectToJsonTransformerTests { .setHeader(MessageHeaders.CONTENT_TYPE, "text/xml") .build(); Message result = transformer.transform(message); - assertEquals("text/xml", result.getHeaders().get(MessageHeaders.CONTENT_TYPE)); + assertThat(result.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo("text/xml"); } @Test(expected = IllegalArgumentException.class) @@ -124,15 +120,15 @@ public class ObjectToJsonTransformerTests { public void simpleIntegerPayload() { ObjectToJsonTransformer transformer = new ObjectToJsonTransformer(); String result = (String) transformer.transform(new GenericMessage<>(123)).getPayload(); - assertEquals("123", result); + assertThat(result).isEqualTo("123"); } @Test public void simpleIntegerAsBytesPayload() { ObjectToJsonTransformer transformer = new ObjectToJsonTransformer(ObjectToJsonTransformer.ResultType.BYTES); Object result = transformer.transform(new GenericMessage<>(123)).getPayload(); - assertThat(result, instanceOf(byte[].class)); - assertEquals("123", new String((byte[]) result)); + assertThat(result).isInstanceOf(byte[].class); + assertThat(new String((byte[]) result)).isEqualTo("123"); } @Test @@ -142,15 +138,15 @@ public class ObjectToJsonTransformerTests { TestPerson person = new TestPerson("John", "Doe", 42); person.setAddress(address); String result = (String) transformer.transform(new GenericMessage<>(person)).getPayload(); - assertTrue(result.contains("\"firstName\":\"John\"")); - assertTrue(result.contains("\"lastName\":\"Doe\"")); - assertTrue(result.contains("\"age\":42")); + assertThat(result.contains("\"firstName\":\"John\"")).isTrue(); + assertThat(result.contains("\"lastName\":\"Doe\"")).isTrue(); + assertThat(result.contains("\"age\":42")).isTrue(); Pattern addressPattern = Pattern.compile("(\"address\":\\{.*?\\})"); Matcher matcher = addressPattern.matcher(result); - assertTrue(matcher.find()); + assertThat(matcher.find()).isTrue(); String addressResult = matcher.group(1); - assertTrue(addressResult.contains("\"number\":123")); - assertTrue(addressResult.contains("\"street\":\"Main Street\"")); + assertThat(addressResult.contains("\"number\":123")).isTrue(); + assertThat(addressResult.contains("\"street\":\"Main Street\"")).isTrue(); } @Test @@ -161,15 +157,15 @@ public class ObjectToJsonTransformerTests { TestPerson person = new TestPerson("John", "Doe", 42); person.setAddress(new TestAddress(123, "Main Street")); String result = (String) transformer.transform(new GenericMessage<>(person)).getPayload(); - assertTrue(result.contains("firstName:\"John\"")); - assertTrue(result.contains("lastName:\"Doe\"")); - assertTrue(result.contains("age:42")); + assertThat(result.contains("firstName:\"John\"")).isTrue(); + assertThat(result.contains("lastName:\"Doe\"")).isTrue(); + assertThat(result.contains("age:42")).isTrue(); Pattern addressPattern = Pattern.compile("(address:\\{.*?\\})"); Matcher matcher = addressPattern.matcher(result); - assertTrue(matcher.find()); + assertThat(matcher.find()).isTrue(); String addressResult = matcher.group(1); - assertTrue(addressResult.contains("number:123")); - assertTrue(addressResult.contains("street:\"Main Street\"")); + assertThat(addressResult.contains("number:123")).isTrue(); + assertThat(addressResult.contains("street:\"Main Street\"")).isTrue(); } @Test @@ -177,13 +173,13 @@ public class ObjectToJsonTransformerTests { ObjectToJsonTransformer transformer = new ObjectToJsonTransformer(); List list = Collections.singletonList("foo"); Message out = transformer.transform(new GenericMessage<>(list)); - assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString(), containsString("SingletonList")); - assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID), equalTo(String.class)); + assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString()).contains("SingletonList"); + assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID)).isEqualTo(String.class); Map map = Collections.singletonMap("foo", 1L); out = transformer.transform(new GenericMessage<>(map)); - assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString(), containsString("SingletonMap")); - assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID), equalTo(Long.class)); - assertThat(out.getHeaders().get(JsonHeaders.KEY_TYPE_ID), equalTo(String.class)); + assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString()).contains("SingletonMap"); + assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID)).isEqualTo(Long.class); + assertThat(out.getHeaders().get(JsonHeaders.KEY_TYPE_ID)).isEqualTo(String.class); } @Test @@ -191,13 +187,13 @@ public class ObjectToJsonTransformerTests { ObjectToJsonTransformer transformer = new ObjectToJsonTransformer(); List list = Collections.singletonList(null); Message out = transformer.transform(new GenericMessage<>(list)); - assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString(), containsString("SingletonList")); - assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID), equalTo(Object.class)); + assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString()).contains("SingletonList"); + assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID)).isEqualTo(Object.class); Map map = Collections.singletonMap("foo", null); out = transformer.transform(new GenericMessage<>(map)); - assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString(), containsString("SingletonMap")); - assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID), equalTo(Object.class)); - assertThat(out.getHeaders().get(JsonHeaders.KEY_TYPE_ID), equalTo(String.class)); + assertThat(out.getHeaders().get(JsonHeaders.TYPE_ID).toString()).contains("SingletonMap"); + assertThat(out.getHeaders().get(JsonHeaders.CONTENT_TYPE_ID)).isEqualTo(Object.class); + assertThat(out.getHeaders().get(JsonHeaders.KEY_TYPE_ID)).isEqualTo(String.class); } @Test @@ -206,15 +202,15 @@ public class ObjectToJsonTransformerTests { TestPerson person = new TestPerson("John", "Doe", 42); person.setAddress(new TestAddress(123, "Main Street")); String result = (String) transformer.transform(new GenericMessage<>(person)).getPayload(); - assertTrue(result.contains("\"firstName\":\"John\"")); - assertTrue(result.contains("\"lastName\":\"Doe\"")); - assertTrue(result.contains("\"age\":42")); + assertThat(result.contains("\"firstName\":\"John\"")).isTrue(); + assertThat(result.contains("\"lastName\":\"Doe\"")).isTrue(); + assertThat(result.contains("\"age\":42")).isTrue(); Pattern addressPattern = Pattern.compile("(\"address\":\\{.*?\\})"); Matcher matcher = addressPattern.matcher(result); - assertTrue(matcher.find()); + assertThat(matcher.find()).isTrue(); String addressResult = matcher.group(1); - assertTrue(addressResult.contains("\"number\":123")); - assertTrue(addressResult.contains("\"street\":\"Main Street\"")); + assertThat(addressResult.contains("\"number\":123")).isTrue(); + assertThat(addressResult.contains("\"street\":\"Main Street\"")).isTrue(); } @Test @@ -224,7 +220,7 @@ public class ObjectToJsonTransformerTests { TestPerson person = new TestPerson("John", "Doe", 42); person.setAddress(new TestAddress(123, "Main Street")); Object payload = transformer.transform(new GenericMessage<>(person)).getPayload(); - assertThat(payload, instanceOf(Map.class)); + assertThat(payload).isInstanceOf(Map.class); SpelExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression("firstName + ': ' + address.street"); @@ -232,22 +228,22 @@ public class ObjectToJsonTransformerTests { evaluationContext.addPropertyAccessor(new MapAccessor()); String value = expression.getValue(evaluationContext, payload, String.class); - assertEquals("John: Main Street", value); + assertThat(value).isEqualTo("John: Main Street"); } @Test public void testJsonStringAndJsonNode() { ObjectToJsonTransformer transformer = new ObjectToJsonTransformer(ObjectToJsonTransformer.ResultType.NODE); Object result = transformer.transform(new GenericMessage<>("{\"foo\": \"FOO\", \"bar\": 1}")).getPayload(); - assertThat(result, instanceOf(ObjectNode.class)); + assertThat(result).isInstanceOf(ObjectNode.class); ObjectNode objectNode = (ObjectNode) result; - assertEquals(2, objectNode.size()); - assertEquals("FOO", objectNode.path("foo").textValue()); - assertEquals(1, objectNode.path("bar").intValue()); + assertThat(objectNode.size()).isEqualTo(2); + assertThat(objectNode.path("foo").textValue()).isEqualTo("FOO"); + assertThat(objectNode.path("bar").intValue()).isEqualTo(1); result = transformer.transform(new GenericMessage<>("foo")).getPayload(); - assertThat(result, instanceOf(TextNode.class)); - assertEquals("foo", ((TextNode) result).textValue()); + assertThat(result).isInstanceOf(TextNode.class); + assertThat(((TextNode) result).textValue()).isEqualTo("foo"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/SimpleJsonSerializerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/SimpleJsonSerializerTests.java index 7e4c62f8ae..6436639a68 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/SimpleJsonSerializerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/SimpleJsonSerializerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.json; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -38,11 +36,11 @@ public class SimpleJsonSerializerTests { Foo foo = new Foo("foo"); String json = SimpleJsonSerializer.toJson(foo, "fileInfo"); Foo fooOut = JsonObjectMapperProvider.newInstance().fromJson(json, Foo.class); - assertThat(fooOut.bool, equalTo(Boolean.TRUE)); - assertThat(fooOut.bar, equalTo(42L)); - assertThat(fooOut.foo, equalTo("bar")); - assertThat(fooOut.dub, equalTo(1.6)); - assertNull(fooOut.fileInfo); + assertThat(fooOut.bool).isEqualTo(Boolean.TRUE); + assertThat(fooOut.bar).isEqualTo(42L); + assertThat(fooOut.foo).isEqualTo("bar"); + assertThat(fooOut.dub).isEqualTo(1.6); + assertThat(fooOut.fileInfo).isNull(); } public static class Foo { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java b/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java index a4ea731385..98a94d487f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.mapping; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collection; @@ -53,10 +51,10 @@ public class HeaderMapperTests { GenericTestProperties properties = createSimpleGenericTestProperties(); Map attributes = this.mapper.toHeadersFromRequest(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertEquals("request-123", attributes.get(GenericTestHeaders.REQUEST_ONLY)); - assertFalse(attributes.containsKey(GenericTestHeaders.REPLY_ONLY)); - assertEquals("Wrong number of mapped header(s)", 2, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.get(GenericTestHeaders.REQUEST_ONLY)).isEqualTo("request-123"); + assertThat(attributes.containsKey(GenericTestHeaders.REPLY_ONLY)).isFalse(); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(2); } @Test @@ -65,11 +63,11 @@ public class HeaderMapperTests { GenericTestProperties properties = createSimpleGenericTestProperties(); Map attributes = this.mapper.toHeadersFromRequest(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertEquals("request-123", attributes.get(GenericTestHeaders.REQUEST_ONLY)); - assertEquals("reply-123", attributes.get(GenericTestHeaders.REPLY_ONLY)); - assertEquals("bar", attributes.get("foo")); - assertEquals("Wrong number of mapped header(s)", 4, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.get(GenericTestHeaders.REQUEST_ONLY)).isEqualTo("request-123"); + assertThat(attributes.get(GenericTestHeaders.REPLY_ONLY)).isEqualTo("reply-123"); + assertThat(attributes.get("foo")).isEqualTo("bar"); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(4); } @Test @@ -78,11 +76,11 @@ public class HeaderMapperTests { GenericTestProperties properties = createSimpleGenericTestProperties(); Map attributes = this.mapper.toHeadersFromRequest(properties); - assertNull(attributes.get(GenericTestHeaders.APP_ID)); - assertNull(attributes.get(GenericTestHeaders.REQUEST_ONLY)); - assertEquals("reply-123", attributes.get(GenericTestHeaders.REPLY_ONLY)); - assertEquals("bar", attributes.get("foo")); - assertEquals("Wrong number of mapped header(s)", 2, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isNull(); + assertThat(attributes.get(GenericTestHeaders.REQUEST_ONLY)).isNull(); + assertThat(attributes.get(GenericTestHeaders.REPLY_ONLY)).isEqualTo("reply-123"); + assertThat(attributes.get("foo")).isEqualTo("bar"); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(2); } @Test @@ -93,12 +91,12 @@ public class HeaderMapperTests { properties.setUserDefinedHeader("something-else", "bar"); Map attributes = this.mapper.toHeadersFromRequest(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertEquals("request-123", attributes.get(GenericTestHeaders.REQUEST_ONLY)); - assertFalse(attributes.containsKey(GenericTestHeaders.REPLY_ONLY)); - assertEquals("bar", attributes.get("foo")); - assertEquals("bar", attributes.get("foo2")); - assertEquals("Wrong number of mapped header(s)", 4, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.get(GenericTestHeaders.REQUEST_ONLY)).isEqualTo("request-123"); + assertThat(attributes.containsKey(GenericTestHeaders.REPLY_ONLY)).isFalse(); + assertThat(attributes.get("foo")).isEqualTo("bar"); + assertThat(attributes.get("foo2")).isEqualTo("bar"); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(4); } @Test @@ -109,10 +107,10 @@ public class HeaderMapperTests { properties.setUserDefinedHeader("something-else", "bar"); Map attributes = this.mapper.toHeadersFromRequest(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertEquals("request-123", attributes.get(GenericTestHeaders.REQUEST_ONLY)); - assertFalse(attributes.containsKey(GenericTestHeaders.REPLY_ONLY)); - assertEquals("Wrong number of mapped header(s)", 2, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.get(GenericTestHeaders.REQUEST_ONLY)).isEqualTo("request-123"); + assertThat(attributes.containsKey(GenericTestHeaders.REPLY_ONLY)).isFalse(); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(2); } @Test @@ -120,10 +118,10 @@ public class HeaderMapperTests { GenericTestProperties properties = createSimpleGenericTestProperties(); Map attributes = this.mapper.toHeadersFromReply(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertFalse(attributes.containsKey(GenericTestHeaders.REQUEST_ONLY)); - assertEquals("reply-123", attributes.get(GenericTestHeaders.REPLY_ONLY)); - assertEquals("Wrong number of mapped header(s)", 2, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.containsKey(GenericTestHeaders.REQUEST_ONLY)).isFalse(); + assertThat(attributes.get(GenericTestHeaders.REPLY_ONLY)).isEqualTo("reply-123"); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(2); } @Test @@ -132,11 +130,11 @@ public class HeaderMapperTests { GenericTestProperties properties = createSimpleGenericTestProperties(); Map attributes = this.mapper.toHeadersFromReply(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertEquals("request-123", attributes.get(GenericTestHeaders.REQUEST_ONLY)); - assertEquals("reply-123", attributes.get(GenericTestHeaders.REPLY_ONLY)); - assertEquals("bar", attributes.get("foo")); - assertEquals("Wrong number of mapped header(s)", 4, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.get(GenericTestHeaders.REQUEST_ONLY)).isEqualTo("request-123"); + assertThat(attributes.get(GenericTestHeaders.REPLY_ONLY)).isEqualTo("reply-123"); + assertThat(attributes.get("foo")).isEqualTo("bar"); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(4); } @Test @@ -148,12 +146,12 @@ public class HeaderMapperTests { properties.setUserDefinedHeader("something-else", "bar"); Map attributes = this.mapper.toHeadersFromReply(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertFalse(attributes.containsKey(GenericTestHeaders.REQUEST_ONLY)); - assertEquals("reply-123", attributes.get(GenericTestHeaders.REPLY_ONLY)); - assertEquals("bar", attributes.get("foo")); - assertEquals("bar", attributes.get("foo2")); - assertEquals("Wrong number of mapped header(s)", 4, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.containsKey(GenericTestHeaders.REQUEST_ONLY)).isFalse(); + assertThat(attributes.get(GenericTestHeaders.REPLY_ONLY)).isEqualTo("reply-123"); + assertThat(attributes.get("foo")).isEqualTo("bar"); + assertThat(attributes.get("foo2")).isEqualTo("bar"); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(4); } @Test @@ -165,10 +163,10 @@ public class HeaderMapperTests { properties.setUserDefinedHeader("something-else", "bar"); Map attributes = this.mapper.toHeadersFromReply(properties); - assertEquals("appId", attributes.get(GenericTestHeaders.APP_ID)); - assertFalse(attributes.containsKey(GenericTestHeaders.REQUEST_ONLY)); - assertEquals("reply-123", attributes.get(GenericTestHeaders.REPLY_ONLY)); - assertEquals("Wrong number of mapped header(s)", 2, attributes.size()); + assertThat(attributes.get(GenericTestHeaders.APP_ID)).isEqualTo("appId"); + assertThat(attributes.containsKey(GenericTestHeaders.REQUEST_ONLY)).isFalse(); + assertThat(attributes.get(GenericTestHeaders.REPLY_ONLY)).isEqualTo("reply-123"); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(2); } @Test @@ -183,9 +181,9 @@ public class HeaderMapperTests { Map attributes = customMapper.toHeadersFromReply(properties); // foo custom header and app Id not mapped - assertFalse(attributes.containsKey(GenericTestHeaders.APP_ID)); - assertFalse(attributes.containsKey("foo")); - assertEquals("Wrong number of mapped header(s)", 1, attributes.size()); + assertThat(attributes.containsKey(GenericTestHeaders.APP_ID)).isFalse(); + assertThat(attributes.containsKey("foo")).isFalse(); + assertThat(attributes.size()).as("Wrong number of mapped header(s)").isEqualTo(1); } private GenericTestProperties createSimpleGenericTestProperties() { @@ -203,12 +201,12 @@ public class HeaderMapperTests { MessageHeaders messageHeaders = createSimpleMessageHeaders(); GenericTestProperties properties = new GenericTestProperties(); this.mapper.fromHeadersToRequest(messageHeaders, properties); - assertEquals("myAppId", properties.getAppId()); - assertNull(properties.getTransactionSize()); - assertEquals(true, properties.getRedelivered()); - assertEquals("request-456", properties.getRequestOnly()); - assertNull(properties.getReplyOnly()); - assertEquals(0, properties.getUserDefinedHeaders().size()); + assertThat(properties.getAppId()).isEqualTo("myAppId"); + assertThat(properties.getTransactionSize()).isNull(); + assertThat(properties.getRedelivered()).isEqualTo(true); + assertThat(properties.getRequestOnly()).isEqualTo("request-456"); + assertThat(properties.getReplyOnly()).isNull(); + assertThat(properties.getUserDefinedHeaders().size()).isEqualTo(0); } @Test @@ -217,13 +215,13 @@ public class HeaderMapperTests { MessageHeaders messageHeaders = createSimpleMessageHeaders(); GenericTestProperties properties = new GenericTestProperties(); this.mapper.fromHeadersToRequest(messageHeaders, properties); - assertEquals("myAppId", properties.getAppId()); - assertNull(properties.getTransactionSize()); - assertEquals(true, properties.getRedelivered()); - assertEquals("request-456", properties.getRequestOnly()); - assertEquals("reply-456", properties.getReplyOnly()); - assertEquals("bar", properties.getUserDefinedHeaders().get("foo")); - assertEquals(1, properties.getUserDefinedHeaders().size()); + assertThat(properties.getAppId()).isEqualTo("myAppId"); + assertThat(properties.getTransactionSize()).isNull(); + assertThat(properties.getRedelivered()).isEqualTo(true); + assertThat(properties.getRequestOnly()).isEqualTo("request-456"); + assertThat(properties.getReplyOnly()).isEqualTo("reply-456"); + assertThat(properties.getUserDefinedHeaders().get("foo")).isEqualTo("bar"); + assertThat(properties.getUserDefinedHeaders().size()).isEqualTo(1); } @Test @@ -232,13 +230,13 @@ public class HeaderMapperTests { MessageHeaders messageHeaders = createSimpleMessageHeaders(); GenericTestProperties properties = new GenericTestProperties(); this.mapper.fromHeadersToRequest(messageHeaders, properties); - assertEquals("myAppId", properties.getAppId()); - assertNull(properties.getTransactionSize()); - assertEquals(true, properties.getRedelivered()); - assertEquals("request-456", properties.getRequestOnly()); - assertNull(properties.getReplyOnly()); - assertEquals("bar", properties.getUserDefinedHeaders().get("foo")); - assertEquals(1, properties.getUserDefinedHeaders().size()); + assertThat(properties.getAppId()).isEqualTo("myAppId"); + assertThat(properties.getTransactionSize()).isNull(); + assertThat(properties.getRedelivered()).isEqualTo(true); + assertThat(properties.getRequestOnly()).isEqualTo("request-456"); + assertThat(properties.getReplyOnly()).isNull(); + assertThat(properties.getUserDefinedHeaders().get("foo")).isEqualTo("bar"); + assertThat(properties.getUserDefinedHeaders().size()).isEqualTo(1); } @Test @@ -258,14 +256,14 @@ public class HeaderMapperTests { MessageHeaders messageHeaders = new MessageHeaders(headers); GenericTestProperties properties = new GenericTestProperties(); this.mapper.fromHeadersToRequest(messageHeaders, properties); - assertEquals("myAppId", properties.getAppId()); - assertNull(properties.getTransactionSize()); - assertEquals(true, properties.getRedelivered()); - assertEquals("request-456", properties.getRequestOnly()); - assertNull(properties.getReplyOnly()); - assertEquals("bar", properties.getUserDefinedHeaders().get("bar")); - assertEquals("qux", properties.getUserDefinedHeaders().get("!qux")); - assertEquals(2, properties.getUserDefinedHeaders().size()); + assertThat(properties.getAppId()).isEqualTo("myAppId"); + assertThat(properties.getTransactionSize()).isNull(); + assertThat(properties.getRedelivered()).isEqualTo(true); + assertThat(properties.getRequestOnly()).isEqualTo("request-456"); + assertThat(properties.getReplyOnly()).isNull(); + assertThat(properties.getUserDefinedHeaders().get("bar")).isEqualTo("bar"); + assertThat(properties.getUserDefinedHeaders().get("!qux")).isEqualTo("qux"); + assertThat(properties.getUserDefinedHeaders().size()).isEqualTo(2); } @Test @@ -273,12 +271,12 @@ public class HeaderMapperTests { MessageHeaders messageHeaders = createSimpleMessageHeaders(); GenericTestProperties properties = new GenericTestProperties(); this.mapper.fromHeadersToReply(messageHeaders, properties); - assertEquals("myAppId", properties.getAppId()); - assertNull(properties.getTransactionSize()); - assertEquals(true, properties.getRedelivered()); - assertNull(properties.getRequestOnly()); - assertEquals("reply-456", properties.getReplyOnly()); - assertEquals(0, properties.getUserDefinedHeaders().size()); + assertThat(properties.getAppId()).isEqualTo("myAppId"); + assertThat(properties.getTransactionSize()).isNull(); + assertThat(properties.getRedelivered()).isEqualTo(true); + assertThat(properties.getRequestOnly()).isNull(); + assertThat(properties.getReplyOnly()).isEqualTo("reply-456"); + assertThat(properties.getUserDefinedHeaders().size()).isEqualTo(0); } @Test @@ -287,13 +285,13 @@ public class HeaderMapperTests { MessageHeaders messageHeaders = createSimpleMessageHeaders(); GenericTestProperties properties = new GenericTestProperties(); this.mapper.fromHeadersToReply(messageHeaders, properties); - assertEquals("myAppId", properties.getAppId()); - assertNull(properties.getTransactionSize()); - assertEquals(true, properties.getRedelivered()); - assertEquals("request-456", properties.getRequestOnly()); - assertEquals("reply-456", properties.getReplyOnly()); - assertEquals("bar", properties.getUserDefinedHeaders().get("foo")); - assertEquals(1, properties.getUserDefinedHeaders().size()); + assertThat(properties.getAppId()).isEqualTo("myAppId"); + assertThat(properties.getTransactionSize()).isNull(); + assertThat(properties.getRedelivered()).isEqualTo(true); + assertThat(properties.getRequestOnly()).isEqualTo("request-456"); + assertThat(properties.getReplyOnly()).isEqualTo("reply-456"); + assertThat(properties.getUserDefinedHeaders().get("foo")).isEqualTo("bar"); + assertThat(properties.getUserDefinedHeaders().size()).isEqualTo(1); } @@ -303,13 +301,13 @@ public class HeaderMapperTests { MessageHeaders messageHeaders = createSimpleMessageHeaders(); GenericTestProperties properties = new GenericTestProperties(); this.mapper.fromHeadersToReply(messageHeaders, properties); - assertEquals("myAppId", properties.getAppId()); - assertNull(properties.getTransactionSize()); - assertEquals(true, properties.getRedelivered()); - assertNull(properties.getRequestOnly()); - assertEquals("reply-456", properties.getReplyOnly()); - assertEquals("bar", properties.getUserDefinedHeaders().get("foo")); - assertEquals(1, properties.getUserDefinedHeaders().size()); + assertThat(properties.getAppId()).isEqualTo("myAppId"); + assertThat(properties.getTransactionSize()).isNull(); + assertThat(properties.getRedelivered()).isEqualTo(true); + assertThat(properties.getRequestOnly()).isNull(); + assertThat(properties.getReplyOnly()).isEqualTo("reply-456"); + assertThat(properties.getUserDefinedHeaders().get("foo")).isEqualTo("bar"); + assertThat(properties.getUserDefinedHeaders().size()).isEqualTo(1); } public MessageHeaders createSimpleMessageHeaders() { @@ -432,7 +430,7 @@ public class HeaderMapperTests { protected void assertMapping(HeaderMatcher strategy, String candidate, boolean match) { - assertEquals("Wrong mapping result for " + candidate + "", match, strategy.matchHeader(candidate)); + assertThat(strategy.matchHeader(candidate)).as("Wrong mapping result for " + candidate + "").isEqualTo(match); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java index 9f4b47ec47..bc0f0c5f7b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/ExpressionEvaluatingMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.message; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.HashMap; @@ -88,7 +88,7 @@ public class ExpressionEvaluatingMessageHandlerTests { handler.handleMessage(message); } catch (MessagingException e) { - assertEquals(e.getFailedMessage(), message); + assertThat(message).isEqualTo(e.getFailedMessage()); throw e; } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/GenericMessageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/GenericMessageTests.java index 41d650a27b..679adf82f1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/GenericMessageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/GenericMessageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.message; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; @@ -39,10 +39,10 @@ public class GenericMessageTests { headerMap.put(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE, 42); headerMap.put(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, 24); GenericMessage message = new GenericMessage("test", headerMap); - assertEquals(123, message.getHeaders().get("testAttribute")); - assertEquals("foo", message.getHeaders().get("testProperty", String.class)); - assertEquals(42, new IntegrationMessageHeaderAccessor(message).getSequenceSize()); - assertEquals(24, new IntegrationMessageHeaderAccessor(message).getSequenceNumber()); + assertThat(message.getHeaders().get("testAttribute")).isEqualTo(123); + assertThat(message.getHeaders().get("testProperty", String.class)).isEqualTo("foo"); + assertThat(new IntegrationMessageHeaderAccessor(message).getSequenceSize()).isEqualTo(42); + assertThat(new IntegrationMessageHeaderAccessor(message).getSequenceNumber()).isEqualTo(24); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/HeaderMatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/HeaderMatcherTests.java deleted file mode 100644 index ef0a1b66d1..0000000000 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/HeaderMatcherTests.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.integration.message; - -import static org.hamcrest.CoreMatchers.any; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasAllHeaders; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasCorrelationId; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasExpirationDate; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeader; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeaderKey; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasMessageId; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasSequenceNumber; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasSequenceSize; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasTimestamp; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.hamcrest.Matcher; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.integration.support.MessageBuilder; -import org.springframework.messaging.Message; - -/** - * @author Alex Peters - * @author Iwein Fuld - * @author Gunnar Hillert - * - */ -public class HeaderMatcherTests { - - static final String UNKNOWN_KEY = "unknownKey"; - - static final String ANY_HEADER_VALUE = "bar"; - - static final String ANY_HEADER_KEY = "test.foo"; - - static final String ANY_PAYLOAD = "bla"; - - static final String OTHER_HEADER_KEY = "test.number"; - - static final Integer OTHER_HEADER_VALUE = Integer.valueOf(123); - - Message message; - - @Before - public void setUp() { - message = MessageBuilder.withPayload(ANY_PAYLOAD).setHeader(ANY_HEADER_KEY, ANY_HEADER_VALUE).setHeader( - OTHER_HEADER_KEY, OTHER_HEADER_VALUE).build(); - } - - @Test - public void hasEntry_withValidKeyValue_matches() throws Exception { - assertThat(message, hasHeader(ANY_HEADER_KEY, ANY_HEADER_VALUE)); - assertThat(message, hasHeader(OTHER_HEADER_KEY, OTHER_HEADER_VALUE)); - } - - @Test - public void hasEntry_withUnknownKey_notMatching() throws Exception { - assertThat(message, not(hasHeader("test.unknown", ANY_HEADER_VALUE))); - } - - @Test - public void hasEntry_withValidKeyAndMatcherValue_matches() throws Exception { - assertThat(message, hasHeader(ANY_HEADER_KEY, is(instanceOf(String.class)))); - assertThat(message, hasHeader(ANY_HEADER_KEY, notNullValue())); - assertThat(message, hasHeader(ANY_HEADER_KEY, is(ANY_HEADER_VALUE))); - } - - @Test - public void hasEntry_withValidKeyAndMatcherValue_notMatching() throws Exception { - assertThat(message, not(hasHeader(ANY_HEADER_KEY, is(instanceOf(Integer.class))))); - } - - @Test - public void hasKey_withValidKey_matches() throws Exception { - assertThat(message, hasHeaderKey(ANY_HEADER_KEY)); - assertThat(message, hasHeaderKey(OTHER_HEADER_KEY)); - } - - @Test - public void hasKey_withInvalidKey_notMatching() throws Exception { - assertThat(message, not(hasHeaderKey(UNKNOWN_KEY))); - } - - @Test - public void hasAllEntries_withMessageHeader_matches() throws Exception { - Map expectedInHeaderMap = message.getHeaders(); - assertThat(message, hasAllHeaders(expectedInHeaderMap)); - } - - @Test - public void hasAllEntries_withValidKeyValueOrMatcherValue_matches() throws Exception { - Map expectedInHeaderMap = new HashMap(); - expectedInHeaderMap.put(ANY_HEADER_KEY, ANY_HEADER_VALUE); - expectedInHeaderMap.put(OTHER_HEADER_KEY, is(OTHER_HEADER_VALUE)); - assertThat(message, hasAllHeaders(expectedInHeaderMap)); - } - - @Test - public void hasAllEntries_withInvalidValidKeyValueOrMatcherValue_notMatching() throws Exception { - Map expectedInHeaderMap = new HashMap(); - expectedInHeaderMap.put(ANY_HEADER_KEY, ANY_HEADER_VALUE); // valid - expectedInHeaderMap.put(UNKNOWN_KEY, not(nullValue())); // fails - assertThat(message, not(hasAllHeaders(expectedInHeaderMap))); - expectedInHeaderMap.remove(UNKNOWN_KEY); - expectedInHeaderMap.put(OTHER_HEADER_KEY, ANY_HEADER_VALUE); // fails - } - - @Test - public void readableException_singleHeader() throws Exception { - try { - assertThat(message, hasHeader("corn", "bread")); - } - catch (AssertionError ae) { - assertTrue(ae.getMessage().contains("Expected: a Message with Headers containing ")); - } - } - - @Test - public void readableException_allHeaders() throws Exception { - try { - Map entries = new HashMap(); - entries.put("corn", "bread"); - entries.put("chocolate", "pudding"); - assertThat(message, hasAllHeaders(entries)); - } - catch (AssertionError ae) { - assertTrue(ae.getMessage().contains("Expected: a Message with Headers containing ")); - } - } - - @Test - public void hasMessageId_sameId() throws Exception { - assertThat(message, hasMessageId(message.getHeaders().getId())); - } - - @Test - public void hasCorrelationId_() throws Exception { - UUID correlationId = message.getHeaders().getId(); - message = MessageBuilder.withPayload("blabla").setCorrelationId(correlationId).build(); - assertThat(message, hasCorrelationId(correlationId)); - } - - @Test - public void hasSequenceNumber_() throws Exception { - int sequenceNumber = 123; - message = MessageBuilder.fromMessage(message).setSequenceNumber(sequenceNumber).build(); - assertThat(message, hasSequenceNumber(sequenceNumber)); - } - - @Test - public void hasSequenceSize_() throws Exception { - int sequenceSize = 123; - message = MessageBuilder.fromMessage(message).setSequenceSize(sequenceSize).build(); - assertThat(message, hasSequenceSize(sequenceSize)); - assertThat(message, hasSequenceSize(is(sequenceSize))); - } - - @Test - public void hasTimestamp_() throws Exception { - assertThat(message, hasTimestamp(new Date(message.getHeaders().getTimestamp()))); - } - - @Test - public void hasExpirationDate_() throws Exception { - Matcher anyMatcher = any(Long.class); - - assertThat(message, not(hasExpirationDate(anyMatcher))); - Date expirationDate = new Date(System.currentTimeMillis() + 10000); - message = MessageBuilder.fromMessage(message).setExpirationDate(expirationDate).build(); - assertThat(message, hasExpirationDate(expirationDate)); - assertThat(message, hasExpirationDate(not(is((System.currentTimeMillis()))))); - } - -} diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java index 22ea872f7d..cae3e18db4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,7 @@ package org.springframework.integration.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -60,12 +59,12 @@ public class MessageBuilderAtConfigTests { @Test public void mutate() { - assertTrue(messageBuilderFactory instanceof MutableMessageBuilderFactory); + assertThat(messageBuilderFactory instanceof MutableMessageBuilderFactory).isTrue(); in.send(new GenericMessage("foo")); Message m1 = out.receive(0); Message m2 = out.receive(0); - assertEquals("org.springframework.integration.support.MutableMessage", m1.getClass().getName()); - assertTrue(m1 == m2); + assertThat(m1.getClass().getName()).isEqualTo("org.springframework.integration.support.MutableMessage"); + assertThat(m1 == m2).isTrue(); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java index 44e8cd08f9..c8f76f629d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,15 +16,7 @@ package org.springframework.integration.message; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeaderKey; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; import java.util.HashMap; @@ -75,7 +67,7 @@ public class MessageBuilderTests { @Test public void testSimpleMessageCreation() { Message message = MessageBuilder.withPayload("foo").build(); - assertEquals("foo", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("foo"); } @Test @@ -84,8 +76,8 @@ public class MessageBuilderTests { .setHeader("foo", "bar") .setHeader("count", 123) .build(); - assertEquals("bar", message.getHeaders().get("foo", String.class)); - assertEquals(new Integer(123), message.getHeaders().get("count", Integer.class)); + assertThat(message.getHeaders().get("foo", String.class)).isEqualTo("bar"); + assertThat(message.getHeaders().get("count", Integer.class)).isEqualTo(new Integer(123)); } @Test @@ -99,12 +91,12 @@ public class MessageBuilderTests { .setHeader("foo", "42") .setHeaderIfAbsent("bar", "99") .build(); - assertEquals("test1", message1.getPayload()); - assertEquals("test2", message2.getPayload()); - assertEquals("1", message1.getHeaders().get("foo")); - assertEquals("42", message2.getHeaders().get("foo")); - assertEquals("2", message1.getHeaders().get("bar")); - assertEquals("2", message2.getHeaders().get("bar")); + assertThat(message1.getPayload()).isEqualTo("test1"); + assertThat(message2.getPayload()).isEqualTo("test2"); + assertThat(message1.getHeaders().get("foo")).isEqualTo("1"); + assertThat(message2.getHeaders().get("foo")).isEqualTo("42"); + assertThat(message1.getHeaders().get("bar")).isEqualTo("2"); + assertThat(message2.getHeaders().get("bar")).isEqualTo("2"); } @Test(expected = IllegalArgumentException.class) @@ -127,8 +119,8 @@ public class MessageBuilderTests { .setHeader("foo", 123) .copyHeadersIfAbsent(message1.getHeaders()) .build(); - assertEquals("test2", message2.getPayload()); - assertEquals(123, message2.getHeaders().get("foo")); + assertThat(message2.getPayload()).isEqualTo("test2"); + assertThat(message2.getHeaders().get("foo")).isEqualTo(123); } @Test @@ -136,8 +128,8 @@ public class MessageBuilderTests { Message message1 = MessageBuilder.withPayload("test") .setHeader("foo", "bar").build(); Message message2 = MessageBuilder.fromMessage(message1).build(); - assertEquals("test", message2.getPayload()); - assertEquals("bar", message2.getHeaders().get("foo")); + assertThat(message2.getPayload()).isEqualTo("test"); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -145,18 +137,18 @@ public class MessageBuilderTests { Message message1 = MessageBuilder.withPayload("test") .setHeader("foo", "bar").build(); Message message2 = MessageBuilder.fromMessage(message1).setHeader("another", 1).build(); - assertEquals("bar", message2.getHeaders().get("foo")); - assertNotSame(message1.getHeaders().getId(), message2.getHeaders().getId()); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(message2.getHeaders().getId()).isNotSameAs(message1.getHeaders().getId()); } @Test public void mutate() { - assertTrue(this.messageBuilderFactory instanceof MutableMessageBuilderFactory); + assertThat(this.messageBuilderFactory instanceof MutableMessageBuilderFactory).isTrue(); in.send(new GenericMessage<>("foo")); Message m1 = out.receive(0); Message m2 = out.receive(0); - assertThat(m1, instanceOf(MutableMessage.class)); - assertTrue(m1 == m2); + assertThat(m1).isInstanceOf(MutableMessage.class); + assertThat(m1 == m2).isTrue(); } @Test @@ -165,9 +157,9 @@ public class MessageBuilderTests { Message message1 = builder .setHeader("foo", "bar").build(); Message message2 = MutableMessageBuilder.fromMessage(message1).setHeader("another", 1).build(); - assertEquals("bar", message2.getHeaders().get("foo")); - assertSame(message1.getHeaders().getId(), message2.getHeaders().getId()); - assertTrue(message2 == message1); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(message2.getHeaders().getId()).isSameAs(message1.getHeaders().getId()); + assertThat(message2 == message1).isTrue(); } @Test @@ -175,28 +167,29 @@ public class MessageBuilderTests { Message message1 = MessageBuilder.withPayload("test") .setHeader("foo", "bar").build(); Message message2 = MutableMessageBuilder.fromMessage(message1).setHeader("another", 1).build(); - assertEquals("bar", message2.getHeaders().get("foo")); - assertSame(message1.getHeaders().getId(), message2.getHeaders().getId()); - assertNotSame(message1, message2); - assertFalse(message2 == message1); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(message2.getHeaders().getId()).isSameAs(message1.getHeaders().getId()); + assertThat(message2).isNotSameAs(message1); + assertThat(message2 == message1).isFalse(); } @Test public void mutableFromImmutableMutate() { Message message1 = MessageBuilder.withPayload("test") .setHeader("foo", "bar").build(); - Message message2 = new MutableMessageBuilderFactory().fromMessage(message1).setHeader("another", 1).build(); - assertEquals("bar", message2.getHeaders().get("foo")); - assertSame(message1.getHeaders().getId(), message2.getHeaders().getId()); - assertNotSame(message1, message2); - assertFalse(message2 == message1); + Message message2 = new MutableMessageBuilderFactory().fromMessage(message1).setHeader("another", 1) + .build(); + assertThat(message2.getHeaders().get("foo")).isEqualTo("bar"); + assertThat(message2.getHeaders().getId()).isSameAs(message1.getHeaders().getId()); + assertThat(message2).isNotSameAs(message1); + assertThat(message2 == message1).isFalse(); } @Test public void testPriority() { Message importantMessage = MessageBuilder.withPayload(1) .setPriority(123).build(); - assertEquals(new Integer(123), new IntegrationMessageHeaderAccessor(importantMessage).getPriority()); + assertThat(new IntegrationMessageHeaderAccessor(importantMessage).getPriority()).isEqualTo(new Integer(123)); } @Test @@ -206,7 +199,7 @@ public class MessageBuilderTests { Message message2 = MessageBuilder.fromMessage(message1) .setHeaderIfAbsent(IntegrationMessageHeaderAccessor.PRIORITY, 13) .build(); - assertEquals(new Integer(42), new IntegrationMessageHeaderAccessor(message2).getPriority()); + assertThat(new IntegrationMessageHeaderAccessor(message2).getPriority()).isEqualTo(new Integer(42)); } @Test @@ -214,7 +207,7 @@ public class MessageBuilderTests { Long past = System.currentTimeMillis() - (60 * 1000); Message expiredMessage = MessageBuilder.withPayload(1) .setExpirationDate(past).build(); - assertEquals(past, new IntegrationMessageHeaderAccessor(expiredMessage).getExpirationDate()); + assertThat(new IntegrationMessageHeaderAccessor(expiredMessage).getExpirationDate()).isEqualTo(past); } @Test @@ -222,7 +215,7 @@ public class MessageBuilderTests { Long past = System.currentTimeMillis() - (60 * 1000); Message expiredMessage = MessageBuilder.withPayload(1) .setExpirationDate(new Date(past)).build(); - assertEquals(past, new IntegrationMessageHeaderAccessor(expiredMessage).getExpirationDate()); + assertThat(new IntegrationMessageHeaderAccessor(expiredMessage).getExpirationDate()).isEqualTo(past); } @Test @@ -232,7 +225,7 @@ public class MessageBuilderTests { Message message2 = MessageBuilder.fromMessage(message1) .removeHeader("foo") .build(); - assertFalse(message2.getHeaders().containsKey("foo")); + assertThat(message2.getHeaders().containsKey("foo")).isFalse(); } @Test @@ -242,119 +235,123 @@ public class MessageBuilderTests { Message message2 = MessageBuilder.fromMessage(message1) .setHeader("foo", null) .build(); - assertFalse(message2.getHeaders().containsKey("foo")); + assertThat(message2.getHeaders().containsKey("foo")).isFalse(); } @Test - public void testPushAndPopSequenceDetails() throws Exception { + public void testPushAndPopSequenceDetails() { Message message1 = MessageBuilder.withPayload(1).pushSequenceDetails("foo", 1, 2).build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); Message message2 = MessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1).build(); - assertTrue(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isTrue(); Message message3 = MessageBuilder.fromMessage(message2).popSequenceDetails().build(); - assertFalse(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testPushAndPopSequenceDetailsWhenNoCorrelationId() throws Exception { + public void testPushAndPopSequenceDetailsWhenNoCorrelationId() { Message message1 = MessageBuilder.withPayload(1).build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); Message message2 = MessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1).build(); - assertFalse(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); Message message3 = MessageBuilder.fromMessage(message2).popSequenceDetails().build(); - assertFalse(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testPopSequenceDetailsWhenNotPopped() throws Exception { + public void testPopSequenceDetailsWhenNotPopped() { Message message1 = MessageBuilder.withPayload(1).build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); Message message2 = MessageBuilder.fromMessage(message1).popSequenceDetails().build(); - assertFalse(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testPushAndPopSequenceDetailsWhenNoSequence() throws Exception { + public void testPushAndPopSequenceDetailsWhenNoSequence() { Message message1 = MessageBuilder.withPayload(1).setCorrelationId("foo").build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); Message message2 = MessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1).build(); - assertTrue(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isTrue(); Message message3 = MessageBuilder.fromMessage(message2).popSequenceDetails().build(); - assertFalse(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testPushAndPopSequenceDetailsMutable() throws Exception { + public void testPushAndPopSequenceDetailsMutable() { Message message1 = MutableMessageBuilder.withPayload(1).pushSequenceDetails("foo", 1, 2).build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); - Message message2 = MutableMessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1).build(); - assertTrue(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); + Message message2 = MutableMessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1) + .build(); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isTrue(); Message message3 = MutableMessageBuilder.fromMessage(message2).popSequenceDetails().build(); - assertFalse(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testPushAndPopSequenceDetailsWhenNoCorrelationIdMutable() throws Exception { + public void testPushAndPopSequenceDetailsWhenNoCorrelationIdMutable() { Message message1 = MutableMessageBuilder.withPayload(1).build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); - Message message2 = MutableMessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1).build(); - assertFalse(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); + Message message2 = MutableMessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1) + .build(); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); Message message3 = MutableMessageBuilder.fromMessage(message2).popSequenceDetails().build(); - assertFalse(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testPopSequenceDetailsWhenNotPoppedMutable() throws Exception { + public void testPopSequenceDetailsWhenNotPoppedMutable() { Message message1 = MutableMessageBuilder.withPayload(1).build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); Message message2 = MutableMessageBuilder.fromMessage(message1).popSequenceDetails().build(); - assertFalse(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testPushAndPopSequenceDetailsWhenNoSequenceMutable() throws Exception { + public void testPushAndPopSequenceDetailsWhenNoSequenceMutable() { Message message1 = MutableMessageBuilder.withPayload(1).setCorrelationId("foo").build(); - assertFalse(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); - Message message2 = MutableMessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1).build(); - assertTrue(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); + Message message2 = MutableMessageBuilder.fromMessage(message1).pushSequenceDetails("bar", 1, 1) + .build(); + assertThat(message2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isTrue(); Message message3 = MutableMessageBuilder.fromMessage(message2).popSequenceDetails().build(); - assertFalse(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertThat(message3.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)).isFalse(); } @Test - public void testNotModifiedSameMessage() throws Exception { + public void testNotModifiedSameMessage() { Message original = MessageBuilder.withPayload("foo").build(); Message result = MessageBuilder.fromMessage(original).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test - public void testContainsHeaderNotModifiedSameMessage() throws Exception { + public void testContainsHeaderNotModifiedSameMessage() { Message original = MessageBuilder.withPayload("foo").setHeader("bar", 42).build(); Message result = MessageBuilder.fromMessage(original).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test - public void testSameHeaderValueAddedNotModifiedSameMessage() throws Exception { + public void testSameHeaderValueAddedNotModifiedSameMessage() { Message original = MessageBuilder.withPayload("foo").setHeader("bar", 42).build(); Message result = MessageBuilder.fromMessage(original).setHeader("bar", 42).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test - public void testCopySameHeaderValuesNotModifiedSameMessage() throws Exception { + public void testCopySameHeaderValuesNotModifiedSameMessage() { Date current = new Date(); - Map originalHeaders = new HashMap(); + Map originalHeaders = new HashMap<>(); originalHeaders.put("b", "xyz"); originalHeaders.put("c", current); - Message original = MessageBuilder.withPayload("foo").setHeader("a", 123).copyHeaders(originalHeaders).build(); - Map newHeaders = new HashMap(); + Message original = MessageBuilder.withPayload("foo").setHeader("a", 123).copyHeaders(originalHeaders) + .build(); + Map newHeaders = new HashMap<>(); newHeaders.put("a", 123); newHeaders.put("b", "xyz"); newHeaders.put("c", current); Message result = MessageBuilder.fromMessage(original).copyHeaders(newHeaders).build(); - assertEquals(original, result); + assertThat(result).isEqualTo(original); } @Test @@ -374,12 +371,13 @@ public class MessageBuilderTests { .pushSequenceDetails("bar", 1, 1) .build(); - assertThat(message, hasHeaderKey(IntegrationMessageHeaderAccessor.CORRELATION_ID)); - assertThat(message, hasHeaderKey(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)); - assertThat(message, hasHeaderKey(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertThat(message, not(hasHeaderKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS))); - assertThat(message, not(hasHeaderKey(MessageHeaders.ID))); - assertThat(message, not(hasHeaderKey(MessageHeaders.TIMESTAMP))); + assertThat(message.getHeaders()) + .containsKeys(IntegrationMessageHeaderAccessor.CORRELATION_ID, + IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, + IntegrationMessageHeaderAccessor.SEQUENCE_SIZE) + .doesNotContainKeys(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS, + MessageHeaders.ID, + MessageHeaders.TIMESTAMP); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java index 0463c724cd..c1593956a1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -42,7 +38,7 @@ public class MessageHeadersTests { @Test public void testTimestamp() { MessageHeaders headers = new MessageHeaders(null); - assertNotNull(headers.getTimestamp()); + assertThat(headers.getTimestamp()).isNotNull(); } @Test @@ -50,20 +46,20 @@ public class MessageHeadersTests { MessageHeaders headers1 = new MessageHeaders(null); Thread.sleep(50L); MessageHeaders headers2 = new MessageHeaders(headers1); - assertNotSame(headers1.getTimestamp(), headers2.getTimestamp()); + assertThat(headers2.getTimestamp()).isNotSameAs(headers1.getTimestamp()); } @Test public void testIdOverwritten() throws Exception { MessageHeaders headers1 = new MessageHeaders(null); MessageHeaders headers2 = new MessageHeaders(headers1); - assertNotSame(headers1.getId(), headers2.getId()); + assertThat(headers2.getId()).isNotSameAs(headers1.getId()); } @Test public void testId() { MessageHeaders headers = new MessageHeaders(null); - assertNotNull(headers.getId()); + assertThat(headers.getId()).isNotNull(); } @Test @@ -72,7 +68,7 @@ public class MessageHeadersTests { Map map = new HashMap(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); - assertEquals(value, headers.get("test")); + assertThat(headers.get("test")).isEqualTo(value); } @Test @@ -81,7 +77,7 @@ public class MessageHeadersTests { Map map = new HashMap(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); - assertEquals(value, headers.get("test", Integer.class)); + assertThat(headers.get("test", Integer.class)).isEqualTo(value); } @Test(expected = IllegalArgumentException.class) @@ -90,21 +86,21 @@ public class MessageHeadersTests { Map map = new HashMap(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); - assertEquals(value, headers.get("test", String.class)); + assertThat(headers.get("test", String.class)).isEqualTo(value); } @Test public void testNullHeaderValue() { Map map = new HashMap(); MessageHeaders headers = new MessageHeaders(map); - assertNull(headers.get("nosuchattribute")); + assertThat(headers.get("nosuchattribute")).isNull(); } @Test public void testNullHeaderValueWithTypedAccess() { Map map = new HashMap(); MessageHeaders headers = new MessageHeaders(map); - assertNull(headers.get("nosuchattribute", String.class)); + assertThat(headers.get("nosuchattribute", String.class)).isNull(); } @Test @@ -114,8 +110,8 @@ public class MessageHeadersTests { map.put("key2", new Integer(123)); MessageHeaders headers = new MessageHeaders(map); Set keys = headers.keySet(); - assertTrue(keys.contains("key1")); - assertTrue(keys.contains("key2")); + assertThat(keys.contains("key1")).isTrue(); + assertThat(keys.contains("key2")).isTrue(); } @Test @@ -125,8 +121,8 @@ public class MessageHeadersTests { map.put("age", 42); MessageHeaders input = new MessageHeaders(map); MessageHeaders output = (MessageHeaders) serializeAndDeserialize(input); - assertEquals("joe", output.get("name")); - assertEquals(42, output.get("age")); + assertThat(output.get("name")).isEqualTo("joe"); + assertThat(output.get("age")).isEqualTo(42); } @Test @@ -137,8 +133,8 @@ public class MessageHeadersTests { map.put("address", address); MessageHeaders input = new MessageHeaders(map); MessageHeaders output = (MessageHeaders) serializeAndDeserialize(input); - assertEquals("joe", output.get("name")); - assertNull(output.get("address")); + assertThat(output.get("name")).isEqualTo("joe"); + assertThat(output.get("address")).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java index 939ab974dd..cc4f798949 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java @@ -16,9 +16,7 @@ package org.springframework.integration.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.concurrent.BlockingQueue; @@ -66,7 +64,7 @@ public class MethodInvokingMessageHandlerTests { handler.handleMessage(message); } catch (MessagingException e) { - assertEquals(e.getFailedMessage(), message); + assertThat(message).isEqualTo(e.getFailedMessage()); throw e; } } @@ -85,7 +83,7 @@ public class MethodInvokingMessageHandlerTests { context.registerChannel("channel", channel); Message message = new GenericMessage<>("testing"); channel.send(message); - assertNull(queue.poll()); + assertThat(queue.poll()).isNull(); MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(testBean, "foo"); handler.setBeanFactory(context); PollingConsumer endpoint = new PollingConsumer(channel, handler); @@ -93,8 +91,8 @@ public class MethodInvokingMessageHandlerTests { context.registerEndpoint("testEndpoint", endpoint); context.refresh(); String result = queue.poll(2000, TimeUnit.MILLISECONDS); - assertNotNull(result); - assertEquals("testing", result); + assertThat(result).isNotNull(); + assertThat(result).isEqualTo("testing"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java index 769012325c..e9e509fc4e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.HashMap; @@ -47,9 +45,9 @@ public class MethodInvokingMessageSourceTests { source.setObject(new TestBean()); source.setMethodName("validMethod"); Message result = source.receive(); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals("valid", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload()).isEqualTo("valid"); } @Test @@ -63,11 +61,11 @@ public class MethodInvokingMessageSourceTests { source.setMethodName("validMethod"); source.setHeaderExpressions(headerExpressions); Message result = source.receive(); - assertNotNull(result); - assertNotNull(result.getPayload()); - assertEquals("valid", result.getPayload()); - assertEquals("abc", result.getHeaders().get("foo")); - assertEquals(123, result.getHeaders().get("bar")); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isNotNull(); + assertThat(result.getPayload()).isEqualTo("valid"); + assertThat(result.getHeaders().get("foo")).isEqualTo("abc"); + assertThat(result.getHeaders().get("bar")).isEqualTo(123); } @Test(expected = MessagingException.class) @@ -104,7 +102,7 @@ public class MethodInvokingMessageSourceTests { source.setObject(new TestBean()); source.setMethodName("nullReturningMethod"); Message message = source.receive(); - assertNull(message); + assertThat(message).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java index 5a4be93fa7..6d0bdc8bba 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.message; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.HashMap; @@ -81,9 +77,9 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); // assertFalse(bean.lastHeaders.containsKey("baz")); } @@ -97,9 +93,9 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); //assertFalse(bean.lastHeaders.containsKey("baz")); } @@ -113,10 +109,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -129,10 +125,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -146,9 +142,9 @@ public class PayloadAndHeaderMappingTests { headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertFalse(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isFalse(); } @Test @@ -163,10 +159,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", "3"); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertFalse(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isFalse(); } @Test @@ -180,16 +176,16 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertEquals("1", bean.lastHeaders.get("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertEquals("2", bean.lastHeaders.get("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); - assertTrue(bean.lastHeaders.containsKey("foo2")); - assertEquals("1", bean.lastHeaders.get("foo2")); - assertTrue(bean.lastHeaders.containsKey("bar2")); - assertEquals("2", bean.lastHeaders.get("bar2")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.get("bar")).isEqualTo("2"); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); + assertThat(bean.lastHeaders.containsKey("foo2")).isTrue(); + assertThat(bean.lastHeaders.get("foo2")).isEqualTo("1"); + assertThat(bean.lastHeaders.containsKey("bar2")).isTrue(); + assertThat(bean.lastHeaders.get("bar2")).isEqualTo("2"); } @Test @@ -204,10 +200,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -222,10 +218,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -238,10 +234,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).as(payload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -256,10 +252,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -270,8 +266,8 @@ public class PayloadAndHeaderMappingTests { Map headers = new HashMap(); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertNull(bean.lastHeaders); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders).isNull(); } @Test @@ -284,10 +280,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -300,10 +296,10 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("baz")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("baz")).isTrue(); } @Test @@ -314,8 +310,8 @@ public class PayloadAndHeaderMappingTests { Map headers = new HashMap(); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertNull(bean.lastHeaders); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders).isNull(); } @Test @@ -326,8 +322,8 @@ public class PayloadAndHeaderMappingTests { Map headers = new HashMap(); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertNull(bean.lastHeaders); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders).isNull(); } @Test @@ -339,13 +335,13 @@ public class PayloadAndHeaderMappingTests { headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastHeaders); + assertThat(bean.lastHeaders).isNull(); // String payload should have been converted to Properties - assertNotNull(bean.lastPayload); - assertTrue(bean.lastPayload instanceof Properties); + assertThat(bean.lastPayload).isNotNull(); + assertThat(bean.lastPayload instanceof Properties).isTrue(); Properties payloadProps = (Properties) bean.lastPayload; - assertTrue(payloadProps.containsKey("payload")); - assertEquals("abc", payloadProps.get("payload")); + assertThat(payloadProps.containsKey("payload")).isTrue(); + assertThat(payloadProps.get("payload")).isEqualTo("abc"); } @Test @@ -357,9 +353,9 @@ public class PayloadAndHeaderMappingTests { headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); } @Test @@ -372,9 +368,9 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); //assertFalse(bean.lastHeaders.containsKey("baz")); } @@ -390,9 +386,9 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); //assertFalse(bean.lastHeaders.containsKey("baz")); } @@ -408,9 +404,9 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); //assertFalse(bean.lastHeaders.containsKey("baz")); } @@ -426,9 +422,9 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); //assertFalse(bean.lastHeaders.containsKey("baz")); } @@ -445,12 +441,12 @@ public class PayloadAndHeaderMappingTests { headers.put("baz", 99); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals(payload, bean.lastPayload); - assertTrue(bean.lastHeaders.containsKey("foo")); - assertEquals("1", bean.lastHeaders.get("foo")); - assertTrue(bean.lastHeaders.containsKey("bar")); - assertTrue(bean.lastHeaders.containsKey("foo2")); - assertEquals("1", bean.lastHeaders.get("foo2")); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.containsKey("foo")).isTrue(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.containsKey("bar")).isTrue(); + assertThat(bean.lastHeaders.containsKey("foo2")).isTrue(); + assertThat(bean.lastHeaders.get("foo2")).isEqualTo("1"); //assertFalse(bean.lastHeaders.containsKey("baz")); } @@ -467,11 +463,11 @@ public class PayloadAndHeaderMappingTests { headers.put("bar", "2"); Message message = MessageBuilder.withPayload("test").copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals("1", bean.lastHeaders.get("foo")); - assertEquals("2", bean.lastHeaders.get("bar")); - assertEquals("1", bean.lastHeaders.get("foo2")); - assertEquals("2", bean.lastHeaders.get("bar2")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar")).isEqualTo("2"); + assertThat(bean.lastHeaders.get("foo2")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar2")).isEqualTo("2"); } @Test @@ -484,11 +480,11 @@ public class PayloadAndHeaderMappingTests { payloadMap.put("baz", "99"); Message message = MessageBuilder.withPayload(payloadMap).copyHeaders(headers).build(); handler.handleMessage(message); - assertEquals("1", bean.lastHeaders.get("foo")); - assertEquals("2", bean.lastHeaders.get("bar")); - assertEquals("1", bean.lastHeaders.get("foo2")); - assertEquals("2", bean.lastHeaders.get("bar2")); - assertEquals(null, bean.lastHeaders.get("baz")); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar")).isEqualTo("2"); + assertThat(bean.lastHeaders.get("foo2")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar2")).isEqualTo("2"); + assertThat(bean.lastHeaders.get("baz")).isEqualTo(null); } @Test(expected = IllegalStateException.class) @@ -523,10 +519,10 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload("test") .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals("1", bean.lastHeaders.get("foo")); - assertEquals("2", bean.lastHeaders.get("bar")); - assertEquals("1", bean.lastHeaders.get("foo2")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar")).isEqualTo("2"); + assertThat(bean.lastHeaders.get("foo2")).isEqualTo("1"); } @Test @@ -541,10 +537,10 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(payload) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNotNull(bean.lastPayload); - assertEquals(payload, bean.lastPayload); - assertEquals("1", bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNotNull(); + assertThat(bean.lastPayload).isEqualTo(payload); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -556,9 +552,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload("test") .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals("1", bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -570,9 +566,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(new Integer(123)) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals("1", bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -586,9 +582,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(payload) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals("1", bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("1"); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -600,9 +596,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(new Integer(789)) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals(new Integer(123), bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -614,9 +610,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(new Integer(789)) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals(new Integer(999), bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(999)); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -628,9 +624,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload("test") .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals(new Integer(123), bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -642,9 +638,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload("test") .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals("123", bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("123"); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -656,9 +652,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(new Object()) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals("123", bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo("123"); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -670,9 +666,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(new Integer(789)) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals(new Integer(123), bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -686,9 +682,9 @@ public class PayloadAndHeaderMappingTests { Message message = MessageBuilder.withPayload(payload) .copyHeaders(headers).build(); handler.handleMessage(message); - assertNull(bean.lastPayload); - assertEquals(new Integer(123), bean.lastHeaders.get("foo")); - assertNull(bean.lastHeaders.get("bar")); + assertThat(bean.lastPayload).isNull(); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test @@ -699,9 +695,9 @@ public class PayloadAndHeaderMappingTests { payload.put("bar", 456); Message message = MessageBuilder.withPayload(payload).build(); handler.handleMessage(message); - assertNull(bean.lastHeaders); - assertNotNull(bean.lastPayload); - assertEquals("123456", bean.lastPayload); + assertThat(bean.lastHeaders).isNull(); + assertThat(bean.lastPayload).isNotNull(); + assertThat(bean.lastPayload).isEqualTo("123456"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/selector/PayloadTypeSelectorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/selector/PayloadTypeSelectorTests.java index e28830ec7d..5848332a4b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/selector/PayloadTypeSelectorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/selector/PayloadTypeSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.message.selector; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -35,33 +34,33 @@ public class PayloadTypeSelectorTests { @Test public void testAcceptedTypeIsSelected() { PayloadTypeSelector selector = new PayloadTypeSelector(String.class); - assertTrue(selector.accept(new GenericMessage<>("test"))); + assertThat(selector.accept(new GenericMessage<>("test"))).isTrue(); } @Test public void testNonAcceptedTypeIsNotSelected() { PayloadTypeSelector selector = new PayloadTypeSelector(Integer.class); - assertFalse(selector.accept(new GenericMessage<>("test"))); + assertThat(selector.accept(new GenericMessage<>("test"))).isFalse(); } @Test public void testMultipleAcceptedTypes() { PayloadTypeSelector selector = new PayloadTypeSelector(String.class, Integer.class); - assertTrue(selector.accept(new GenericMessage<>("test1"))); - assertTrue(selector.accept(new GenericMessage<>(2))); - assertFalse(selector.accept(new ErrorMessage(new RuntimeException()))); + assertThat(selector.accept(new GenericMessage<>("test1"))).isTrue(); + assertThat(selector.accept(new GenericMessage<>(2))).isTrue(); + assertThat(selector.accept(new ErrorMessage(new RuntimeException()))).isFalse(); } @Test public void testSubclassOfAcceptedTypeIsSelected() { PayloadTypeSelector selector = new PayloadTypeSelector(RuntimeException.class); - assertTrue(selector.accept(new ErrorMessage(new MessagingException("test")))); + assertThat(selector.accept(new ErrorMessage(new MessagingException("test")))).isTrue(); } @Test public void testSuperclassOfAcceptedTypeIsNotSelected() { PayloadTypeSelector selector = new PayloadTypeSelector(RuntimeException.class); - assertFalse(selector.accept(new ErrorMessage(new Exception("test")))); + assertThat(selector.accept(new ErrorMessage(new Exception("test")))).isFalse(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/selector/UnexpiredMessageSelectorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/selector/UnexpiredMessageSelectorTests.java index ec48ffd5d1..5fbe1bd1f7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/selector/UnexpiredMessageSelectorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/selector/UnexpiredMessageSelectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.message.selector; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -37,7 +36,7 @@ public class UnexpiredMessageSelectorTests { Message message = MessageBuilder.withPayload("expired") .setExpirationDate(past).build(); UnexpiredMessageSelector selector = new UnexpiredMessageSelector(); - assertFalse(selector.accept(message)); + assertThat(selector.accept(message)).isFalse(); } @Test @@ -46,14 +45,14 @@ public class UnexpiredMessageSelectorTests { Message message = MessageBuilder.withPayload("unexpired") .setExpirationDate(future).build(); UnexpiredMessageSelector selector = new UnexpiredMessageSelector(); - assertTrue(selector.accept(message)); + assertThat(selector.accept(message)).isTrue(); } @Test public void testMessageWithNullExpirationDateNeverExpires() { Message message = MessageBuilder.withPayload("unexpired").build(); UnexpiredMessageSelector selector = new UnexpiredMessageSelector(); - assertTrue(selector.accept(message)); + assertThat(selector.accept(message)).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/metadata/PropertiesPersistingMetadataStoreTests.java b/spring-integration-core/src/test/java/org/springframework/integration/metadata/PropertiesPersistingMetadataStoreTests.java index ad530a2433..4573b6a1d0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/metadata/PropertiesPersistingMetadataStoreTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/metadata/PropertiesPersistingMetadataStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.metadata; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Properties; @@ -50,16 +46,16 @@ public class PropertiesPersistingMetadataStoreTests { file.delete(); PropertiesPersistingMetadataStore metadataStore = new PropertiesPersistingMetadataStore(); metadataStore.afterPropertiesSet(); - assertTrue(file.exists()); - assertNull(metadataStore.putIfAbsent("foo", "baz")); - assertNotNull(metadataStore.putIfAbsent("foo", "baz")); - assertFalse(metadataStore.replace("foo", "xxx", "bar")); - assertTrue(metadataStore.replace("foo", "baz", "bar")); + assertThat(file.exists()).isTrue(); + assertThat(metadataStore.putIfAbsent("foo", "baz")).isNull(); + assertThat(metadataStore.putIfAbsent("foo", "baz")).isNotNull(); + assertThat(metadataStore.replace("foo", "xxx", "bar")).isFalse(); + assertThat(metadataStore.replace("foo", "baz", "bar")).isTrue(); metadataStore.close(); Properties persistentProperties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(file)); - assertNotNull(persistentProperties); - assertEquals(1, persistentProperties.size()); - assertEquals("bar", persistentProperties.get("foo")); + assertThat(persistentProperties).isNotNull(); + assertThat(persistentProperties.size()).isEqualTo(1); + assertThat(persistentProperties.get("foo")).isEqualTo("bar"); file.delete(); } @@ -71,11 +67,11 @@ public class PropertiesPersistingMetadataStoreTests { metadataStore.afterPropertiesSet(); metadataStore.put("foo", "bar"); metadataStore.close(); - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); Properties persistentProperties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(file)); - assertNotNull(persistentProperties); - assertEquals(1, persistentProperties.size()); - assertEquals("bar", persistentProperties.get("foo")); + assertThat(persistentProperties).isNotNull(); + assertThat(persistentProperties.size()).isEqualTo(1); + assertThat(persistentProperties.get("foo")).isEqualTo("bar"); } @Test @@ -87,11 +83,11 @@ public class PropertiesPersistingMetadataStoreTests { metadataStore.afterPropertiesSet(); metadataStore.put("foo", "bar"); metadataStore.close(); - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); Properties persistentProperties = PropertiesLoaderUtils.loadProperties(new FileSystemResource(file)); - assertNotNull(persistentProperties); - assertEquals(1, persistentProperties.size()); - assertEquals("bar", persistentProperties.get("foo")); + assertThat(persistentProperties).isNotNull(); + assertThat(persistentProperties.size()).isEqualTo(1); + assertThat(persistentProperties.get("foo")).isEqualTo("bar"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/resource/ResourceInboundChannelAdapterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/resource/ResourceInboundChannelAdapterParserTests.java index 2a1ac5b0cb..2b34d6b1b1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/resource/ResourceInboundChannelAdapterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/resource/ResourceInboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.resource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Collection; @@ -79,12 +75,12 @@ public class ResourceInboundChannelAdapterParserTests { SourcePollingChannelAdapter.class); ResourceRetrievingMessageSource source = TestUtils.getPropertyValue(resourceAdapter, "source", ResourceRetrievingMessageSource.class); - assertNotNull(source); + assertThat(source).isNotNull(); boolean autoStartup = TestUtils.getPropertyValue(resourceAdapter, "autoStartup", Boolean.class); - assertFalse(autoStartup); + assertThat(autoStartup).isFalse(); - assertEquals("/**/*", TestUtils.getPropertyValue(source, "pattern")); - assertEquals(context, TestUtils.getPropertyValue(source, "patternResolver")); + assertThat(TestUtils.getPropertyValue(source, "pattern")).isEqualTo("/**/*"); + assertThat(TestUtils.getPropertyValue(source, "patternResolver")).isEqualTo(context); } @Test(expected = BeanCreationException.class) @@ -100,8 +96,8 @@ public class ResourceInboundChannelAdapterParserTests { SourcePollingChannelAdapter.class); ResourceRetrievingMessageSource source = TestUtils.getPropertyValue(resourceAdapter, "source", ResourceRetrievingMessageSource.class); - assertNotNull(source); - assertEquals(context.getBean("customResolver"), TestUtils.getPropertyValue(source, "patternResolver")); + assertThat(source).isNotNull(); + assertThat(TestUtils.getPropertyValue(source, "patternResolver")).isEqualTo(context.getBean("customResolver")); context.close(); } @@ -118,10 +114,10 @@ public class ResourceInboundChannelAdapterParserTests { "ResourcePatternResolver-config-usage.xml", this.getClass()); QueueChannel resultChannel = context.getBean("resultChannel", QueueChannel.class); Message message = (Message) resultChannel.receive(10000); - assertNotNull(message); + assertThat(message).isNotNull(); Resource[] resources = message.getPayload(); for (Resource resource : resources) { - assertTrue(resource.getURI().toString().contains("testUsage")); + assertThat(resource.getURI().toString().contains("testUsage")).isTrue(); } context.close(); } @@ -141,16 +137,16 @@ public class ResourceInboundChannelAdapterParserTests { SourcePollingChannelAdapter.class); ResourceRetrievingMessageSource source = TestUtils.getPropertyValue(resourceAdapter, "source", ResourceRetrievingMessageSource.class); - assertNotNull(source); + assertThat(source).isNotNull(); TestCollectionFilter customFilter = context.getBean("customFilter", TestCollectionFilter.class); - assertEquals(customFilter, TestUtils.getPropertyValue(source, "filter")); + assertThat(TestUtils.getPropertyValue(source, "filter")).isEqualTo(customFilter); - assertFalse(customFilter.invoked); + assertThat(customFilter.invoked).isFalse(); resourceAdapter.start(); QueueChannel resultChannel = context.getBean("resultChannel", QueueChannel.class); Message message = (Message) resultChannel.receive(10000); - assertNotNull(message); - assertTrue(customFilter.invoked); + assertThat(message).isNotNull(); + assertThat(customFilter.invoked).isTrue(); context.close(); } @@ -168,8 +164,8 @@ public class ResourceInboundChannelAdapterParserTests { SourcePollingChannelAdapter.class); ResourceRetrievingMessageSource source = TestUtils.getPropertyValue(resourceAdapter, "source", ResourceRetrievingMessageSource.class); - assertNotNull(source); - assertNull(TestUtils.getPropertyValue(source, "filter")); + assertThat(source).isNotNull(); + assertThat(TestUtils.getPropertyValue(source, "filter")).isNull(); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java index 05c7f70bac..1970e78591 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,12 +16,8 @@ package org.springframework.integration.router; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.After; import org.junit.Before; @@ -91,10 +87,10 @@ public class ErrorMessageExceptionTypeRouterTests { router.handleMessage(message); - assertNotNull(illegalArgumentChannel.receive(1000)); - assertNull(defaultChannel.receive(0)); - assertNull(runtimeExceptionChannel.receive(0)); - assertNull(messageHandlingExceptionChannel.receive(0)); + assertThat(illegalArgumentChannel.receive(1000)).isNotNull(); + assertThat(defaultChannel.receive(0)).isNull(); + assertThat(runtimeExceptionChannel.receive(0)).isNull(); + assertThat(messageHandlingExceptionChannel.receive(0)).isNull(); } @Test @@ -114,10 +110,10 @@ public class ErrorMessageExceptionTypeRouterTests { router.handleMessage(message); - assertNotNull(runtimeExceptionChannel.receive(1000)); - assertNull(illegalArgumentChannel.receive(0)); - assertNull(defaultChannel.receive(0)); - assertNull(messageHandlingExceptionChannel.receive(0)); + assertThat(runtimeExceptionChannel.receive(1000)).isNotNull(); + assertThat(illegalArgumentChannel.receive(0)).isNull(); + assertThat(defaultChannel.receive(0)).isNull(); + assertThat(messageHandlingExceptionChannel.receive(0)).isNull(); } @Test @@ -136,10 +132,10 @@ public class ErrorMessageExceptionTypeRouterTests { router.handleMessage(message); - assertNotNull(messageHandlingExceptionChannel.receive(1000)); - assertNull(runtimeExceptionChannel.receive(0)); - assertNull(illegalArgumentChannel.receive(0)); - assertNull(defaultChannel.receive(0)); + assertThat(messageHandlingExceptionChannel.receive(1000)).isNotNull(); + assertThat(runtimeExceptionChannel.receive(0)).isNull(); + assertThat(illegalArgumentChannel.receive(0)).isNull(); + assertThat(defaultChannel.receive(0)).isNull(); } @Test @@ -156,10 +152,10 @@ public class ErrorMessageExceptionTypeRouterTests { router.handleMessage(message); - assertNotNull(defaultChannel.receive(1000)); - assertNull(runtimeExceptionChannel.receive(0)); - assertNull(illegalArgumentChannel.receive(0)); - assertNull(messageHandlingExceptionChannel.receive(0)); + assertThat(defaultChannel.receive(1000)).isNotNull(); + assertThat(runtimeExceptionChannel.receive(0)).isNull(); + assertThat(illegalArgumentChannel.receive(0)).isNull(); + assertThat(messageHandlingExceptionChannel.receive(0)).isNull(); } @Test @@ -181,8 +177,8 @@ public class ErrorMessageExceptionTypeRouterTests { fail("MessageDeliveryException expected"); } catch (Exception e) { - assertThat(e, instanceOf(MessageDeliveryException.class)); - assertThat(e.getMessage(), containsString("'fooRouter'")); + assertThat(e).isInstanceOf(MessageDeliveryException.class); + assertThat(e.getMessage()).contains("'fooRouter'"); } } @@ -204,10 +200,10 @@ public class ErrorMessageExceptionTypeRouterTests { router.handleMessage(message); - assertNotNull(illegalArgumentChannel.receive(1000)); - assertNull(defaultChannel.receive(0)); - assertNull(runtimeExceptionChannel.receive(0)); - assertNull(messageHandlingExceptionChannel.receive(0)); + assertThat(illegalArgumentChannel.receive(1000)).isNotNull(); + assertThat(defaultChannel.receive(0)).isNull(); + assertThat(runtimeExceptionChannel.receive(0)).isNull(); + assertThat(messageHandlingExceptionChannel.receive(0)).isNull(); } @Test @@ -227,10 +223,10 @@ public class ErrorMessageExceptionTypeRouterTests { router.handleMessage(message); - assertNotNull(illegalArgumentChannel.receive(1000)); - assertNull(defaultChannel.receive(0)); - assertNull(runtimeExceptionChannel.receive(0)); - assertNull(messageHandlingExceptionChannel.receive(0)); + assertThat(illegalArgumentChannel.receive(1000)).isNotNull(); + assertThat(defaultChannel.receive(0)).isNull(); + assertThat(runtimeExceptionChannel.receive(0)).isNull(); + assertThat(messageHandlingExceptionChannel.receive(0)).isNull(); } @Test @@ -248,8 +244,8 @@ public class ErrorMessageExceptionTypeRouterTests { router.handleMessage(message); - assertNotNull(messageHandlingExceptionChannel.receive(1000)); - assertNull(defaultChannel.receive(0)); + assertThat(messageHandlingExceptionChannel.receive(1000)).isNotNull(); + assertThat(defaultChannel.receive(0)).isNull(); } @Test @@ -262,8 +258,8 @@ public class ErrorMessageExceptionTypeRouterTests { fail("IllegalStateException expected"); } catch (Exception e) { - assertThat(e, instanceOf(IllegalStateException.class)); - assertThat(e.getCause(), instanceOf(ClassNotFoundException.class)); + assertThat(e).isInstanceOf(IllegalStateException.class); + assertThat(e.getCause()).isInstanceOf(ClassNotFoundException.class); } } @@ -272,7 +268,7 @@ public class ErrorMessageExceptionTypeRouterTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); ctx.getBean(ErrorMessageExceptionTypeRouter.class) .handleMessage(new GenericMessage<>(new NullPointerException())); - assertNotNull(ctx.getBean("channel", PollableChannel.class).receive(0)); + assertThat(ctx.getBean("channel", PollableChannel.class).receive(0)).isNotNull(); ctx.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java index 9af27bd1f7..f991798ee4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.router; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -54,8 +50,8 @@ public class HeaderValueRouterTests { Message message = MessageBuilder.withPayload("test").setHeader("testHeaderName", testChannel).build(); handler.handleMessage(message); Message result = testChannel.receive(1000); - assertNotNull(result); - assertSame(message, result); + assertThat(result).isNotNull(); + assertThat(result).isSameAs(message); context.close(); } @@ -74,8 +70,8 @@ public class HeaderValueRouterTests { handler.handleMessage(message); QueueChannel channel = (QueueChannel) context.getBean("testChannel"); Message result = channel.receive(1000); - assertNotNull(result); - assertSame(message, result); + assertThat(result).isNotNull(); + assertThat(result).isSameAs(message); // validate dynamics HeaderValueRouter router = (HeaderValueRouter) context.getBean("router"); @@ -83,13 +79,13 @@ public class HeaderValueRouterTests { router.handleMessage(message); QueueChannel newChannel = (QueueChannel) context.getBean("newChannel"); result = newChannel.receive(10); - assertNotNull(result); + assertThat(result).isNotNull(); router.removeChannelMapping("testChannel"); router.handleMessage(message); result = channel.receive(1000); - assertNotNull(result); - assertSame(message, result); + assertThat(result).isNotNull(); + assertThat(result).isSameAs(message); context.close(); } @@ -112,8 +108,8 @@ public class HeaderValueRouterTests { handler.handleMessage(message); QueueChannel channel = (QueueChannel) context.getBean("testChannel"); Message result = channel.receive(1000); - assertNotNull(result); - assertSame(message, result); + assertThat(result).isNotNull(); + assertThat(result).isSameAs(message); context.close(); } @@ -140,8 +136,8 @@ public class HeaderValueRouterTests { handler.handleMessage(message); QueueChannel channel = (QueueChannel) context.getBean("anotherChannel"); Message result = channel.receive(1000); - assertNotNull(result); - assertSame(message, result); + assertThat(result).isNotNull(); + assertThat(result).isSameAs(message); context.close(); } @@ -163,10 +159,10 @@ public class HeaderValueRouterTests { QueueChannel channel2 = (QueueChannel) context.getBean("channel2"); Message result1 = channel1.receive(1000); Message result2 = channel2.receive(1000); - assertNotNull(result1); - assertNotNull(result2); - assertSame(message, result1); - assertSame(message, result2); + assertThat(result1).isNotNull(); + assertThat(result2).isNotNull(); + assertThat(result1).isSameAs(message); + assertThat(result2).isSameAs(message); context.close(); } @@ -188,10 +184,10 @@ public class HeaderValueRouterTests { QueueChannel channel2 = (QueueChannel) context.getBean("channel2"); Message result1 = channel1.receive(1000); Message result2 = channel2.receive(1000); - assertNotNull(result1); - assertNotNull(result2); - assertSame(message, result1); - assertSame(message, result2); + assertThat(result1).isNotNull(); + assertThat(result2).isNotNull(); + assertThat(result1).isSameAs(message); + assertThat(result2).isSameAs(message); context.close(); } @@ -214,10 +210,11 @@ public class HeaderValueRouterTests { QueueChannel channel1 = (QueueChannel) context.getBean("channel1"); QueueChannel channel2 = (QueueChannel) context.getBean("channel2"); QueueChannel channel3 = (QueueChannel) context.getBean("channel3"); - assertThat(channel1.getQueueSize(), equalTo(2)); - assertThat(channel2.getQueueSize(), equalTo(1)); - assertThat(channel3.getQueueSize(), equalTo(1)); - assertThat(context.getBean(HeaderValueRouter.class).getDynamicChannelNames(), contains("channel1", "channel3")); + assertThat(channel1.getQueueSize()).isEqualTo(2); + assertThat(channel2.getQueueSize()).isEqualTo(1); + assertThat(channel3.getQueueSize()).isEqualTo(1); + assertThat(context.getBean(HeaderValueRouter.class).getDynamicChannelNames()) + .containsExactly("channel1", "channel3"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java index 77b4704c95..e48e83aeb7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java @@ -16,10 +16,8 @@ package org.springframework.integration.router; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; @@ -60,8 +58,8 @@ public class MethodInvokingRouterTests { Message message = new GenericMessage<>("bar"); router.handleMessage(message); Message replyMessage = barChannel.receive(); - assertNotNull(replyMessage); - assertEquals(message, replyMessage); + assertThat(replyMessage).isNotNull(); + assertThat(replyMessage).isEqualTo(message); } @Test @@ -77,8 +75,8 @@ public class MethodInvokingRouterTests { Message message = new GenericMessage<>("bar"); router.handleMessage(message); Message replyMessage = barChannel.receive(); - assertNotNull(replyMessage); - assertEquals(message, replyMessage); + assertThat(replyMessage).isNotNull(); + assertThat(replyMessage).isEqualTo(message); } @Test @@ -99,9 +97,9 @@ public class MethodInvokingRouterTests { router.handleMessage(message); Message fooReply = fooChannel.receive(0); Message barReply = barChannel.receive(0); - assertNotNull(fooReply); - assertNull(barReply); - assertEquals(message, fooReply); + assertThat(fooReply).isNotNull(); + assertThat(barReply).isNull(); + assertThat(fooReply).isEqualTo(message); } @Test(expected = MessagingException.class) @@ -141,21 +139,20 @@ public class MethodInvokingRouterTests { Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1 = fooChannel.receive(0); - assertNotNull(result1); - assertEquals("foo", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2 = barChannel.receive(0); - assertNotNull(result2); - assertEquals("bar", result2.getPayload()); + assertThat(result2).isNotNull(); + assertThat(result2.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ } - } @Test @@ -190,16 +187,16 @@ public class MethodInvokingRouterTests { router.setChannelResolver(channelResolver); router.handleMessage(fooMessage); Message result1 = fooChannel.receive(0); - assertNotNull(result1); - assertEquals("foo", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2 = barChannel.receive(0); - assertNotNull(result2); - assertEquals("bar", result2.getPayload()); + assertThat(result2).isNotNull(); + assertThat(result2.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -239,16 +236,16 @@ public class MethodInvokingRouterTests { Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1 = fooChannel.receive(0); - assertNotNull(result1); - assertEquals("foo", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2 = barChannel.receive(0); - assertNotNull(result2); - assertEquals("bar", result2.getPayload()); + assertThat(result2).isNotNull(); + assertThat(result2.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -289,21 +286,21 @@ public class MethodInvokingRouterTests { router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); Message result1b = barChannel.receive(0); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2a = fooChannel.receive(0); Message result2b = barChannel.receive(0); - assertNotNull(result2a); - assertEquals("bar", result2a.getPayload()); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2a).isNotNull(); + assertThat(result2a.getPayload()).isEqualTo("bar"); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -342,22 +339,22 @@ public class MethodInvokingRouterTests { Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); Message result1b = barChannel.receive(0); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2a = fooChannel.receive(0); - assertNotNull(result2a); - assertEquals("bar", result2a.getPayload()); + assertThat(result2a).isNotNull(); + assertThat(result2a.getPayload()).isEqualTo("bar"); Message result2b = barChannel.receive(0); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -396,22 +393,22 @@ public class MethodInvokingRouterTests { Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); Message result1b = barChannel.receive(0); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2a = fooChannel.receive(0); - assertNotNull(result2a); - assertEquals("bar", result2a.getPayload()); + assertThat(result2a).isNotNull(); + assertThat(result2a.getPayload()).isEqualTo("bar"); Message result2b = barChannel.receive(0); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -445,27 +442,27 @@ public class MethodInvokingRouterTests { channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); Message result1b = barChannel.receive(0); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2a = fooChannel.receive(0); Message result2b = barChannel.receive(0); - assertNotNull(result2a); - assertEquals("bar", result2a.getPayload()); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2a).isNotNull(); + assertThat(result2a.getPayload()).isEqualTo("bar"); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -500,27 +497,27 @@ public class MethodInvokingRouterTests { channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); Message result1b = barChannel.receive(0); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2a = fooChannel.receive(0); Message result2b = barChannel.receive(0); - assertNotNull(result2a); - assertEquals("bar", result2a.getPayload()); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2a).isNotNull(); + assertThat(result2a.getPayload()).isEqualTo("bar"); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -561,21 +558,21 @@ public class MethodInvokingRouterTests { router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); Message result1b = barChannel.receive(0); - assertNotNull(result1a); - assertEquals("foo", result1a.getPayload()); - assertNotNull(result1b); - assertEquals("foo", result1b.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("foo"); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("foo"); router.handleMessage(barMessage); Message result2a = fooChannel.receive(0); Message result2b = barChannel.receive(0); - assertNotNull(result2a); - assertEquals("bar", result2a.getPayload()); - assertNotNull(result2b); - assertEquals("bar", result2b.getPayload()); + assertThat(result2a).isNotNull(); + assertThat(result2a.getPayload()).isEqualTo("bar"); + assertThat(result2b).isNotNull(); + assertThat(result2b.getPayload()).isEqualTo("bar"); try { router.handleMessage(badMessage); - fail(); + fail("MessageDeliveryException expected"); } catch (MessageDeliveryException e) { /* Success */ @@ -600,14 +597,14 @@ public class MethodInvokingRouterTests { Message message = new GenericMessage<>("bar"); router.handleMessage(message); Message replyMessage = stringsChannel.receive(10000); - assertNotNull(replyMessage); - assertEquals(message, replyMessage); + assertThat(replyMessage).isNotNull(); + assertThat(replyMessage).isEqualTo(message); message = new GenericMessage<>(11); router.handleMessage(message); replyMessage = numbersChannel.receive(10000); - assertNotNull(replyMessage); - assertEquals(message, replyMessage); + assertThat(replyMessage).isNotNull(); + assertThat(replyMessage).isEqualTo(message); } @@ -637,7 +634,7 @@ public class MethodInvokingRouterTests { public static class MultiChannelNameRoutingTestBean { public List routePayload(String name) { - List results = new ArrayList(); + List results = new ArrayList<>(); if (name.equals("foo") || name.equals("bar")) { results.add("foo-channel"); results.add("bar-channel"); @@ -646,7 +643,7 @@ public class MethodInvokingRouterTests { } public List routeMessage(Message message) { - List results = new ArrayList(); + List results = new ArrayList<>(); if (message.getPayload().equals("foo") || message.getPayload().equals("bar")) { results.add("foo-channel"); results.add("bar-channel"); @@ -701,7 +698,7 @@ public class MethodInvokingRouterTests { } public List routePayload(String name) { - List results = new ArrayList(); + List results = new ArrayList<>(); if (name.equals("foo") || name.equals("bar")) { results.add(channelResolver.resolveDestination("foo-channel")); results.add(channelResolver.resolveDestination("bar-channel")); @@ -710,7 +707,7 @@ public class MethodInvokingRouterTests { } public List routeMessage(Message message) { - List results = new ArrayList(); + List results = new ArrayList<>(); if (message.getPayload().equals("foo") || message.getPayload().equals("bar")) { results.add(channelResolver.resolveDestination("foo-channel")); results.add(channelResolver.resolveDestination("bar-channel")); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/MultiChannelRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/MultiChannelRouterTests.java index 3bcbc6216a..b474296398 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/MultiChannelRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/MultiChannelRouterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.Arrays; @@ -57,11 +56,11 @@ public class MultiChannelRouterTests { Message message = new GenericMessage<>("test"); router.handleMessage(message); Message result1 = channel1.receive(25); - assertNotNull(result1); - assertEquals("test", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("test"); Message result2 = channel2.receive(25); - assertNotNull(result2); - assertEquals("test", result2.getPayload()); + assertThat(result2).isNotNull(); + assertThat(result2.getPayload()).isEqualTo("test"); } @Test(expected = MessagingException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/PayloadTypeRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/PayloadTypeRouterTests.java index b8dfcc399f..fd0d73a344 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/PayloadTypeRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/PayloadTypeRouterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,10 +16,8 @@ package org.springframework.integration.router; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.Serializable; import java.util.Map; @@ -58,27 +56,27 @@ public class PayloadTypeRouterTests { Message message1 = new GenericMessage<>("test"); Message message2 = new GenericMessage<>(123); - assertEquals(1, router.getChannelKeys(message1).size()); + assertThat(router.getChannelKeys(message1).size()).isEqualTo(1); - assertNull(stringChannel.receive(0)); + assertThat(stringChannel.receive(0)).isNull(); router.handleMessage(message1); - assertEquals(message1, stringChannel.receive(0)); + assertThat(stringChannel.receive(0)).isEqualTo(message1); - assertEquals(1, router.getChannelKeys(message2).size()); + assertThat(router.getChannelKeys(message2).size()).isEqualTo(1); - assertNull(integerChannel.receive(0)); + assertThat(integerChannel.receive(0)).isNull(); router.handleMessage(message2); - assertEquals(message2, integerChannel.receive(0)); + assertThat(integerChannel.receive(0)).isEqualTo(message2); // validate dynamics QueueChannel newChannel = new QueueChannel(); beanFactory.registerSingleton("newChannel", newChannel); router.setChannelMapping(String.class.getName(), "newChannel"); - assertEquals(1, router.getChannelKeys(message1).size()); + assertThat(router.getChannelKeys(message1).size()).isEqualTo(1); - assertNull(newChannel.receive(0)); + assertThat(newChannel.receive(0)).isNull(); router.handleMessage(message1); - assertEquals(message1, newChannel.receive(0)); + assertThat(newChannel.receive(0)).isEqualTo(message1); // validate exception is thrown if mappings were removed and // channelResolutionRequires = true (which is the default) @@ -90,7 +88,7 @@ public class PayloadTypeRouterTests { try { router.handleMessage(message1); - fail(); + fail("Exception expected"); } catch (Exception e) { // ignore @@ -116,18 +114,18 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(99); router.handleMessage(message); Message result = numberChannel.receive(0); - assertNotNull(result); - assertEquals(99, result.getPayload()); - assertNull(defaultChannel.receive(0)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(99); + assertThat(defaultChannel.receive(0)).isNull(); // validate dynamics QueueChannel newChannel = new QueueChannel(); beanFactory.registerSingleton("newChannel", newChannel); router.setChannelMapping(Integer.class.getName(), "newChannel"); - assertEquals(1, router.getChannelKeys(message).size()); + assertThat(router.getChannelKeys(message).size()).isEqualTo(1); router.handleMessage(message); result = newChannel.receive(10); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test @@ -156,10 +154,10 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(99); router.handleMessage(message); Message result = integerChannel.receive(0); - assertNotNull(result); - assertEquals(99, result.getPayload()); - assertNull(numberChannel.receive(0)); - assertNull(defaultChannel.receive(0)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(99); + assertThat(numberChannel.receive(0)).isNull(); + assertThat(defaultChannel.receive(0)).isNull(); } @Test @@ -184,9 +182,9 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(99); router.handleMessage(message); Message result = comparableChannel.receive(0); - assertNotNull(result); - assertEquals(99, result.getPayload()); - assertNull(defaultChannel.receive(0)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(99); + assertThat(defaultChannel.receive(0)).isNull(); } @Test @@ -211,7 +209,7 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(new C1()); router.handleMessage(message); Message result = i2Channel.receive(0); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test @@ -241,8 +239,8 @@ public class PayloadTypeRouterTests { router.setDefaultOutputChannel(defaultChannel); Message message = new GenericMessage<>(new C1()); router.handleMessage(message); - assertNotNull(serializableChannel.receive(0)); - assertNull(i3Channel.receive(0)); + assertThat(serializableChannel.receive(0)).isNotNull(); + assertThat(i3Channel.receive(0)).isNull(); } @Test @@ -273,7 +271,7 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(new C1()); router.handleMessage(message); Message result = c3Channel.receive(0); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test @@ -304,7 +302,7 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(new C1()); router.handleMessage(message); Message result = i1AChannel.receive(0); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test @@ -333,19 +331,19 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(99); router.handleMessage(message); Message result = comparableChannel.receive(0); - assertNotNull(result); - assertEquals(99, result.getPayload()); - assertNull(numberChannel.receive(0)); - assertNull(defaultChannel.receive(0)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(99); + assertThat(numberChannel.receive(0)).isNull(); + assertThat(defaultChannel.receive(0)).isNull(); // validate dynamics QueueChannel newChannel = new QueueChannel(); beanFactory.registerSingleton("newChannel", newChannel); router.setChannelMapping(Integer.class.getName(), "newChannel"); - assertEquals(1, router.getChannelKeys(message).size()); + assertThat(router.getChannelKeys(message).size()).isEqualTo(1); router.handleMessage(message); result = newChannel.receive(10); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test(expected = MessageHandlingException.class) @@ -401,10 +399,10 @@ public class PayloadTypeRouterTests { Message message = new GenericMessage<>(99); router.handleMessage(message); Message result = numberChannel.receive(0); - assertNotNull(result); - assertEquals(99, result.getPayload()); - assertNull(serializableChannel.receive(0)); - assertNull(defaultChannel.receive(0)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(99); + assertThat(serializableChannel.receive(0)).isNull(); + assertThat(defaultChannel.receive(0)).isNull(); } @Test @@ -432,8 +430,8 @@ public class PayloadTypeRouterTests { router.handleMessage(message2); Message reply1 = stringChannel.receive(0); Message reply2 = integerChannel.receive(0); - assertEquals("test", reply1.getPayload()); - assertEquals(123, reply2.getPayload()); + assertThat(reply1.getPayload()).isEqualTo("test"); + assertThat(reply2.getPayload()).isEqualTo(123); } @Test @@ -460,11 +458,11 @@ public class PayloadTypeRouterTests { router.handleMessage(message1); router.handleMessage(message2); Message result1 = stringChannel.receive(25); - assertNotNull(result1); - assertEquals("test", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("test"); Message result2 = defaultChannel.receive(25); - assertNotNull(result2); - assertEquals(123, result2.getPayload()); + assertThat(result2).isNotNull(); + assertThat(result2.getPayload()).isEqualTo(123); } @Test @@ -498,7 +496,7 @@ public class PayloadTypeRouterTests { router.setDefaultOutputChannel(defaultChannel); Message message = new GenericMessage<>(new C1()); router.handleMessage(message); - assertNotNull(c2Channel.receive(100)); + assertThat(c2Channel.receive(100)).isNotNull(); } @Test(expected = MessageHandlingException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java index 93c970faa0..ab2f0887b2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.router; -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.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -65,9 +62,9 @@ public class RecipientListRouterTests { router.afterPropertiesSet(); ConcurrentLinkedQueue recipients = (ConcurrentLinkedQueue) new DirectFieldAccessor(router).getPropertyValue("recipients"); - assertEquals(2, recipients.size()); - assertEquals(channel1, new DirectFieldAccessor(recipients.poll()).getPropertyValue("channel")); - assertEquals(channel2, new DirectFieldAccessor(recipients.poll()).getPropertyValue("channel")); + assertThat(recipients.size()).isEqualTo(2); + assertThat(new DirectFieldAccessor(recipients.poll()).getPropertyValue("channel")).isEqualTo(channel1); + assertThat(new DirectFieldAccessor(recipients.poll()).getPropertyValue("channel")).isEqualTo(channel2); } @Test @@ -84,11 +81,11 @@ public class RecipientListRouterTests { Message message = new GenericMessage("test"); router.handleMessage(message); Message result1 = channel1.receive(25); - assertNotNull(result1); - assertEquals("test", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("test"); Message result2 = channel2.receive(25); - assertNotNull(result2); - assertEquals("test", result2.getPayload()); + assertThat(result2).isNotNull(); + assertThat(result2.getPayload()).isEqualTo("test"); } @Test @@ -100,10 +97,10 @@ public class RecipientListRouterTests { Message message = new GenericMessage("test"); router.handleMessage(message); Message result1 = channel.receive(25); - assertNotNull(result1); - assertEquals("test", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("test"); Message result2 = channel.receive(5); - assertNull(result2); + assertThat(result2).isNull(); } @Test(expected = MessageDeliveryException.class) @@ -128,10 +125,10 @@ public class RecipientListRouterTests { } catch (RuntimeException e) { Message result1a = channelA.receive(0); - assertNotNull(result1a); - assertEquals("blocker", result1a.getPayload()); - assertNull(channelB.receive(0)); - assertNull(channelC.receive(0)); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("blocker"); + assertThat(channelB.receive(0)).isNull(); + assertThat(channelC.receive(0)).isNull(); throw e; } } @@ -158,12 +155,12 @@ public class RecipientListRouterTests { } catch (RuntimeException e) { Message result1a = channelA.receive(0); - assertNotNull(result1a); - assertEquals("test", result1a.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("test"); Message result1b = channelB.receive(0); - assertNotNull(result1b); - assertEquals("blocker", result1b.getPayload()); - assertNull(channelC.receive(0)); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("blocker"); + assertThat(channelC.receive(0)).isNull(); throw e; } } @@ -190,14 +187,14 @@ public class RecipientListRouterTests { } catch (RuntimeException e) { Message result1a = channelA.receive(0); - assertNotNull(result1a); - assertEquals("test", result1a.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("test"); Message result1b = channelB.receive(0); - assertNotNull(result1b); - assertEquals("test", result1b.getPayload()); + assertThat(result1b).isNotNull(); + assertThat(result1b.getPayload()).isEqualTo("test"); Message result1c = channelC.receive(0); - assertNotNull(result1c); - assertEquals("blocker", result1c.getPayload()); + assertThat(result1c).isNotNull(); + assertThat(result1c.getPayload()).isEqualTo("blocker"); throw e; } } @@ -224,12 +221,12 @@ public class RecipientListRouterTests { Message result1a = channelA.receive(0); Message result1b = channelB.receive(0); Message result1c = channelC.receive(0); - assertNotNull(result1a); - assertNotNull(result1b); - assertNotNull(result1c); - assertEquals("blocker", result1a.getPayload()); - assertEquals("test", result1b.getPayload()); - assertEquals("test", result1c.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1b).isNotNull(); + assertThat(result1c).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("blocker"); + assertThat(result1b.getPayload()).isEqualTo("test"); + assertThat(result1c.getPayload()).isEqualTo("test"); } @Test @@ -254,12 +251,12 @@ public class RecipientListRouterTests { Message result1a = channelA.receive(0); Message result1b = channelB.receive(0); Message result1c = channelC.receive(0); - assertNotNull(result1a); - assertNotNull(result1b); - assertNotNull(result1c); - assertEquals("test", result1a.getPayload()); - assertEquals("blocker", result1b.getPayload()); - assertEquals("test", result1c.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1b).isNotNull(); + assertThat(result1c).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("test"); + assertThat(result1b.getPayload()).isEqualTo("blocker"); + assertThat(result1c.getPayload()).isEqualTo("test"); } @Test @@ -284,12 +281,12 @@ public class RecipientListRouterTests { Message result1a = channelA.receive(0); Message result1b = channelB.receive(0); Message result1c = channelC.receive(0); - assertNotNull(result1a); - assertNotNull(result1b); - assertNotNull(result1c); - assertEquals("test", result1a.getPayload()); - assertEquals("test", result1b.getPayload()); - assertEquals("blocker", result1c.getPayload()); + assertThat(result1a).isNotNull(); + assertThat(result1b).isNotNull(); + assertThat(result1c).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("test"); + assertThat(result1b.getPayload()).isEqualTo("test"); + assertThat(result1c.getPayload()).isEqualTo("blocker"); } @Test @@ -307,16 +304,16 @@ public class RecipientListRouterTests { router.handleMessage(message); Message result1a = channelA.receive(0); Message result1b = channelB.receive(0); - assertNotNull(result1a); - assertNotNull(result1b); - assertEquals("test", result1a.getPayload()); - assertEquals(0, new IntegrationMessageHeaderAccessor(result1a).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(result1a).getSequenceSize()); - assertNull(new IntegrationMessageHeaderAccessor(result1a).getCorrelationId()); - assertEquals("test", result1b.getPayload()); - assertEquals(0, new IntegrationMessageHeaderAccessor(result1b).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(result1b).getSequenceSize()); - assertNull(new IntegrationMessageHeaderAccessor(result1b).getCorrelationId()); + assertThat(result1a).isNotNull(); + assertThat(result1b).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("test"); + assertThat(new IntegrationMessageHeaderAccessor(result1a).getSequenceNumber()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(result1a).getSequenceSize()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(result1a).getCorrelationId()).isNull(); + assertThat(result1b.getPayload()).isEqualTo("test"); + assertThat(new IntegrationMessageHeaderAccessor(result1b).getSequenceNumber()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(result1b).getSequenceSize()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(result1b).getCorrelationId()).isNull(); } @Test @@ -335,16 +332,18 @@ public class RecipientListRouterTests { router.handleMessage(message); Message result1a = channelA.receive(0); Message result1b = channelB.receive(0); - assertNotNull(result1a); - assertNotNull(result1b); - assertEquals("test", result1a.getPayload()); - assertEquals(1, new IntegrationMessageHeaderAccessor(result1a).getSequenceNumber()); - assertEquals(2, new IntegrationMessageHeaderAccessor(result1a).getSequenceSize()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(result1a).getCorrelationId()); - assertEquals("test", result1b.getPayload()); - assertEquals(2, new IntegrationMessageHeaderAccessor(result1b).getSequenceNumber()); - assertEquals(2, new IntegrationMessageHeaderAccessor(result1b).getSequenceSize()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(result1b).getCorrelationId()); + assertThat(result1a).isNotNull(); + assertThat(result1b).isNotNull(); + assertThat(result1a.getPayload()).isEqualTo("test"); + assertThat(new IntegrationMessageHeaderAccessor(result1a).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(result1a).getSequenceSize()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(result1a).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); + assertThat(result1b.getPayload()).isEqualTo("test"); + assertThat(new IntegrationMessageHeaderAccessor(result1b).getSequenceNumber()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(result1b).getSequenceSize()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(result1b).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); } @Test(expected = IllegalArgumentException.class) @@ -369,7 +368,7 @@ public class RecipientListRouterTests { router.afterPropertiesSet(); router.handleMessage(new GenericMessage("foo")); Message receive = defaultOutputChannel.receive(1000); - assertNotNull(receive); + assertThat(receive).isNotNull(); } @Test @@ -390,15 +389,15 @@ public class RecipientListRouterTests { Message message = new GenericMessage("test"); router.handleMessage(message); Message reply1 = channel1.receive(0); - assertEquals(message, reply1); + assertThat(reply1).isEqualTo(message); Message reply2 = channel2.receive(0); - assertNull(reply2); + assertThat(reply2).isNull(); Message reply3 = channel3.receive(0); - assertEquals(message, reply3); + assertThat(reply3).isEqualTo(message); Message reply4 = channel4.receive(0); - assertEquals(message, reply4); + assertThat(reply4).isEqualTo(message); Message reply5 = channel5.receive(0); - assertNull(reply5); + assertThat(reply5).isNull(); } @Test @@ -415,10 +414,10 @@ public class RecipientListRouterTests { Message message = new GenericMessage("test"); router.handleMessage(message); Message result1 = defaultChannel.receive(25); - assertNotNull(result1); - assertEquals("test", result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload()).isEqualTo("test"); Message result2 = channel.receive(5); - assertNull(result2); + assertThat(result2).isNull(); } @Test @@ -438,7 +437,7 @@ public class RecipientListRouterTests { router.handleMessage(new GenericMessage("foo")); - assertSame(defaultChannel, TestUtils.getPropertyValue(router, "defaultOutputChannel")); + assertThat(TestUtils.getPropertyValue(router, "defaultOutputChannel")).isSameAs(defaultChannel); Mockito.verify(beanFactory).getBean(Mockito.eq("defaultChannel"), Mockito.eq(MessageChannel.class)); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java b/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java index 88b0a59a42..67af389b0e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -94,10 +92,10 @@ public class RouterConcurrencyTest { exec.execute(runnable); exec.execute(runnable); exec.shutdown(); - assertTrue(exec.awaitTermination(30, TimeUnit.SECONDS)); - assertEquals(2, returns.size()); - assertNotNull(returns.get(0)); - assertNotNull(returns.get(1)); + assertThat(exec.awaitTermination(30, TimeUnit.SECONDS)).isTrue(); + assertThat(returns.size()).isEqualTo(2); + assertThat(returns.get(0)).isNotNull(); + assertThat(returns.get(1)).isNotNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/RouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/RouterTests.java index 87aadc063f..340edae03e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/RouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/RouterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -135,7 +135,7 @@ public class RouterTests { context.refresh(); router.handleMessage(new GenericMessage<>("test")); Message reply = testChannel.receive(0); - assertEquals("test", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("test"); context.close(); } @@ -164,10 +164,10 @@ public class RouterTests { router.handleMessage(new GenericMessage<>("test")); Message reply1 = testChannel1.receive(0); - assertEquals("test", reply1.getPayload()); + assertThat(reply1.getPayload()).isEqualTo("test"); Message reply2 = testChannel2.receive(0); - assertEquals("test", reply2.getPayload()); + assertThat(reply2.getPayload()).isEqualTo("test"); context.close(); } @@ -212,7 +212,7 @@ public class RouterTests { context.refresh(); router.handleMessage(new GenericMessage<>("test")); Message reply = testChannel.receive(0); - assertEquals("test", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("test"); context.close(); } @@ -237,7 +237,7 @@ public class RouterTests { context.refresh(); router.handleMessage(new GenericMessage<>("test")); Message reply = testChannel.receive(0); - assertEquals("test", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("test"); context.close(); } @@ -286,7 +286,7 @@ public class RouterTests { context.refresh(); router.handleMessage(new GenericMessage<>("test")); Message reply = testChannel.receive(0); - assertEquals("test", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("test"); context.close(); } @@ -347,10 +347,10 @@ public class RouterTests { router.handleMessage(new GenericMessage<>("test")); Message reply1 = testChannel1.receive(0); - assertEquals("test", reply1.getPayload()); + assertThat(reply1.getPayload()).isEqualTo("test"); Message reply2 = testChannel2.receive(0); - assertEquals("test", reply2.getPayload()); + assertThat(reply2.getPayload()).isEqualTo("test"); context.close(); } @@ -388,10 +388,10 @@ public class RouterTests { router.handleMessage(new GenericMessage<>("test")); Message reply1 = testChannel1.receive(0); - assertEquals("test", reply1.getPayload()); + assertThat(reply1.getPayload()).isEqualTo("test"); Message reply2 = testChannel2.receive(0); - assertEquals("test", reply2.getPayload()); + assertThat(reply2.getPayload()).isEqualTo("test"); context.close(); } @@ -421,10 +421,10 @@ public class RouterTests { router.handleMessage(new GenericMessage<>("test")); Message reply1 = testChannel1.receive(0); - assertEquals("test", reply1.getPayload()); + assertThat(reply1.getPayload()).isEqualTo("test"); Message reply2 = testChannel2.receive(0); - assertEquals("test", reply2.getPayload()); + assertThat(reply2.getPayload()).isEqualTo("test"); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/DynamicExpressionRouterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/DynamicExpressionRouterIntegrationTests.java index 6effeda9dd..ce14b892f0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/DynamicExpressionRouterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/DynamicExpressionRouterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -62,12 +61,12 @@ public class DynamicExpressionRouterIntegrationTests { this.input.send(message2); this.input.send(message3); this.input.send(message4); - assertEquals(testBean1, odd.receive(0).getPayload()); - assertEquals(testBean2, even.receive(0).getPayload()); - assertEquals(testBean3, odd.receive(0).getPayload()); - assertEquals(testBean4, even.receive(0).getPayload()); - assertNull(odd.receive(0)); - assertNull(even.receive(0)); + assertThat(odd.receive(0).getPayload()).isEqualTo(testBean1); + assertThat(even.receive(0).getPayload()).isEqualTo(testBean2); + assertThat(odd.receive(0).getPayload()).isEqualTo(testBean3); + assertThat(even.receive(0).getPayload()).isEqualTo(testBean4); + assertThat(odd.receive(0)).isNull(); + assertThat(even.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/ExceptionTypeRouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/ExceptionTypeRouterParserTests.java index 8d9258cd95..d5dc86218b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/ExceptionTypeRouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/ExceptionTypeRouterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -44,18 +43,18 @@ public class ExceptionTypeRouterParserTests { inputChannel.send(new GenericMessage(new NullPointerException())); QueueChannel nullPointerChannel = context.getBean("nullPointerChannel", QueueChannel.class); Message npeMessage = (Message) nullPointerChannel.receive(1000); - assertNotNull(npeMessage); - assertTrue(npeMessage.getPayload() instanceof NullPointerException); + assertThat(npeMessage).isNotNull(); + assertThat(npeMessage.getPayload() instanceof NullPointerException).isTrue(); inputChannel.send(new GenericMessage(new IllegalArgumentException())); QueueChannel illegalArgumentChannel = context.getBean("illegalArgumentChannel", QueueChannel.class); Message iaMessage = (Message) illegalArgumentChannel.receive(1000); - assertNotNull(iaMessage); - assertTrue(iaMessage.getPayload() instanceof IllegalArgumentException); + assertThat(iaMessage).isNotNull(); + assertThat(iaMessage.getPayload() instanceof IllegalArgumentException).isTrue(); inputChannel.send(new GenericMessage("Hello")); QueueChannel outputChannel = context.getBean("outputChannel", QueueChannel.class); - assertNotNull(outputChannel.receive(1000)); + assertThat(outputChannel.receive(1000)).isNotNull(); context.close(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterConvertibleTypeTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterConvertibleTypeTests.java index 5de2c4b69d..3b621ea5ce 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterConvertibleTypeTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterConvertibleTypeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -57,11 +56,11 @@ public class HeaderValueRouterConvertibleTypeTests { inputChannel.send(trueMessage); inputChannel.send(falseMessage); Message trueResult = trueChannel.receive(); - assertNotNull(trueResult); - assertEquals(1, trueResult.getPayload()); + assertThat(trueResult).isNotNull(); + assertThat(trueResult.getPayload()).isEqualTo(1); Message falseResult = falseChannel.receive(); - assertNotNull(falseResult); - assertEquals(0, falseResult.getPayload()); + assertThat(falseResult).isNotNull(); + assertThat(falseResult.getPayload()).isEqualTo(0); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterParserTests.java index e4629dc820..7a54859b78 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/HeaderValueRouterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -61,9 +61,9 @@ public class HeaderValueRouterParserTests { PollableChannel channel1 = (PollableChannel) context.getBean("channel1"); PollableChannel channel2 = (PollableChannel) context.getBean("channel2"); message1 = channel1.receive(); - assertEquals("channel1", message1.getHeaders().get("testHeader")); + assertThat(message1.getHeaders().get("testHeader")).isEqualTo("channel1"); message2 = channel2.receive(); - assertEquals("channel2", message2.getHeaders().get("testHeader")); + assertThat(message2.getHeaders().get("testHeader")).isEqualTo("channel2"); } @Test @@ -80,9 +80,9 @@ public class HeaderValueRouterParserTests { PollableChannel channel1 = (PollableChannel) context.getBean("channel1"); PollableChannel channel2 = (PollableChannel) context.getBean("channel2"); message1 = channel1.receive(); - assertEquals("1", message1.getHeaders().get("testHeader")); + assertThat(message1.getHeaders().get("testHeader")).isEqualTo("1"); message2 = channel2.receive(); - assertEquals("2", message2.getHeaders().get("testHeader")); + assertThat(message2.getHeaders().get("testHeader")).isEqualTo("2"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java index 4191eff139..67be94473f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; @@ -63,10 +63,10 @@ public class PayloadTypeRouterParserTests { PollableChannel chanel2 = (PollableChannel) context.getBean("channel2"); PollableChannel chanel3 = (PollableChannel) context.getBean("channel3"); PollableChannel chanel4 = (PollableChannel) context.getBean("channel4"); - assertTrue(chanel1.receive(100).getPayload() instanceof String); - assertTrue(chanel2.receive(100).getPayload() instanceof Integer); - assertTrue(chanel3.receive(100).getPayload().getClass().isArray()); - assertTrue(chanel4.receive(100).getPayload().getClass().isArray()); + assertThat(chanel1.receive(100).getPayload() instanceof String).isTrue(); + assertThat(chanel2.receive(100).getPayload() instanceof Integer).isTrue(); + assertThat(chanel3.receive(100).getPayload().getClass().isArray()).isTrue(); + assertThat(chanel4.receive(100).getPayload().getClass().isArray()).isTrue(); } @Test(expected = BeanDefinitionStoreException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RecipientListRouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RecipientListRouterParserTests.java index 7dc0621e9c..b4978dc687 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RecipientListRouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RecipientListRouterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -67,34 +65,34 @@ public class RecipientListRouterParserTests { channel.send(message); PollableChannel chanel1 = (PollableChannel) context.getBean("channel1"); PollableChannel chanel2 = (PollableChannel) context.getBean("channel2"); - assertEquals(1, chanel1.receive(0).getPayload()); - assertEquals(1, chanel2.receive(0).getPayload()); + assertThat(chanel1.receive(0).getPayload()).isEqualTo(1); + assertThat(chanel2.receive(0).getPayload()).isEqualTo(1); } @Test public void simpleRouter() { Object endpoint = context.getBean("simpleRouter"); Object handler = TestUtils.getPropertyValue(endpoint, "handler"); - assertEquals(RecipientListRouter.class, handler.getClass()); + assertThat(handler.getClass()).isEqualTo(RecipientListRouter.class); RecipientListRouter router = (RecipientListRouter) handler; DirectFieldAccessor accessor = new DirectFieldAccessor(router); - assertEquals(-1L, new DirectFieldAccessor( - accessor.getPropertyValue("messagingTemplate")).getPropertyValue("sendTimeout")); - assertEquals(Boolean.FALSE, accessor.getPropertyValue("applySequence")); - assertEquals(Boolean.FALSE, accessor.getPropertyValue("ignoreSendFailures")); + assertThat(new DirectFieldAccessor( + accessor.getPropertyValue("messagingTemplate")).getPropertyValue("sendTimeout")).isEqualTo(-1L); + assertThat(accessor.getPropertyValue("applySequence")).isEqualTo(Boolean.FALSE); + assertThat(accessor.getPropertyValue("ignoreSendFailures")).isEqualTo(Boolean.FALSE); } @Test public void customRouter() { Object endpoint = context.getBean("customRouter"); Object handler = TestUtils.getPropertyValue(endpoint, "handler"); - assertEquals(RecipientListRouter.class, handler.getClass()); + assertThat(handler.getClass()).isEqualTo(RecipientListRouter.class); RecipientListRouter router = (RecipientListRouter) handler; DirectFieldAccessor accessor = new DirectFieldAccessor(router); - assertEquals(1234L, new DirectFieldAccessor( - accessor.getPropertyValue("messagingTemplate")).getPropertyValue("sendTimeout")); - assertEquals(Boolean.TRUE, accessor.getPropertyValue("applySequence")); - assertEquals(Boolean.TRUE, accessor.getPropertyValue("ignoreSendFailures")); + assertThat(new DirectFieldAccessor( + accessor.getPropertyValue("messagingTemplate")).getPropertyValue("sendTimeout")).isEqualTo(1234L); + assertThat(accessor.getPropertyValue("applySequence")).isEqualTo(Boolean.TRUE); + assertThat(accessor.getPropertyValue("ignoreSendFailures")).isEqualTo(Boolean.TRUE); } @Test @@ -104,8 +102,8 @@ public class RecipientListRouterParserTests { simpleDynamicInput.send(message); PollableChannel chanel1 = (PollableChannel) context.getBean("channel1"); PollableChannel chanel2 = (PollableChannel) context.getBean("channel2"); - assertEquals(1, chanel1.receive(0).getPayload()); - assertNull(chanel2.receive(0)); + assertThat(chanel1.receive(0).getPayload()).isEqualTo(1); + assertThat(chanel2.receive(0)).isNull(); } @Test @@ -116,9 +114,9 @@ public class RecipientListRouterParserTests { PollableChannel chanel1 = (PollableChannel) context.getBean("channel1"); PollableChannel chanel2 = (PollableChannel) context.getBean("channel2"); Message output = chanel1.receive(0); - assertNotNull(output); - assertEquals(1, output.getPayload()); - assertNull(chanel2.receive(0)); + assertThat(output).isNotNull(); + assertThat(output.getPayload()).isEqualTo(1); + assertThat(chanel2.receive(0)).isNull(); } public static class TestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java index d277666da9..8def36bd8d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -51,8 +50,8 @@ public class RouterFactoryBeanTests { MessageHandler handler = fb.getObject(); this.routeAttempted = false; handler.handleMessage(new GenericMessage<>("foo")); - assertNotNull(bar.receive(10000)); - assertTrue(this.routeAttempted); + assertThat(bar.receive(10000)).isNotNull(); + assertThat(this.routeAttempted).isTrue(); testApplicationContext.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java index 817a56e685..4894f5eb61 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -126,37 +123,37 @@ public class RouterParserTests { public void testRouter() { this.input.send(new GenericMessage("1")); Message result1 = this.output1.receive(1000); - assertEquals("1", result1.getPayload()); - assertNull(output2.receive(0)); + assertThat(result1.getPayload()).isEqualTo("1"); + assertThat(output2.receive(0)).isNull(); input.send(new GenericMessage("2")); Message result2 = this.output2.receive(1000); - assertEquals("2", result2.getPayload()); - assertNull(output1.receive(0)); + assertThat(result2.getPayload()).isEqualTo("2"); + assertThat(output1.receive(0)).isNull(); } @Test public void testRouterWithDefaultOutputChannel() { this.inputForRouterWithDefaultOutput.send(new GenericMessage("99")); - assertNull(this.output1.receive(0)); - assertNull(this.output2.receive(0)); + assertThat(this.output1.receive(0)).isNull(); + assertThat(this.output2.receive(0)).isNull(); Message result = this.defaultOutput.receive(0); - assertEquals("99", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("99"); } @Test public void refOnlyForAbstractMessageRouterImplementation() { this.inputForAbstractMessageRouterImplementation.send(new GenericMessage("test-implementation")); Message result = this.output3.receive(1000); - assertNotNull(result); - assertEquals("test-implementation", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test-implementation"); } @Test public void refOnlyForAnnotatedObject() { this.inputForAnnotatedRouter.send(new GenericMessage("test-annotation")); Message result = this.output4.receive(1000); - assertNotNull(result); - assertEquals("test-annotation", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("test-annotation"); } @Test @@ -165,7 +162,7 @@ public class RouterParserTests { this.inputForRouterRequiringResolution.send(new GenericMessage(3)); } catch (Exception e) { - assertTrue(e.getCause() instanceof DestinationResolutionException); + assertThat(e.getCause() instanceof DestinationResolutionException).isTrue(); } } @@ -176,10 +173,10 @@ public class RouterParserTests { @Test public void timeoutValueConfigured() { - assertTrue(this.routerWithTimeout instanceof MethodInvokingRouter); + assertThat(this.routerWithTimeout instanceof MethodInvokingRouter).isTrue(); MessagingTemplate template = TestUtils.getPropertyValue(this.routerWithTimeout, "messagingTemplate", MessagingTemplate.class); Long timeout = TestUtils.getPropertyValue(template, "sendTimeout", Long.class); - assertEquals(new Long(1234), timeout); + assertThat(timeout).isEqualTo(new Long(1234)); } @Test @@ -189,39 +186,42 @@ public class RouterParserTests { Message message1 = this.sequenceOut1.receive(1000); Message message2 = this.sequenceOut2.receive(1000); Message message3 = this.sequenceOut3.receive(1000); - assertEquals(originalMessage.getHeaders().getId(), new IntegrationMessageHeaderAccessor(message1).getCorrelationId()); - assertEquals(originalMessage.getHeaders().getId(), new IntegrationMessageHeaderAccessor(message2).getCorrelationId()); - assertEquals(originalMessage.getHeaders().getId(), new IntegrationMessageHeaderAccessor(message3).getCorrelationId()); - assertEquals(1, new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()); - assertEquals(3, new IntegrationMessageHeaderAccessor(message1).getSequenceSize()); - assertEquals(2, new IntegrationMessageHeaderAccessor(message2).getSequenceNumber()); - assertEquals(3, new IntegrationMessageHeaderAccessor(message2).getSequenceSize()); - assertEquals(3, new IntegrationMessageHeaderAccessor(message3).getSequenceNumber()); - assertEquals(3, new IntegrationMessageHeaderAccessor(message3).getSequenceSize()); + assertThat(new IntegrationMessageHeaderAccessor(message1).getCorrelationId()) + .isEqualTo(originalMessage.getHeaders().getId()); + assertThat(new IntegrationMessageHeaderAccessor(message2).getCorrelationId()) + .isEqualTo(originalMessage.getHeaders().getId()); + assertThat(new IntegrationMessageHeaderAccessor(message3).getCorrelationId()) + .isEqualTo(originalMessage.getHeaders().getId()); + assertThat(new IntegrationMessageHeaderAccessor(message1).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(message1).getSequenceSize()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(message2).getSequenceNumber()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(message2).getSequenceSize()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(message3).getSequenceNumber()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(message3).getSequenceSize()).isEqualTo(3); } @Test public void testInt2893RouterNestedBean() { this.routerNestedBeanChannel.send(new GenericMessage("1")); Message result1 = this.output1.receive(1000); - assertEquals("1", result1.getPayload()); - assertNull(this.output2.receive(0)); + assertThat(result1.getPayload()).isEqualTo("1"); + assertThat(this.output2.receive(0)).isNull(); this.routerNestedBeanChannel.send(new GenericMessage("2")); Message result2 = this.output2.receive(1000); - assertEquals("2", result2.getPayload()); - assertNull(this.output1.receive(0)); + assertThat(result2.getPayload()).isEqualTo("2"); + assertThat(this.output1.receive(0)).isNull(); } @Test public void testInt2893RouterNestedBeanWithinChain() { this.chainRouterNestedBeanChannel.send(new GenericMessage("1")); Message result1 = this.output1.receive(1000); - assertEquals("1", result1.getPayload()); - assertNull(this.output2.receive(0)); + assertThat(result1.getPayload()).isEqualTo("1"); + assertThat(this.output2.receive(0)).isNull(); this.chainRouterNestedBeanChannel.send(new GenericMessage("2")); Message result2 = this.output2.receive(1000); - assertEquals("2", result2.getPayload()); - assertNull(this.output1.receive(0)); + assertThat(result2.getPayload()).isEqualTo("2"); + assertThat(this.output1.receive(0)).isNull(); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterWithMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterWithMappingTests.java index 35d71543f4..d64dd916e4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterWithMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterWithMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -84,23 +81,23 @@ public class RouterWithMappingTests { Message message2 = MessageBuilder.withPayload(new TestBean("bar")).build(); Message message3 = MessageBuilder.withPayload(new TestBean("baz")).build(); expressionRouter.send(message1); - assertNotNull(fooChannelForExpression.receive(0)); - assertNull(barChannelForExpression.receive(0)); - assertNull(defaultChannelForExpression.receive(0)); + assertThat(fooChannelForExpression.receive(0)).isNotNull(); + assertThat(barChannelForExpression.receive(0)).isNull(); + assertThat(defaultChannelForExpression.receive(0)).isNull(); expressionRouter.send(message2); - assertNotNull(barChannelForExpression.receive(0)); - assertNull(fooChannelForExpression.receive(0)); - assertNull(defaultChannelForExpression.receive(0)); + assertThat(barChannelForExpression.receive(0)).isNotNull(); + assertThat(fooChannelForExpression.receive(0)).isNull(); + assertThat(defaultChannelForExpression.receive(0)).isNull(); expressionRouter.send(message3); - assertNotNull(defaultChannelForExpression.receive(0)); - assertNull(fooChannelForExpression.receive(0)); - assertNull(barChannelForExpression.receive(0)); + assertThat(defaultChannelForExpression.receive(0)).isNotNull(); + assertThat(fooChannelForExpression.receive(0)).isNull(); + assertThat(barChannelForExpression.receive(0)).isNull(); // validate dynamics spelRouterHandler.setChannelMapping("baz", "fooChannelForExpression"); expressionRouter.send(message3); - assertNull(defaultChannelForExpression.receive(10)); - assertNotNull(fooChannelForExpression.receive(10)); - assertNull(barChannelForExpression.receive(0)); + assertThat(defaultChannelForExpression.receive(10)).isNull(); + assertThat(fooChannelForExpression.receive(10)).isNotNull(); + assertThat(barChannelForExpression.receive(0)).isNull(); } @Test @@ -109,23 +106,23 @@ public class RouterWithMappingTests { Message message2 = MessageBuilder.withPayload(new TestBean("bar")).build(); Message message3 = MessageBuilder.withPayload(new TestBean("baz")).build(); pojoRouter.send(message1); - assertNotNull(fooChannelForPojo.receive(0)); - assertNull(barChannelForPojo.receive(0)); - assertNull(defaultChannelForPojo.receive(0)); + assertThat(fooChannelForPojo.receive(0)).isNotNull(); + assertThat(barChannelForPojo.receive(0)).isNull(); + assertThat(defaultChannelForPojo.receive(0)).isNull(); pojoRouter.send(message2); - assertNotNull(barChannelForPojo.receive(0)); - assertNull(fooChannelForPojo.receive(0)); - assertNull(defaultChannelForPojo.receive(0)); + assertThat(barChannelForPojo.receive(0)).isNotNull(); + assertThat(fooChannelForPojo.receive(0)).isNull(); + assertThat(defaultChannelForPojo.receive(0)).isNull(); pojoRouter.send(message3); - assertNotNull(defaultChannelForPojo.receive(0)); - assertNull(fooChannelForPojo.receive(0)); - assertNull(barChannelForPojo.receive(0)); + assertThat(defaultChannelForPojo.receive(0)).isNotNull(); + assertThat(fooChannelForPojo.receive(0)).isNull(); + assertThat(barChannelForPojo.receive(0)).isNull(); - assertTrue(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isTrue(); this.pojoRouterEndpoint.stop(); - assertFalse(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isFalse(); this.pojoRouterEndpoint.start(); - assertTrue(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isTrue(); } private static class TestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/SpelRouterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/SpelRouterIntegrationTests.java index 03ff4fd978..afc3b5c9ac 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/SpelRouterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/SpelRouterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -69,12 +68,12 @@ public class SpelRouterIntegrationTests { this.simpleInput.send(message2); this.simpleInput.send(message3); this.simpleInput.send(message4); - assertEquals(testBean1, odd.receive(0).getPayload()); - assertEquals(testBean2, even.receive(0).getPayload()); - assertEquals(testBean3, odd.receive(0).getPayload()); - assertEquals(testBean4, even.receive(0).getPayload()); - assertNull(odd.receive(0)); - assertNull(even.receive(0)); + assertThat(odd.receive(0).getPayload()).isEqualTo(testBean1); + assertThat(even.receive(0).getPayload()).isEqualTo(testBean2); + assertThat(odd.receive(0).getPayload()).isEqualTo(testBean3); + assertThat(even.receive(0).getPayload()).isEqualTo(testBean4); + assertThat(odd.receive(0)).isNull(); + assertThat(even.receive(0)).isNull(); } @Test @@ -84,13 +83,13 @@ public class SpelRouterIntegrationTests { this.beanResolvingInput.send(MessageBuilder.withPayload(20).build()); this.beanResolvingInput.send(MessageBuilder.withPayload(30).build()); this.beanResolvingInput.send(MessageBuilder.withPayload(34).build()); - assertEquals(20, testBean.clear.receive(0).getPayload()); - assertEquals(30, testBean.clear.receive(0).getPayload()); - assertNull(testBean.clear.receive(0)); - assertEquals(5, testBean.remainders.receive(0).getPayload()); - assertEquals(9, testBean.remainders.receive(0).getPayload()); - assertEquals(34, testBean.remainders.receive(0).getPayload()); - assertNull(testBean.remainders.receive(0)); + assertThat(testBean.clear.receive(0).getPayload()).isEqualTo(20); + assertThat(testBean.clear.receive(0).getPayload()).isEqualTo(30); + assertThat(testBean.clear.receive(0)).isNull(); + assertThat(testBean.remainders.receive(0).getPayload()).isEqualTo(5); + assertThat(testBean.remainders.receive(0).getPayload()).isEqualTo(9); + assertThat(testBean.remainders.receive(0).getPayload()).isEqualTo(34); + assertThat(testBean.remainders.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterAggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterAggregatorTests.java index e42f7b4530..f29e5746ec 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterAggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterAggregatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.router.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -48,14 +47,14 @@ public class SplitterAggregatorTests { PollableChannel outputChannel = (PollableChannel) context.getBean("results"); inputChannel.send(new GenericMessage(this.nextTen())); Message result1 = outputChannel.receive(1000); - assertNotNull(result1); - assertEquals(Integer.class, result1.getPayload().getClass()); - assertEquals(55, result1.getPayload()); + assertThat(result1).isNotNull(); + assertThat(result1.getPayload().getClass()).isEqualTo(Integer.class); + assertThat(result1.getPayload()).isEqualTo(55); inputChannel.send(new GenericMessage(this.nextTen())); Message result2 = outputChannel.receive(1000); - assertNotNull(result2); - assertEquals(Integer.class, result2.getPayload().getClass()); - assertEquals(155, result2.getPayload()); + assertThat(result2).isNotNull(); + assertThat(result2.getPayload().getClass()).isEqualTo(Integer.class); + assertThat(result2.getPayload()).isEqualTo(155); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterParserTests.java index ea0b0dfabd..23eca9beca 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/SplitterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.router.config; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; @@ -51,14 +48,14 @@ public class SplitterParserTests { PollableChannel output = (PollableChannel) context.getBean("output"); input.send(new GenericMessage("this.is.a.test")); Message result1 = output.receive(1000); - assertEquals("this", result1.getPayload()); + assertThat(result1.getPayload()).isEqualTo("this"); Message result2 = output.receive(1000); - assertEquals("is", result2.getPayload()); + assertThat(result2.getPayload()).isEqualTo("is"); Message result3 = output.receive(1000); - assertEquals("a", result3.getPayload()); + assertThat(result3.getPayload()).isEqualTo("a"); Message result4 = output.receive(1000); - assertEquals("test", result4.getPayload()); - assertNull(output.receive(0)); + assertThat(result4.getPayload()).isEqualTo("test"); + assertThat(output.receive(0)).isNull(); context.close(); } @@ -71,14 +68,14 @@ public class SplitterParserTests { PollableChannel output = (PollableChannel) context.getBean("output"); input.send(new GenericMessage("this.is.a.test")); Message result1 = output.receive(1000); - assertEquals("this", result1.getPayload()); + assertThat(result1.getPayload()).isEqualTo("this"); Message result2 = output.receive(1000); - assertEquals("is", result2.getPayload()); + assertThat(result2.getPayload()).isEqualTo("is"); Message result3 = output.receive(1000); - assertEquals("a", result3.getPayload()); + assertThat(result3.getPayload()).isEqualTo("a"); Message result4 = output.receive(1000); - assertEquals("test", result4.getPayload()); - assertNull(output.receive(0)); + assertThat(result4.getPayload()).isEqualTo("test"); + assertThat(output.receive(0)).isNull(); context.close(); } @@ -91,14 +88,14 @@ public class SplitterParserTests { PollableChannel output = (PollableChannel) context.getBean("output"); input.send(new GenericMessage("this.is.a.test")); Message result1 = output.receive(1000); - assertEquals("this", result1.getPayload()); + assertThat(result1.getPayload()).isEqualTo("this"); Message result2 = output.receive(1000); - assertEquals("is", result2.getPayload()); + assertThat(result2.getPayload()).isEqualTo("is"); Message result3 = output.receive(1000); - assertEquals("a", result3.getPayload()); + assertThat(result3.getPayload()).isEqualTo("a"); Message result4 = output.receive(1000); - assertEquals("test", result4.getPayload()); - assertNull(output.receive(0)); + assertThat(result4.getPayload()).isEqualTo("test"); + assertThat(output.receive(0)).isNull(); context.close(); } @@ -121,8 +118,8 @@ public class SplitterParserTests { PollableChannel output = (PollableChannel) context.getBean("output"); inputChannel.send(MessageBuilder.withPayload(Collections.emptyList()).build()); Message message = output.receive(1000); - assertThat(new IntegrationMessageHeaderAccessor(message).getSequenceNumber(), is(0)); - assertThat(new IntegrationMessageHeaderAccessor(message).getSequenceSize(), is(0)); + assertThat(new IntegrationMessageHeaderAccessor(message).getSequenceNumber()).isEqualTo(0); + assertThat(new IntegrationMessageHeaderAccessor(message).getSequenceSize()).isEqualTo(0); context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/routingslip/RoutingSlipTests.java b/spring-integration-core/src/test/java/org/springframework/integration/routingslip/RoutingSlipTests.java index 54ffedebec..de6b331aef 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/routingslip/RoutingSlipTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/routingslip/RoutingSlipTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2019 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,8 @@ package org.springframework.integration.routingslip; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Arrays; import java.util.Collections; @@ -93,17 +88,18 @@ public class RoutingSlipTests { .setHeader("myRoutingSlipChannel", "channel5").build(); this.input.send(request); Message reply = replyChannel.receive(10000); - assertNotNull(reply); + assertThat(reply).isNotNull(); List> messages = (List>) reply.getPayload(); for (Message message : messages) { Map, Integer> routingSlip = message.getHeaders() .get(IntegrationMessageHeaderAccessor.ROUTING_SLIP, Map.class); - assertEquals(routingSlip.keySet().iterator().next().size(), routingSlip.values().iterator().next().intValue()); + assertThat(routingSlip.values().iterator().next().intValue()) + .isEqualTo(routingSlip.keySet().iterator().next().size()); MessageHistory messageHistory = MessageHistory.read(message); List channelNames = Arrays.asList("input", "split", "process", "channel1", "channel2", "channel3", "channel4", "channel5", "aggregate"); for (Properties properties : messageHistory) { - assertTrue(channelNames.contains(properties.getProperty("name"))); + assertThat(channelNames.contains(properties.getProperty("name"))).isTrue(); } } } @@ -112,13 +108,13 @@ public class RoutingSlipTests { public void testDynamicRoutingSlipRoutStrategy() { this.routingSlipHeaderChannel.send(new GenericMessage<>("foo")); Message result = this.resultsChannel.receive(10000); - assertNotNull(result); - assertEquals("FOO", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo("FOO"); this.routingSlipHeaderChannel.send(new GenericMessage<>(2)); result = this.resultsChannel.receive(10000); - assertNotNull(result); - assertEquals(4, result.getPayload()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(4); } @Test @@ -128,19 +124,18 @@ public class RoutingSlipTests { fail("IllegalArgumentException expected"); } catch (Exception e) { - assertThat(e, instanceOf(IllegalArgumentException.class)); - assertThat(e.getMessage(), - containsString("The RoutingSlip can contain " + - "only bean names of MessageChannel or RoutingSlipRouteStrategy, " + - "or MessageChannel and RoutingSlipRouteStrategy instances")); + assertThat(e).isInstanceOf(IllegalArgumentException.class); + assertThat(e.getMessage()).contains("The RoutingSlip can contain " + + "only bean names of MessageChannel or RoutingSlipRouteStrategy, " + + "or MessageChannel and RoutingSlipRouteStrategy instances"); } try { this.invalidRoutingSlipChannel.send(new GenericMessage<>("foo")); fail("MessagingException expected"); } catch (Exception e) { - assertThat(e, instanceOf(MessagingException.class)); - assertThat(e.getMessage(), containsString("replyChannel must be a MessageChannel or String")); + assertThat(e).isInstanceOf(MessagingException.class); + assertThat(e.getMessage()).contains("replyChannel must be a MessageChannel or String"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherParserTests.java index 2c1329809a..fe3dd64947 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,7 @@ package org.springframework.integration.scattergather.config; -import static org.hamcrest.Matchers.instanceOf; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Collection; @@ -58,54 +52,55 @@ public class ScatterGatherParserTests { @Test public void testAuction() { MessageHandler scatterGather = this.beanFactory.getBean("scatterGather1.handler", MessageHandler.class); - assertThat(scatterGather, instanceOf(ScatterGatherHandler.class)); - assertSame(this.beanFactory.getBean("scatterChannel"), - TestUtils.getPropertyValue(scatterGather, "scatterChannel")); - assertTrue(this.beanFactory.containsBean("scatterGather1.gatherer")); + assertThat(scatterGather).isInstanceOf(ScatterGatherHandler.class); + assertThat(TestUtils.getPropertyValue(scatterGather, "scatterChannel")) + .isSameAs(this.beanFactory.getBean("scatterChannel")); + assertThat(this.beanFactory.containsBean("scatterGather1.gatherer")).isTrue(); AggregatingMessageHandler gatherer = this.beanFactory.getBean("scatterGather1.gatherer", AggregatingMessageHandler.class); - assertSame(gatherer, TestUtils.getPropertyValue(scatterGather, "gatherer")); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherer")).isSameAs(gatherer); Object reaper = this.beanFactory.getBean("reaper"); - assertSame(gatherer.getMessageStore(), TestUtils.getPropertyValue(reaper, "messageGroupStore")); - assertTrue(TestUtils.getPropertyValue(scatterGather, "requiresReply", Boolean.class)); + assertThat(TestUtils.getPropertyValue(reaper, "messageGroupStore")).isSameAs(gatherer.getMessageStore()); + assertThat(TestUtils.getPropertyValue(scatterGather, "requiresReply", Boolean.class)).isTrue(); } @Test @SuppressWarnings("unchecked") public void testDistribution() { MessageHandler scatterGather = this.beanFactory.getBean("scatterGather2.handler", MessageHandler.class); - assertSame(this.beanFactory.getBean("gatherChannel"), - TestUtils.getPropertyValue(scatterGather, "gatherChannel")); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherChannel")) + .isSameAs(this.beanFactory.getBean("gatherChannel")); Lifecycle gatherEndpoint = TestUtils.getPropertyValue(scatterGather, "gatherEndpoint", Lifecycle.class); - assertNotNull(TestUtils.getPropertyValue(scatterGather, "gatherEndpoint")); - assertThat(TestUtils.getPropertyValue(scatterGather, "gatherEndpoint"), instanceOf(EventDrivenConsumer.class)); - assertTrue(TestUtils.getPropertyValue(scatterGather, "gatherEndpoint.running", Boolean.class)); - assertEquals(100L, TestUtils.getPropertyValue(scatterGather, "gatherTimeout")); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherEndpoint")).isNotNull(); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherEndpoint")).isInstanceOf(EventDrivenConsumer.class); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherEndpoint.running", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherTimeout")).isEqualTo(100L); - assertTrue(this.beanFactory.containsBean("myGatherer")); + assertThat(this.beanFactory.containsBean("myGatherer")).isTrue(); Object gatherer = this.beanFactory.getBean("myGatherer"); - assertSame(gatherer, TestUtils.getPropertyValue(scatterGather, "gatherer")); - assertSame(this.beanFactory.getBean("messageStore"), TestUtils.getPropertyValue(gatherer, "messageStore")); - assertSame(gatherer, TestUtils.getPropertyValue(scatterGather, "gatherEndpoint.handler")); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherer")).isSameAs(gatherer); + assertThat(TestUtils.getPropertyValue(gatherer, "messageStore")) + .isSameAs(this.beanFactory.getBean("messageStore")); + assertThat(TestUtils.getPropertyValue(scatterGather, "gatherEndpoint.handler")).isSameAs(gatherer); - assertTrue(this.beanFactory.containsBean("myScatterer")); + assertThat(this.beanFactory.containsBean("myScatterer")).isTrue(); Object scatterer = this.beanFactory.getBean("myScatterer"); - assertTrue(TestUtils.getPropertyValue(scatterer, "applySequence", Boolean.class)); + assertThat(TestUtils.getPropertyValue(scatterer, "applySequence", Boolean.class)).isTrue(); Collection recipients = TestUtils.getPropertyValue(scatterer, "recipients", Collection.class); - assertEquals(1, recipients.size()); - assertSame(this.beanFactory.getBean("distributionChannel"), recipients.iterator().next().getChannel()); + assertThat(recipients.size()).isEqualTo(1); + assertThat(recipients.iterator().next().getChannel()).isSameAs(this.beanFactory.getBean("distributionChannel")); Object scatterChannel = TestUtils.getPropertyValue(scatterGather, "scatterChannel"); - assertThat(scatterChannel, instanceOf(FixedSubscriberChannel.class)); - assertSame(scatterer, TestUtils.getPropertyValue(scatterChannel, "handler")); + assertThat(scatterChannel).isInstanceOf(FixedSubscriberChannel.class); + assertThat(TestUtils.getPropertyValue(scatterChannel, "handler")).isSameAs(scatterer); - assertTrue(gatherEndpoint.isRunning()); + assertThat(gatherEndpoint.isRunning()).isTrue(); ((Lifecycle) scatterGather).stop(); - assertFalse(((Lifecycle) scatterGather).isRunning()); - assertFalse(gatherEndpoint.isRunning()); + assertThat(((Lifecycle) scatterGather).isRunning()).isFalse(); + assertThat(gatherEndpoint.isRunning()).isFalse(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherTests.java index 50d22a7f24..b52afc4d76 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/scattergather/config/ScatterGatherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,10 +16,7 @@ package org.springframework.integration.scattergather.config; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.List; @@ -63,29 +60,29 @@ public class ScatterGatherTests { public void testAuction() { this.inputAuction.send(new GenericMessage("foo")); Message bestQuoteMessage = this.output.receive(10000); - assertNotNull(bestQuoteMessage); + assertThat(bestQuoteMessage).isNotNull(); Object payload = bestQuoteMessage.getPayload(); - assertThat(payload, instanceOf(List.class)); - assertThat(((List) payload).size(), greaterThanOrEqualTo(1)); + assertThat(payload).isInstanceOf(List.class); + assertThat(((List) payload).size()).isGreaterThanOrEqualTo(1); } @Test public void testDistribution() { this.inputDistribution.send(new GenericMessage("foo")); Message bestQuoteMessage = this.output.receive(10000); - assertNotNull(bestQuoteMessage); + assertThat(bestQuoteMessage).isNotNull(); Object payload = bestQuoteMessage.getPayload(); - assertThat(payload, instanceOf(List.class)); - assertThat(((List) payload).size(), greaterThanOrEqualTo(1)); + assertThat(payload).isInstanceOf(List.class); + assertThat(((List) payload).size()).isGreaterThanOrEqualTo(1); } @Test public void testGatewayScatterGather() { Message bestQuoteMessage = this.gateway.exchange(new GenericMessage("foo")); - assertNotNull(bestQuoteMessage); + assertThat(bestQuoteMessage).isNotNull(); Object payload = bestQuoteMessage.getPayload(); - assertThat(payload, instanceOf(List.class)); - assertThat(((List) payload).size(), greaterThanOrEqualTo(1)); + assertThat(payload).isInstanceOf(List.class); + assertThat(((List) payload).size()).isGreaterThanOrEqualTo(1); } @Test @@ -93,7 +90,7 @@ public class ScatterGatherTests { this.scatterGatherWithinChain.send(new GenericMessage("foo")); for (int i = 0; i < 3; i++) { Message result = this.output.receive(10000); - assertNotNull(result); + assertThat(result).isNotNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java b/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java index 836771154d..62b2140ba0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.selector; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -41,7 +40,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(false)); chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); - assertTrue(chain.accept(message)); + assertThat(chain.accept(message)).isTrue(); } @Test @@ -52,7 +51,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(false)); chain.add(new TestSelector(false)); chain.add(new TestSelector(false)); - assertFalse(chain.accept(message)); + assertThat(chain.accept(message)).isFalse(); } @Test @@ -62,7 +61,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(true)); chain.add(new TestSelector(true)); - assertTrue(chain.accept(message)); + assertThat(chain.accept(message)).isTrue(); } @Test @@ -72,7 +71,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); chain.add(new TestSelector(true)); - assertFalse(chain.accept(message)); + assertThat(chain.accept(message)).isFalse(); } @Test @@ -82,7 +81,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); - assertTrue(chain.accept(message)); + assertThat(chain.accept(message)).isTrue(); } @Test @@ -93,7 +92,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); chain.add(new TestSelector(false)); - assertTrue(chain.accept(message)); + assertThat(chain.accept(message)).isTrue(); } @Test @@ -103,7 +102,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(false)); chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); - assertFalse(chain.accept(message)); + assertThat(chain.accept(message)).isFalse(); } @Test @@ -114,7 +113,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); chain.add(new TestSelector(false)); - assertFalse(chain.accept(message)); + assertThat(chain.accept(message)).isFalse(); } @Test @@ -124,7 +123,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); - assertTrue(chain.accept(message)); + assertThat(chain.accept(message)).isTrue(); } @Test @@ -135,7 +134,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); chain.add(new TestSelector(true)); - assertTrue(chain.accept(message)); + assertThat(chain.accept(message)).isTrue(); } @Test @@ -145,7 +144,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(false)); chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); - assertFalse(chain.accept(message)); + assertThat(chain.accept(message)).isFalse(); } @Test @@ -156,7 +155,7 @@ public class MessageSelectorChainTests { chain.add(new TestSelector(true)); chain.add(new TestSelector(true)); chain.add(new TestSelector(false)); - assertFalse(chain.accept(message)); + assertThat(chain.accept(message)).isFalse(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/DefaultSplitterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/DefaultSplitterTests.java index 411e27767f..a3c46639fb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/DefaultSplitterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/DefaultSplitterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.splitter; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; @@ -62,16 +56,16 @@ public class DefaultSplitterTests { splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); List> replies = replyChannel.clear(); - assertEquals(3, replies.size()); + assertThat(replies.size()).isEqualTo(3); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("x", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("x"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("y", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("y"); Message reply3 = replies.get(2); - assertNotNull(reply3); - assertEquals("z", reply3.getPayload()); + assertThat(reply3).isNotNull(); + assertThat(reply3.getPayload()).isEqualTo("z"); } @Test @@ -83,16 +77,16 @@ public class DefaultSplitterTests { splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); List> replies = replyChannel.clear(); - assertEquals(3, replies.size()); + assertThat(replies.size()).isEqualTo(3); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("x", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("x"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("y", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("y"); Message reply3 = replies.get(2); - assertNotNull(reply3); - assertEquals("z", reply3.getPayload()); + assertThat(reply3).isNotNull(); + assertThat(reply3.getPayload()).isEqualTo("z"); } @Test @@ -104,9 +98,10 @@ public class DefaultSplitterTests { splitter.setOutputChannel(outputChannel); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, splitter); endpoint.start(); - assertTrue(inputChannel.send(message)); + assertThat(inputChannel.send(message)).isTrue(); Message reply = outputChannel.receive(0); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); } @Test @@ -117,7 +112,7 @@ public class DefaultSplitterTests { splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); Message output = replyChannel.receive(15); - assertThat(output, is(nullValue())); + assertThat(output).isNull(); } @Test @@ -131,9 +126,10 @@ public class DefaultSplitterTests { splitter.handleMessage(message); for (int i = 0; i < 10; i++) { Message reply = outputChannel.receive(0); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); } - assertNull(outputChannel.receive(10)); + assertThat(outputChannel.receive(10)).isNull(); } @Test @@ -156,9 +152,10 @@ public class DefaultSplitterTests { splitter.handleMessage(message); for (int i = 0; i < 10; i++) { Message reply = outputChannel.receive(0); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); + assertThat(new IntegrationMessageHeaderAccessor(reply).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); } - assertNull(outputChannel.receive(10)); + assertThat(outputChannel.receive(10)).isNull(); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/DynamicExpressionSplitterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/DynamicExpressionSplitterIntegrationTests.java index c19cb196dc..97c2aa1183 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/DynamicExpressionSplitterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/DynamicExpressionSplitterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.splitter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -56,15 +55,15 @@ public class DynamicExpressionSplitterIntegrationTests { Message two = output.receive(0); Message three = output.receive(0); Message four = output.receive(0); - assertEquals(1, one.getPayload()); - assertEquals("foo", one.getHeaders().get("foo")); - assertEquals(2, two.getPayload()); - assertEquals("foo", two.getHeaders().get("foo")); - assertEquals(3, three.getPayload()); - assertEquals("foo", three.getHeaders().get("foo")); - assertEquals(4, four.getPayload()); - assertEquals("foo", four.getHeaders().get("foo")); - assertNull(output.receive(0)); + assertThat(one.getPayload()).isEqualTo(1); + assertThat(one.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(two.getPayload()).isEqualTo(2); + assertThat(two.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(three.getPayload()).isEqualTo(3); + assertThat(three.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(four.getPayload()).isEqualTo(4); + assertThat(four.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(output.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java index 4b4f1667b7..bdd19c92c3 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java @@ -16,9 +16,7 @@ package org.springframework.integration.splitter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; @@ -61,11 +59,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -77,11 +75,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -93,11 +91,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -109,11 +107,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -125,11 +123,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -141,11 +139,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -161,16 +159,16 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); - assertEquals("myValue", reply1.getHeaders().get("myHeader")); - assertEquals("bar", reply1.getHeaders().get("foo")); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); + assertThat(reply1.getHeaders().get("myHeader")).isEqualTo("myValue"); + assertThat(reply1.getHeaders().get("foo")).isEqualTo("bar"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); - assertEquals("myValue", reply2.getHeaders().get("myHeader")); - assertEquals("bar", reply2.getHeaders().get("foo")); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); + assertThat(reply2.getHeaders().get("myHeader")).isEqualTo("myValue"); + assertThat(reply2.getHeaders().get("foo")).isEqualTo("bar"); } @Test @@ -182,11 +180,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -198,11 +196,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -214,11 +212,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -230,11 +228,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -248,11 +246,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -264,11 +262,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -280,11 +278,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -296,11 +294,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -312,11 +310,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -330,11 +328,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -356,11 +354,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @SuppressWarnings("unchecked") @@ -394,12 +392,12 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); - assertTrue("Expected stream.close()", closed.get()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); + assertThat(closed.get()).as("Expected stream.close()").isTrue(); } @Test @@ -411,15 +409,17 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply1).getSequenceSize()); - assertEquals(1, new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()); + assertThat(reply1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceSize()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceSize()); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()); + assertThat(reply2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceSize()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); } @Test @@ -431,15 +431,17 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply1).getSequenceSize()); - assertEquals(1, new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()); + assertThat(reply1).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceSize()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceSize()); - assertEquals(2, new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()); - assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()); + assertThat(reply2).isNotNull(); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceSize()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getSequenceNumber()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()) + .isEqualTo(message.getHeaders().getId()); } @Test @@ -451,11 +453,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test @@ -471,17 +473,17 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("a", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("a"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("b", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("b"); Message reply3 = replies.get(2); - assertNotNull(reply3); - assertEquals("c", reply3.getPayload()); + assertThat(reply3).isNotNull(); + assertThat(reply3.getPayload()).isEqualTo("c"); Message reply4 = replies.get(3); - assertNotNull(reply4); - assertEquals("d", reply4.getPayload()); + assertThat(reply4).isNotNull(); + assertThat(reply4.getPayload()).isEqualTo("d"); } @Test @@ -496,11 +498,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test(expected = IllegalArgumentException.class) @@ -520,11 +522,11 @@ public class MethodInvokingSplitterTests { splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); - assertNotNull(reply1); - assertEquals("foo", reply1.getPayload()); + assertThat(reply1).isNotNull(); + assertThat(reply1.getPayload()).isEqualTo("foo"); Message reply2 = replies.get(1); - assertNotNull(reply2); - assertEquals("bar", reply2.getPayload()); + assertThat(reply2).isNotNull(); + assertThat(reply2.getPayload()).isEqualTo("bar"); } @Test(expected = IllegalArgumentException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java index 694bc825f5..b65d4135cb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.splitter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; @@ -71,10 +69,10 @@ public class SpelSplitterIntegrationTests { this.dups.send(message); Message one = output.receive(0); Message two = output.receive(0); - assertNotNull(one); - assertNotNull(two); - assertEquals("one", one.getPayload()); - assertEquals("one", two.getPayload()); + assertThat(one).isNotNull(); + assertThat(two).isNotNull(); + assertThat(one.getPayload()).isEqualTo("one"); + assertThat(two.getPayload()).isEqualTo("one"); } @Test @@ -85,15 +83,15 @@ public class SpelSplitterIntegrationTests { Message two = output.receive(0); Message three = output.receive(0); Message four = output.receive(0); - assertEquals(new Integer(1), one.getPayload()); - assertEquals("foo", one.getHeaders().get("foo")); - assertEquals(new Integer(2), two.getPayload()); - assertEquals("foo", two.getHeaders().get("foo")); - assertEquals(new Integer(3), three.getPayload()); - assertEquals("foo", three.getHeaders().get("foo")); - assertEquals(new Integer(4), four.getPayload()); - assertEquals("foo", four.getHeaders().get("foo")); - assertNull(output.receive(0)); + assertThat(one.getPayload()).isEqualTo(new Integer(1)); + assertThat(one.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(two.getPayload()).isEqualTo(new Integer(2)); + assertThat(two.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(three.getPayload()).isEqualTo(new Integer(3)); + assertThat(three.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(four.getPayload()).isEqualTo(new Integer(4)); + assertThat(four.getHeaders().get("foo")).isEqualTo("foo"); + assertThat(output.receive(0)).isNull(); } @Test @@ -104,11 +102,11 @@ public class SpelSplitterIntegrationTests { Message b = output.receive(0); Message c = output.receive(0); Message d = output.receive(0); - assertEquals("a", a.getPayload()); - assertEquals("b", b.getPayload()); - assertEquals("c", c.getPayload()); - assertEquals("d", d.getPayload()); - assertNull(output.receive(0)); + assertThat(a.getPayload()).isEqualTo("a"); + assertThat(b.getPayload()).isEqualTo("b"); + assertThat(c.getPayload()).isEqualTo("c"); + assertThat(d.getPayload()).isEqualTo("d"); + assertThat(output.receive(0)).isNull(); } @Test @@ -118,19 +116,19 @@ public class SpelSplitterIntegrationTests { Message b = output.receive(0); Message c = output.receive(0); Message d = output.receive(0); - assertEquals("a", a.getPayload()); - assertEquals(1, new IntegrationMessageHeaderAccessor(a).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(a).getSequenceSize()); - assertEquals("b", b.getPayload()); - assertEquals(2, new IntegrationMessageHeaderAccessor(b).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(b).getSequenceSize()); - assertEquals("c", c.getPayload()); - assertEquals(3, new IntegrationMessageHeaderAccessor(c).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(c).getSequenceSize()); - assertEquals("d", d.getPayload()); - assertEquals(4, new IntegrationMessageHeaderAccessor(d).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(d).getSequenceSize()); - assertNull(output.receive(0)); + assertThat(a.getPayload()).isEqualTo("a"); + assertThat(new IntegrationMessageHeaderAccessor(a).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(a).getSequenceSize()).isEqualTo(0); + assertThat(b.getPayload()).isEqualTo("b"); + assertThat(new IntegrationMessageHeaderAccessor(b).getSequenceNumber()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(b).getSequenceSize()).isEqualTo(0); + assertThat(c.getPayload()).isEqualTo("c"); + assertThat(new IntegrationMessageHeaderAccessor(c).getSequenceNumber()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(c).getSequenceSize()).isEqualTo(0); + assertThat(d.getPayload()).isEqualTo("d"); + assertThat(new IntegrationMessageHeaderAccessor(d).getSequenceNumber()).isEqualTo(4); + assertThat(new IntegrationMessageHeaderAccessor(d).getSequenceSize()).isEqualTo(0); + assertThat(output.receive(0)).isNull(); } @Test @@ -140,19 +138,19 @@ public class SpelSplitterIntegrationTests { Message b = output.receive(0); Message c = output.receive(0); Message d = output.receive(0); - assertEquals("a", a.getPayload()); - assertEquals(1, new IntegrationMessageHeaderAccessor(a).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(a).getSequenceSize()); - assertEquals("b", b.getPayload()); - assertEquals(2, new IntegrationMessageHeaderAccessor(b).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(b).getSequenceSize()); - assertEquals("c", c.getPayload()); - assertEquals(3, new IntegrationMessageHeaderAccessor(c).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(c).getSequenceSize()); - assertEquals("d", d.getPayload()); - assertEquals(4, new IntegrationMessageHeaderAccessor(d).getSequenceNumber()); - assertEquals(0, new IntegrationMessageHeaderAccessor(d).getSequenceSize()); - assertNull(output.receive(0)); + assertThat(a.getPayload()).isEqualTo("a"); + assertThat(new IntegrationMessageHeaderAccessor(a).getSequenceNumber()).isEqualTo(1); + assertThat(new IntegrationMessageHeaderAccessor(a).getSequenceSize()).isEqualTo(0); + assertThat(b.getPayload()).isEqualTo("b"); + assertThat(new IntegrationMessageHeaderAccessor(b).getSequenceNumber()).isEqualTo(2); + assertThat(new IntegrationMessageHeaderAccessor(b).getSequenceSize()).isEqualTo(0); + assertThat(c.getPayload()).isEqualTo("c"); + assertThat(new IntegrationMessageHeaderAccessor(c).getSequenceNumber()).isEqualTo(3); + assertThat(new IntegrationMessageHeaderAccessor(c).getSequenceSize()).isEqualTo(0); + assertThat(d.getPayload()).isEqualTo("d"); + assertThat(new IntegrationMessageHeaderAccessor(d).getSequenceNumber()).isEqualTo(4); + assertThat(new IntegrationMessageHeaderAccessor(d).getSequenceSize()).isEqualTo(0); + assertThat(output.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/SplitterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/SplitterIntegrationTests.java index 43cd200c9f..e0fe645cf0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/SplitterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/SplitterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.splitter; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Arrays; @@ -111,28 +110,28 @@ public class SplitterIntegrationTests { @Test public void annotated() throws Exception { inAnnotated.send(new GenericMessage(sentence)); - assertTrue(this.receiver.receivedWords.containsAll(words)); - assertTrue(words.containsAll(this.receiver.receivedWords)); + assertThat(this.receiver.receivedWords.containsAll(words)).isTrue(); + assertThat(words.containsAll(this.receiver.receivedWords)).isTrue(); } @Test public void methodInvoking() throws Exception { inMethodInvoking.send(new GenericMessage(sentence)); - assertTrue(receiver.receivedWords.containsAll(words)); - assertTrue(words.containsAll(this.receiver.receivedWords)); + assertThat(receiver.receivedWords.containsAll(words)).isTrue(); + assertThat(words.containsAll(this.receiver.receivedWords)).isTrue(); } @Test public void defaultSplitter() throws Exception { inDefault.send(new GenericMessage>(words)); - assertTrue(receiver.receivedWords.containsAll(words)); - assertTrue(words.containsAll(receiver.receivedWords)); + assertThat(receiver.receivedWords.containsAll(words)).isTrue(); + assertThat(words.containsAll(receiver.receivedWords)).isTrue(); } @Test public void delimiterSplitter() throws Exception { inDelimiters.send(new GenericMessage("one,two, three; four/five")); - assertTrue(receiver.receivedWords.containsAll(Arrays.asList("one", "two", "three", "four", "five"))); + assertThat(receiver.receivedWords.containsAll(Arrays.asList("one", "two", "three", "four", "five"))).isTrue(); } @Test(expected = IllegalArgumentException.class) @@ -143,9 +142,9 @@ public class SplitterIntegrationTests { } catch (BeanCreationException e) { Throwable cause = e.getMostSpecificCause(); - assertNotNull(cause); - assertTrue(cause instanceof IllegalArgumentException); - assertTrue(cause.getMessage().contains("'delimiters' property is only available")); + assertThat(cause).isNotNull(); + assertThat(cause instanceof IllegalArgumentException).isTrue(); + assertThat(cause.getMessage().contains("'delimiters' property is only available")).isTrue(); throw cause; } } @@ -158,9 +157,9 @@ public class SplitterIntegrationTests { } catch (BeanCreationException e) { Throwable cause = e.getMostSpecificCause(); - assertNotNull(cause); - assertTrue(cause instanceof IllegalArgumentException); - assertTrue(cause.getMessage().contains("'delimiters' property is only available")); + assertThat(cause).isNotNull(); + assertThat(cause instanceof IllegalArgumentException).isTrue(); + assertThat(cause.getMessage().contains("'delimiters' property is only available")).isTrue(); throw cause; } } @@ -173,9 +172,9 @@ public class SplitterIntegrationTests { } catch (BeanCreationException e) { Throwable cause = e.getMostSpecificCause(); - assertNotNull(cause); - assertTrue(cause instanceof IllegalArgumentException); - assertTrue(cause.getMessage().contains("'delimiters' property is only available")); + assertThat(cause).isNotNull(); + assertThat(cause instanceof IllegalArgumentException).isTrue(); + assertThat(cause.getMessage().contains("'delimiters' property is only available")).isTrue(); throw cause; } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java index 389cab0cf3..da4e55aeb3 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java @@ -16,10 +16,7 @@ package org.springframework.integration.splitter; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.util.Comparator; @@ -72,9 +69,8 @@ public class StreamingSplitterTests { receivedMessages.sort(Comparator.comparing(o -> o.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class))); assertThat(receivedMessages.get(4) - .getHeaders() - .get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class), - is(messageQuantity)); + .getHeaders() + .get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class)).isEqualTo(messageQuantity); } @Test @@ -93,16 +89,14 @@ public class StreamingSplitterTests { splitter.afterPropertiesSet(); splitter.handleMessage(this.message); List> receivedMessages = replyChannel.clear(); - assertThat(receivedMessages.size(), is(messageQuantity)); + assertThat(receivedMessages.size()).isEqualTo(messageQuantity); for (Message receivedMessage : receivedMessages) { MessageHeaders headers = receivedMessage.getHeaders(); - assertTrue("Unexpected result with: " + headers, headers.containsKey(anyHeaderKey)); - assertThat("Unexpected result with: " + headers, - headers.get(anyHeaderKey, String.class), - is(anyHeaderValue)); - assertThat("Unexpected result with: " + headers, - headers.get(IntegrationMessageHeaderAccessor.CORRELATION_ID, UUID.class), - is(message.getHeaders().getId())); + assertThat(headers.containsKey(anyHeaderKey)).as("Unexpected result with: " + headers).isTrue(); + assertThat(headers.get(anyHeaderKey, String.class)).as("Unexpected result with: " + headers) + .isEqualTo(anyHeaderValue); + assertThat(headers.get(IntegrationMessageHeaderAccessor.CORRELATION_ID, UUID.class)) + .as("Unexpected result with: " + headers).isEqualTo(message.getHeaders().getId()); } } @@ -115,7 +109,7 @@ public class StreamingSplitterTests { splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); splitter.handleMessage(this.message); - assertThat(replyChannel.getQueueSize(), is(messageQuantity)); + assertThat(replyChannel.getQueueSize()).isEqualTo(messageQuantity); } @Test @@ -127,7 +121,7 @@ public class StreamingSplitterTests { splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); splitter.handleMessage(this.message); - assertThat(replyChannel.getQueueSize(), is(messageQuantity)); + assertThat(replyChannel.getQueueSize()).isEqualTo(messageQuantity); } @Test @@ -139,9 +133,9 @@ public class StreamingSplitterTests { splitter.setOutputChannel(replyChannel); splitter.afterPropertiesSet(); - new EventDrivenConsumer(replyChannel, message -> assertThat("Failure with msg: " + message, - message.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class), - is(Integer.valueOf((String) message.getPayload())))).start(); + new EventDrivenConsumer(replyChannel, message -> assertThat(message.getHeaders() + .get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class)) + .as("Failure with msg: " + message).isEqualTo(Integer.valueOf((String) message.getPayload()))).start(); splitter.handleMessage(this.message); } @@ -155,13 +149,13 @@ public class StreamingSplitterTests { splitter.afterPropertiesSet(); final AtomicInteger receivedMessageCounter = new AtomicInteger(0); new EventDrivenConsumer(replyChannel, message -> { - assertThat("Failure with msg: " + message, message.getPayload(), is(notNullValue())); + assertThat(message.getPayload()).as("Failure with msg: " + message).isNotNull(); receivedMessageCounter.incrementAndGet(); }).start(); splitter.handleMessage(this.message); - assertThat(receivedMessageCounter.get(), is(messageQuantity)); + assertThat(receivedMessageCounter.get()).isEqualTo(messageQuantity); } static class IteratorTestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java index 2837756ee5..7d01143f70 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.store; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willAnswer; import static org.mockito.Mockito.spy; @@ -55,14 +51,14 @@ public class MessageGroupQueueTests { MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), "FOO"); queue.put(new GenericMessage<>("foo")); Message result = queue.poll(100, TimeUnit.MILLISECONDS); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test public void testPollTimeout() throws Exception { MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), "FOO"); Message result = queue.poll(1, TimeUnit.MILLISECONDS); - assertNull(result); + assertThat(result).isNull(); } @Test @@ -87,9 +83,9 @@ public class MessageGroupQueueTests { Thread.currentThread().interrupt(); } }); - assertTrue(latch1.await(10, TimeUnit.SECONDS)); + assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); queue.put(new GenericMessage<>("foo")); - assertTrue(latch2.await(10, TimeUnit.SECONDS)); + assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); exec.shutdownNow(); } @@ -97,9 +93,9 @@ public class MessageGroupQueueTests { public void testSize() throws Exception { MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), "FOO"); queue.put(new GenericMessage("foo")); - assertEquals(1, queue.size()); + assertThat(queue.size()).isEqualTo(1); queue.poll(100, TimeUnit.MILLISECONDS); - assertEquals(0, queue.size()); + assertThat(queue.size()).isEqualTo(0); } @Test @@ -107,12 +103,12 @@ public class MessageGroupQueueTests { SimpleMessageStore messageGroupStore = new SimpleMessageStore(); MessageGroupQueue queue = new MessageGroupQueue(messageGroupStore, "FOO", 2); queue.put(new GenericMessage<>("foo")); - assertEquals(1, queue.remainingCapacity()); + assertThat(queue.remainingCapacity()).isEqualTo(1); queue.put(new GenericMessage<>("bar")); - assertEquals(0, queue.remainingCapacity()); + assertThat(queue.remainingCapacity()).isEqualTo(0); Message result = queue.poll(100, TimeUnit.MILLISECONDS); - assertNotNull(result); - assertEquals(1, queue.remainingCapacity()); + assertThat(result).isNotNull(); + assertThat(queue.remainingCapacity()).isEqualTo(1); } @Test @@ -120,7 +116,7 @@ public class MessageGroupQueueTests { SimpleMessageStore messageGroupStore = new SimpleMessageStore(); MessageGroupQueue queue = new MessageGroupQueue(messageGroupStore, "FOO", 1); queue.put(new GenericMessage<>("foo")); - assertFalse(queue.offer(new GenericMessage<>("bar"), 100, TimeUnit.MILLISECONDS)); + assertThat(queue.offer(new GenericMessage<>("bar"), 100, TimeUnit.MILLISECONDS)).isFalse(); } @Test @@ -128,7 +124,7 @@ public class MessageGroupQueueTests { MessageGroupQueue queue = new MessageGroupQueue(new SimpleMessageStore(), "FOO"); queue.put(new GenericMessage<>("foo")); Message result = queue.take(); - assertNotNull(result); + assertThat(result).isNotNull(); } @Test @@ -185,17 +181,17 @@ public class MessageGroupQueueTests { } for (int j = 0; j < 2 * concurrency; j++) { - assertTrue(completionService.take().get()); + assertThat(completionService.take().get()).isTrue(); } if (set != null) { // Ensure all items polled are unique - assertEquals(concurrency * maxPerTask, set.size()); + assertThat(set.size()).isEqualTo(concurrency * maxPerTask); } - assertEquals(0, queue.size()); + assertThat(queue.size()).isEqualTo(0); messageGroupStore.expireMessageGroups(-10000); - assertEquals(Integer.MAX_VALUE, queue.remainingCapacity()); + assertThat(queue.remainingCapacity()).isEqualTo(Integer.MAX_VALUE); executorService.shutdown(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreReaperTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreReaperTests.java index 74280cef62..ca1bbfd5c7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreReaperTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreReaperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.store; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; @@ -78,14 +76,14 @@ public class MessageStoreReaperTests { @Test public void testExpiry() throws Exception { messageStore.addMessageToGroup("FOO", new GenericMessage("foo")); - assertEquals(1, messageStore.getMessageGroup("FOO").size()); + assertThat(messageStore.getMessageGroup("FOO").size()).isEqualTo(1); // wait for expiry... int n = 0; while (n++ < 200 & messageStore.getMessageGroup("FOO").size() > 0) { Thread.sleep(50); } - assertEquals(0, messageStore.getMessageGroup("FOO").size()); - assertEquals(1, expiryCallback.groups.size()); + assertThat(messageStore.getMessageGroup("FOO").size()).isEqualTo(0); + assertThat(expiryCallback.groups.size()).isEqualTo(1); } @Test @@ -93,7 +91,7 @@ public class MessageStoreReaperTests { GenericMessage testMessage = new GenericMessage("foo"); messageStore2.addMessageToGroup("FOO", testMessage); - assertEquals(1, messageStore2.getMessageGroup("FOO").size()); + assertThat(messageStore2.getMessageGroup("FOO").size()).isEqualTo(1); reaper2.setExpireOnDestroy(true); reaper2.setTimeout(0); @@ -103,27 +101,27 @@ public class MessageStoreReaperTests { reaper2.start(); } - assertTrue(reaper2.isRunning()); + assertThat(reaper2.isRunning()).isTrue(); //reaper timeout is set to 0, but need to ensure positive elapsed time Thread.sleep(1L); reaper2.stop(); - assertTrue(!reaper2.isRunning()); + assertThat(!reaper2.isRunning()).isTrue(); - assertEquals(0, messageStore2.getMessageGroup("FOO").size()); - assertEquals(1, expiryCallback2.groups.size()); + assertThat(messageStore2.getMessageGroup("FOO").size()).isEqualTo(0); + assertThat(expiryCallback2.groups.size()).isEqualTo(1); messageStore2.addMessageToGroup("FOO", testMessage); - assertEquals(1, messageStore2.getMessageGroup("FOO").size()); + assertThat(messageStore2.getMessageGroup("FOO").size()).isEqualTo(1); reaper2.run(); - assertEquals(1, messageStore2.getMessageGroup("FOO").size()); + assertThat(messageStore2.getMessageGroup("FOO").size()).isEqualTo(1); reaper2.stop(); - assertEquals(1, messageStore2.getMessageGroup("FOO").size()); + assertThat(messageStore2.getMessageGroup("FOO").size()).isEqualTo(1); reaper2.start(); reaper2.run(); - assertEquals(0, messageStore2.getMessageGroup("FOO").size()); - assertEquals(2, expiryCallback2.groups.size()); + assertThat(messageStore2.getMessageGroup("FOO").size()).isEqualTo(0); + assertThat(expiryCallback2.groups.size()).isEqualTo(2); } @Test @@ -134,8 +132,8 @@ public class MessageStoreReaperTests { .setSequenceNumber(1) .build()); Message discard = this.discards.receive(10000); - assertNotNull(discard); - assertEquals("foo", discard.getPayload()); + assertThat(discard).isNotNull(); + assertThat(discard.getPayload()).isEqualTo("foo"); } public static class ExpiryCallback implements MessageGroupCallback { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java index 3bef21791c..c130c13308 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.store; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.Collection; @@ -42,7 +42,7 @@ public class MessageStoreTests { public void shouldRegisterCallbacks() throws Exception { TestMessageStore store = new TestMessageStore(); store.setExpiryCallbacks(Collections.singletonList((messageGroupStore, group) -> { })); - assertEquals(1, ((Collection) ReflectionTestUtils.getField(store, "expiryCallbacks")).size()); + assertThat(((Collection) ReflectionTestUtils.getField(store, "expiryCallbacks")).size()).isEqualTo(1); } @Test @@ -56,21 +56,21 @@ public class MessageStoreTests { }); store.expireMessageGroups(-10000); - assertEquals("[foo]", list.toString()); - assertEquals(0, store.getMessageGroup("bar").size()); + assertThat(list.toString()).isEqualTo("[foo]"); + assertThat(store.getMessageGroup("bar").size()).isEqualTo(0); } @Test public void testGroupCount() throws Exception { TestMessageStore store = new TestMessageStore(); - assertEquals(1, store.getMessageGroupCount()); + assertThat(store.getMessageGroupCount()).isEqualTo(1); } @Test public void testGroupSizes() throws Exception { TestMessageStore store = new TestMessageStore(); - assertEquals(1, store.getMessageCountForAllMessageGroups()); + assertThat(store.getMessageCountForAllMessageGroups()).isEqualTo(1); } private static class TestMessageStore extends SimpleMessageStore { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageGroupTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageGroupTests.java index 55afe2c024..cdfa21353d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageGroupTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageGroupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2016 the original author or authors. + * Copyright 2009-2019 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,10 +16,7 @@ package org.springframework.integration.store; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.willReturn; import static org.mockito.Mockito.mock; @@ -66,11 +63,11 @@ public class SimpleMessageGroupTests { prepareForSequenceAwareMessageGroup(); final Message message1 = MessageBuilder.withPayload("test").setSequenceNumber(1).build(); final Message message2 = MessageBuilder.fromMessage(message1).setSequenceNumber(1).build(); - assertThat(this.sequenceAwareGroup.canAdd(message1), is(true)); + assertThat(this.sequenceAwareGroup.canAdd(message1)).isTrue(); this.group.add(message1); this.group.add(message2); prepareForSequenceAwareMessageGroup(); - assertThat(this.sequenceAwareGroup.canAdd(message1), is(false)); + assertThat(this.sequenceAwareGroup.canAdd(message1)).isFalse(); } @Test @@ -78,11 +75,11 @@ public class SimpleMessageGroupTests { prepareForSequenceAwareMessageGroup(); final Message message1 = MessageBuilder.withPayload("test").build(); final Message message2 = MessageBuilder.fromMessage(message1).build(); - assertThat(this.sequenceAwareGroup.canAdd(message1), is(true)); + assertThat(this.sequenceAwareGroup.canAdd(message1)).isTrue(); this.group.add(message1); this.group.add(message2); prepareForSequenceAwareMessageGroup(); - assertThat(this.sequenceAwareGroup.canAdd(message1), is(true)); + assertThat(this.sequenceAwareGroup.canAdd(message1)).isTrue(); } @SuppressWarnings("unchecked") @@ -97,7 +94,7 @@ public class SimpleMessageGroupTests { messages.add(null); messages.add(m2); SimpleMessageGroup grp = new SimpleMessageGroup(messages, 1); - assertEquals(2, grp.getMessages().size()); + assertThat(grp.getMessages().size()).isEqualTo(2); } @Test @@ -114,7 +111,7 @@ public class SimpleMessageGroupTests { group.getMessages().contains(message); } watch.stop(); - assertTrue(watch.getTotalTimeMillis() < 5000); + assertThat(watch.getTotalTimeMillis() < 5000).isTrue(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java index 1b932c7eb1..566d303327 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,14 +16,8 @@ package org.springframework.integration.store; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.ArrayList; import java.util.Arrays; @@ -58,7 +52,7 @@ public class SimpleMessageStoreTests { SimpleMessageStore store = new SimpleMessageStore(); Message testMessage1 = MessageBuilder.withPayload("foo").build(); store.addMessage(testMessage1); - assertThat(store.getMessage(testMessage1.getHeaders().getId()), is(testMessage1)); + assertThat(store.getMessage(testMessage1.getHeaders().getId())).isEqualTo(testMessage1); } @Test(expected = MessagingException.class) @@ -81,8 +75,8 @@ public class SimpleMessageStoreTests { fail("Should have thrown"); } catch (Exception e) { - assertThat(e, instanceOf(MessagingException.class)); - assertThat(e.getMessage(), containsString("was out of capacity (1)")); + assertThat(e).isInstanceOf(MessagingException.class); + assertThat(e.getMessage()).contains("was out of capacity (1)"); } store.removeMessage(testMessage2.getHeaders().getId()); try { @@ -90,8 +84,8 @@ public class SimpleMessageStoreTests { fail("Should have thrown"); } catch (Exception e) { - assertThat(e, instanceOf(MessagingException.class)); - assertThat(e.getMessage(), containsString("was out of capacity (1)")); + assertThat(e).isInstanceOf(MessagingException.class); + assertThat(e.getMessage()).contains("was out of capacity (1)"); } store.removeMessage(testMessage1.getHeaders().getId()); store.addMessage(testMessage2); @@ -116,11 +110,11 @@ public class SimpleMessageStoreTests { // Simulate a blocked consumer Thread.sleep(10); Message t1 = store2.removeMessage(testMessage1.getHeaders().getId()); - assertEquals(testMessage1, t1); + assertThat(t1).isEqualTo(testMessage1); - assertTrue(message2Latch.await(10, TimeUnit.SECONDS)); + assertThat(message2Latch.await(10, TimeUnit.SECONDS)).isTrue(); Message t2 = store2.getMessage(testMessage2.getHeaders().getId()); - assertEquals(testMessage2, t2); + assertThat(t2).isEqualTo(testMessage2); exec.shutdownNow(); } @@ -162,7 +156,7 @@ public class SimpleMessageStoreTests { Thread.sleep(10); store2.removeMessagesFromGroup("foo", testMessage1); - assertTrue(message2Latch.await(10, TimeUnit.SECONDS)); + assertThat(message2Latch.await(10, TimeUnit.SECONDS)).isTrue(); MessageGroup messageGroup = store2.getMessageGroup("foo"); messageGroup.getMessages().contains(testMessage2); exec.shutdownNow(); @@ -198,8 +192,8 @@ public class SimpleMessageStoreTests { fail("Should have thrown"); } catch (Exception e) { - assertThat(e, instanceOf(MessagingException.class)); - assertThat(e.getMessage(), containsString("was out of capacity (1) for group 'foo'")); + assertThat(e).isInstanceOf(MessagingException.class); + assertThat(e.getMessage()).contains("was out of capacity (1) for group 'foo'"); } store.removeMessagesFromGroup("foo", testMessage2); try { @@ -207,8 +201,8 @@ public class SimpleMessageStoreTests { fail("Should have thrown"); } catch (Exception e) { - assertThat(e, instanceOf(MessagingException.class)); - assertThat(e.getMessage(), containsString("was out of capacity (1) for group 'foo'")); + assertThat(e).isInstanceOf(MessagingException.class); + assertThat(e.getMessage()).contains("was out of capacity (1) for group 'foo'"); } store.removeMessagesFromGroup("foo", testMessage1); store.addMessageToGroup("foo", testMessage2); @@ -220,7 +214,7 @@ public class SimpleMessageStoreTests { SimpleMessageStore store = new SimpleMessageStore(); Message testMessage1 = MessageBuilder.withPayload("foo").build(); store.addMessageToGroup("bar", testMessage1); - assertEquals(1, store.getMessageGroup("bar").size()); + assertThat(store.getMessageGroup("bar").size()).isEqualTo(1); } @Test @@ -231,8 +225,8 @@ public class SimpleMessageStoreTests { Message testMessage2 = store.getMessageGroup("bar").getOne(); store.removeMessagesFromGroup("bar", testMessage2); MessageGroup group = store.getMessageGroup("bar"); - assertEquals(0, group.size()); - assertEquals(0, store.getMessageGroup("bar").size()); + assertThat(group.size()).isEqualTo(0); + assertThat(store.getMessageGroup("bar").size()).isEqualTo(0); } @Test @@ -242,8 +236,8 @@ public class SimpleMessageStoreTests { store.addMessageToGroup("bar", MessageBuilder.withPayload("foo").build()); store.addMessageToGroup("bar", MessageBuilder.withPayload("foo").build()); store.removeMessageGroup("bar"); - assertEquals(0, store.getMessageGroup("bar").size()); - assertEquals(0, store.getMessageGroupCount()); + assertThat(store.getMessageGroup("bar").size()).isEqualTo(0); + assertThat(store.getMessageGroupCount()).isEqualTo(0); } } @@ -253,14 +247,14 @@ public class SimpleMessageStoreTests { store.setCopyOnGet(true); Message testMessage1 = MessageBuilder.withPayload("foo").build(); store.addMessageToGroup("bar", testMessage1); - assertNotSame(store.getMessageGroup("bar"), store.getMessageGroup("bar")); + assertThat(store.getMessageGroup("bar")).isNotSameAs(store.getMessageGroup("bar")); } @Test public void shouldRegisterCallbacks() throws Exception { SimpleMessageStore store = new SimpleMessageStore(); store.setExpiryCallbacks(Arrays.asList((messageGroupStore, group) -> { })); - assertEquals(1, ((Collection) ReflectionTestUtils.getField(store, "expiryCallbacks")).size()); + assertThat(((Collection) ReflectionTestUtils.getField(store, "expiryCallbacks")).size()).isEqualTo(1); } @Test @@ -275,11 +269,11 @@ public class SimpleMessageStoreTests { Message testMessage1 = MessageBuilder.withPayload("foo").build(); store.addMessageToGroup("bar", testMessage1); - assertEquals(1, store.getMessageGroup("bar").size()); + assertThat(store.getMessageGroup("bar").size()).isEqualTo(1); store.expireMessageGroups(-10000); - assertEquals("[foo]", list.toString()); - assertEquals(0, store.getMessageGroup("bar").size()); + assertThat(list.toString()).isEqualTo("[foo]"); + assertThat(store.getMessageGroup("bar").size()).isEqualTo(0); } @@ -294,10 +288,10 @@ public class SimpleMessageStoreTests { messages.add(message); } MessageGroup group = messageStore.getMessageGroup(groupId); - assertEquals(25, group.size()); + assertThat(group.size()).isEqualTo(25); messageStore.removeMessagesFromGroup(groupId, messages); group = messageStore.getMessageGroup(groupId); - assertEquals(0, group.size()); + assertThat(group.size()).isEqualTo(0); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/MessageBuilderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/MessageBuilderTests.java index 11650bb44a..3172ee755e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/MessageBuilderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/MessageBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.support; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -35,16 +33,16 @@ public class MessageBuilderTests { public void testReadOnlyHeaders() { DefaultMessageBuilderFactory factory = new DefaultMessageBuilderFactory(); Message message = factory.withPayload("bar").setHeader("foo", "baz").setHeader("qux", "fiz").build(); - assertThat(message.getHeaders().get("foo"), equalTo("baz")); - assertThat(message.getHeaders().get("qux"), equalTo("fiz")); + assertThat(message.getHeaders().get("foo")).isEqualTo("baz"); + assertThat(message.getHeaders().get("qux")).isEqualTo("fiz"); factory.setReadOnlyHeaders("foo"); message = factory.fromMessage(message).build(); - assertNull(message.getHeaders().get("foo")); - assertThat(message.getHeaders().get("qux"), equalTo("fiz")); + assertThat(message.getHeaders().get("foo")).isNull(); + assertThat(message.getHeaders().get("qux")).isEqualTo("fiz"); factory.addReadOnlyHeaders("qux"); message = factory.fromMessage(message).build(); - assertNull(message.getHeaders().get("foo")); - assertNull(message.getHeaders().get("qux")); + assertThat(message.getHeaders().get("foo")).isNull(); + assertThat(message.getHeaders().get("qux")).isNull(); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java index a00afbc236..96d8929449 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,14 +16,12 @@ package org.springframework.integration.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeader; -import static org.springframework.integration.test.matcher.PayloadMatcher.hasPayload; +import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; +import org.springframework.integration.test.predicate.MessagePredicate; import org.springframework.integration.test.support.AbstractRequestResponseScenarioTests; import org.springframework.integration.test.support.MessageValidator; import org.springframework.integration.test.support.PayloadValidator; @@ -37,7 +35,7 @@ public class MessageScenariosTests extends AbstractRequestResponseScenarioTests @Override protected List defineRequestResponseScenarios() { - List scenarios = new ArrayList(); + List scenarios = new ArrayList<>(); RequestResponseScenario scenario1 = new RequestResponseScenario( "inputChannel", "outputChannel") .setPayload("hello") @@ -45,12 +43,14 @@ public class MessageScenariosTests extends AbstractRequestResponseScenarioTests @Override protected void validateResponse(String response) { - assertEquals("HELLO", response); + assertThat(response).isEqualTo("HELLO"); } }); scenarios.add(scenario1); + Message resultMessage = MessageBuilder.withPayload("HELLO").setHeader("foo", "bar").build(); + RequestResponseScenario scenario2 = new RequestResponseScenario( "inputChannel", "outputChannel") .setMessage(MessageBuilder.withPayload("hello").setHeader("foo", "bar").build()) @@ -58,8 +58,7 @@ public class MessageScenariosTests extends AbstractRequestResponseScenarioTests @Override protected void validateMessage(Message message) { - assertThat(message, hasPayload("HELLO")); - assertThat(message, hasHeader("foo", "bar")); + assertThat(message).matches(new MessagePredicate(resultMessage)); } }); @@ -72,8 +71,7 @@ public class MessageScenariosTests extends AbstractRequestResponseScenarioTests @Override protected void validateMessage(Message message) { - assertThat(message, hasPayload("HELLO")); - assertThat(message, hasHeader("foo", "bar")); + assertThat(message).matches(new MessagePredicate(resultMessage)); } }); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java index efc3cbbee6..40d77d48e0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 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,7 @@ package org.springframework.integration.support; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.nio.ByteBuffer; import java.util.HashMap; @@ -53,8 +51,8 @@ public class MutableMessageTests { MutableMessage mutableMessage = new MutableMessage<>(payload, headerMap); MutableMessageHeaders headers = mutableMessage.getHeaders(); - assertThat(headers.getRawHeaders(), hasEntry(MessageHeaders.ID, uuid)); - assertThat(headers.getRawHeaders(), hasEntry(MessageHeaders.TIMESTAMP, timestamp)); + assertThat(headers.getRawHeaders()).containsEntry(MessageHeaders.ID, uuid); + assertThat(headers.getRawHeaders()).containsEntry(MessageHeaders.TIMESTAMP, timestamp); } @Test @@ -73,7 +71,7 @@ public class MutableMessageTests { headers.remove("eep"); headers.putAll(additional); - assertThat(headers.getRawHeaders(), hasEntry("foo", "bar")); + assertThat(headers.getRawHeaders()).containsEntry("foo", "bar"); } @Test @@ -89,8 +87,8 @@ public class MutableMessageTests { headerMapStrings.put(MessageHeaders.ID, uuid.toString()); headerMapStrings.put(MessageHeaders.TIMESTAMP, timestamp.toString()); MutableMessage mutableMessageStrings = new MutableMessage<>(payload, headerMapStrings); - assertEquals(uuid, mutableMessageStrings.getHeaders().getId()); - assertEquals(timestamp, mutableMessageStrings.getHeaders().getTimestamp()); + assertThat(mutableMessageStrings.getHeaders().getId()).isEqualTo(uuid); + assertThat(mutableMessageStrings.getHeaders().getTimestamp()).isEqualTo(timestamp); // UUID as byte[]; timestamp as Long Map headerMapByte = new HashMap<>(); @@ -103,8 +101,8 @@ public class MutableMessageTests { headerMapByte.put(MessageHeaders.ID, uuidAsBytes); headerMapByte.put(MessageHeaders.TIMESTAMP, timestamp); MutableMessage mutableMessageBytes = new MutableMessage<>(payload, headerMapByte); - assertEquals(uuid, mutableMessageBytes.getHeaders().getId()); - assertEquals(timestamp, mutableMessageBytes.getHeaders().getTimestamp()); + assertThat(mutableMessageBytes.getHeaders().getId()).isEqualTo(uuid); + assertThat(mutableMessageBytes.getHeaders().getTimestamp()).isEqualTo(timestamp); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/SingleScenarioTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/SingleScenarioTests.java index 94ab83981c..c41b9cce85 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/SingleScenarioTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/SingleScenarioTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.support; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.springframework.integration.test.support.PayloadValidator; import org.springframework.integration.test.support.RequestResponseScenario; @@ -34,7 +34,7 @@ public class SingleScenarioTests extends SingleRequestResponseScenarioTests { .setResponseValidator(new PayloadValidator() { @Override protected void validateResponse(String response) { - assertEquals("HELLO", response); + assertThat(response).isEqualTo("HELLO"); } }); return scenario; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/converter/MapMessageConverterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/converter/MapMessageConverterTests.java index 30f96909b8..5eea2048d7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/converter/MapMessageConverterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/converter/MapMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.support.converter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Map; @@ -50,25 +47,25 @@ public class MapMessageConverterTests { @SuppressWarnings("unchecked") Map headers = (Map) map.get("headers"); - assertNotNull(headers); - assertNotNull(map.get("payload")); - assertEquals("foo", map.get("payload")); - assertNotNull(headers.get("bar")); - assertEquals("baz", headers.get("bar")); - assertNull(headers.get("baz")); + assertThat(headers).isNotNull(); + assertThat(map.get("payload")).isNotNull(); + assertThat(map.get("payload")).isEqualTo("foo"); + assertThat(headers.get("bar")).isNotNull(); + assertThat(headers.get("bar")).isEqualTo("baz"); + assertThat(headers.get("baz")).isNull(); headers.put("baz", "qux"); Message converted = converter.toMessage(map, null); - assertEquals("foo", converted.getPayload()); - assertEquals("baz", converted.getHeaders().get("bar")); - assertEquals("qux", converted.getHeaders().get("baz")); + assertThat(converted.getPayload()).isEqualTo("foo"); + assertThat(converted.getHeaders().get("bar")).isEqualTo("baz"); + assertThat(converted.getHeaders().get("baz")).isEqualTo("qux"); converter.setFilterHeadersInToMessage(true); converted = converter.toMessage(map, null); - assertEquals("foo", converted.getPayload()); - assertEquals("baz", converted.getHeaders().get("bar")); - assertNull(converted.getHeaders().get("baz")); + assertThat(converted.getPayload()).isEqualTo("foo"); + assertThat(converted.getHeaders().get("bar")).isEqualTo("baz"); + assertThat(converted.getHeaders().get("baz")).isNull(); } @Test @@ -89,7 +86,7 @@ public class MapMessageConverterTests { fail("Expected exception"); } catch (IllegalArgumentException e) { - assertEquals("'payload' entry cannot be null", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("'payload' entry cannot be null"); } } @@ -104,11 +101,11 @@ public class MapMessageConverterTests { @SuppressWarnings("unchecked") Map headers = (Map) map.get("headers"); - assertNotNull(headers); - assertEquals(0, headers.size()); + assertThat(headers).isNotNull(); + assertThat(headers.size()).isEqualTo(0); map.remove("headers"); Message converted = converter.toMessage(map, null); - assertEquals("foo", converted.getPayload()); + assertThat(converted.getPayload()).isEqualTo("foo"); } @Test @@ -123,10 +120,10 @@ public class MapMessageConverterTests { @SuppressWarnings("unchecked") Map headers = (Map) map.get("headers"); - assertNotNull(headers); - assertNotNull(map.get("payload")); - assertEquals("foo", map.get("payload")); - assertFalse(headers.keySet().contains("bar")); - assertEquals(0, headers.size()); + assertThat(headers).isNotNull(); + assertThat(map.get("payload")).isNotNull(); + assertThat(map.get("payload")).isEqualTo("foo"); + assertThat(headers.keySet().contains("bar")).isFalse(); + assertThat(headers.size()).isEqualTo(0); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiatorTests.java index 6c9257c262..1658d64e4e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2018 the original author or authors. + * Copyright 2012-2019 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,11 +16,7 @@ package org.springframework.integration.support.leader; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; @@ -80,27 +76,27 @@ public class LockRegistryLeaderInitiatorTests { @Test public void startAndStop() throws Exception { - assertThat(this.initiator.getContext().isLeader(), is(false)); + assertThat(this.initiator.getContext().isLeader()).isFalse(); this.initiator.start(); - assertThat(this.initiator.isRunning(), is(true)); - assertTrue(this.granted.await(10, TimeUnit.SECONDS)); - assertThat(this.initiator.getContext().isLeader(), is(true)); + assertThat(this.initiator.isRunning()).isTrue(); + assertThat(this.granted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(this.initiator.getContext().isLeader()).isTrue(); Thread.sleep(200L); - assertThat(this.initiator.getContext().isLeader(), is(true)); + assertThat(this.initiator.getContext().isLeader()).isTrue(); this.initiator.stop(); - assertTrue(this.revoked.await(10, TimeUnit.SECONDS)); - assertThat(this.initiator.getContext().isLeader(), is(false)); + assertThat(this.revoked.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(this.initiator.getContext().isLeader()).isFalse(); } @Test public void yield() throws Exception { - assertThat(this.initiator.getContext().isLeader(), is(false)); + assertThat(this.initiator.getContext().isLeader()).isFalse(); this.initiator.start(); - assertThat(this.initiator.isRunning(), is(true)); - assertTrue(this.granted.await(10, TimeUnit.SECONDS)); - assertThat(this.initiator.getContext().isLeader(), is(true)); + assertThat(this.initiator.isRunning()).isTrue(); + assertThat(this.granted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(this.initiator.getContext().isLeader()).isTrue(); this.initiator.getContext().yield(); - assertThat(this.revoked.await(10, TimeUnit.SECONDS), is(true)); + assertThat(this.revoked.await(10, TimeUnit.SECONDS)).isTrue(); this.initiator.stop(); } @@ -112,11 +108,11 @@ public class LockRegistryLeaderInitiatorTests { CountDownLatch other = new CountDownLatch(1); another.setLeaderEventPublisher(new CountingPublisher(other)); this.initiator.start(); - assertThat(this.granted.await(20, TimeUnit.SECONDS), is(true)); + assertThat(this.granted.await(20, TimeUnit.SECONDS)).isTrue(); another.start(); this.initiator.stop(); - assertThat(other.await(20, TimeUnit.SECONDS), is(true)); - assertThat(another.getContext().isLeader(), is(true)); + assertThat(other.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat(another.getContext().isLeader()).isTrue(); another.stop(); } @@ -130,12 +126,12 @@ public class LockRegistryLeaderInitiatorTests { another.setLeaderEventPublisher(new CountingPublisher(other, new CountDownLatch(1), failedAcquireLatch)); another.setPublishFailedEvents(true); this.initiator.start(); - assertThat(this.granted.await(20, TimeUnit.SECONDS), is(true)); + assertThat(this.granted.await(20, TimeUnit.SECONDS)).isTrue(); another.start(); - assertThat(failedAcquireLatch.await(20, TimeUnit.SECONDS), is(true)); + assertThat(failedAcquireLatch.await(20, TimeUnit.SECONDS)).isTrue(); this.initiator.stop(); - assertThat(other.await(20, TimeUnit.SECONDS), is(true)); - assertThat(another.getContext().isLeader(), is(true)); + assertThat(other.await(20, TimeUnit.SECONDS)).isTrue(); + assertThat(another.getContext().isLeader()).isTrue(); another.stop(); } @@ -159,8 +155,8 @@ public class LockRegistryLeaderInitiatorTests { this.initiator.start(); - assertTrue(onGranted.await(10, TimeUnit.SECONDS)); - assertTrue(initiator.getContext().isLeader()); + assertThat(onGranted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(initiator.getContext().isLeader()).isTrue(); this.initiator.stop(); } @@ -209,18 +205,18 @@ public class LockRegistryLeaderInitiatorTests { second.start(); // first initiator should lead and publish granted event - assertThat(firstGranted.await(10, TimeUnit.SECONDS), is(true)); - assertThat(first.getContext().isLeader(), is(true)); - assertThat(second.getContext().isLeader(), is(false)); + assertThat(firstGranted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(first.getContext().isLeader()).isTrue(); + assertThat(second.getContext().isLeader()).isFalse(); // simulate first registry instance unable to obtain lock, for example due to lock timeout firstLocked.set(false); // second initiator should take lead and publish granted event, first initiator should publish revoked event - assertThat(secondGranted.await(10, TimeUnit.SECONDS), is(true)); - assertThat(firstRevoked.await(10, TimeUnit.SECONDS), is(true)); - assertThat(second.getContext().isLeader(), is(true)); - assertThat(first.getContext().isLeader(), is(false)); + assertThat(secondGranted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(firstRevoked.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(second.getContext().isLeader()).isTrue(); + assertThat(first.getContext().isLeader()).isFalse(); first.stop(); second.stop(); @@ -266,7 +262,7 @@ public class LockRegistryLeaderInitiatorTests { another.start(); Throwable throwable = throwableAtomicReference.get(); - assertNull(throwable); + assertThat(throwable).isNull(); } @Test @@ -294,9 +290,9 @@ public class LockRegistryLeaderInitiatorTests { another.start(); - assertTrue(onGranted.await(10, TimeUnit.SECONDS)); - assertTrue(another.getContext().isLeader()); - assertTrue(exceptionThrown.get()); + assertThat(onGranted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(another.getContext().isLeader()).isTrue(); + assertThat(exceptionThrown.get()).isTrue(); another.stop(); } @@ -309,7 +305,7 @@ public class LockRegistryLeaderInitiatorTests { ExecutorService executorService = TestUtils.getPropertyValue(this.initiator, "executorService", ExecutorService.class); - assertTrue(executorService.isShutdown()); + assertThat(executorService.isShutdown()).isTrue(); } @Test @@ -321,7 +317,7 @@ public class LockRegistryLeaderInitiatorTests { another.start(); another.destroy(); - assertFalse(executorService.isShutdown()); + assertThat(executorService.isShutdown()).isFalse(); } private static class CountingPublisher implements LeaderEventPublisher { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/locks/DefaultLockRegistryTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/locks/DefaultLockRegistryTests.java index 9c9f9f3cbb..1efdc6c65f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/locks/DefaultLockRegistryTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/locks/DefaultLockRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.support.locks; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.locks.Lock; @@ -47,9 +46,9 @@ public class DefaultLockRegistryTests { Lock a = registry.obtain(23); Lock b = registry.obtain(new Object()); Lock c = registry.obtain("hello"); - assertSame(a, b); - assertSame(a, c); - assertSame(b, c); + assertThat(b).isSameAs(a); + assertThat(c).isSameAs(a); + assertThat(c).isSameAs(b); } @Test @@ -69,7 +68,7 @@ public class DefaultLockRegistryTests { return 256; } }); - assertSame(lock1, lock2); + assertThat(lock2).isSameAs(lock1); } @Test @@ -89,7 +88,7 @@ public class DefaultLockRegistryTests { return 255; } }); - assertNotSame(lock1, lock2); + assertThat(lock2).isNotSameAs(lock1); } @Test @@ -127,7 +126,7 @@ public class DefaultLockRegistryTests { for (int i = 0; i < 4; i++) { for (int j = 1; j < 4; j++) { if (i != j) { - assertNotSame(locks[i], locks[j]); + assertThat(locks[j]).isNotSameAs(locks[i]); } } } @@ -160,10 +159,10 @@ public class DefaultLockRegistryTests { return 3; } }); - assertSame(locks[0], moreLocks[0]); - assertSame(locks[1], moreLocks[1]); - assertSame(locks[2], moreLocks[2]); - assertSame(locks[3], moreLocks[3]); + assertThat(moreLocks[0]).isSameAs(locks[0]); + assertThat(moreLocks[1]).isSameAs(locks[1]); + assertThat(moreLocks[2]).isSameAs(locks[2]); + assertThat(moreLocks[3]).isSameAs(locks[3]); moreLocks[0] = registry.obtain(new Object() { @Override @@ -192,10 +191,10 @@ public class DefaultLockRegistryTests { return 7; } }); - assertSame(locks[0], moreLocks[0]); - assertSame(locks[1], moreLocks[1]); - assertSame(locks[2], moreLocks[2]); - assertSame(locks[3], moreLocks[3]); + assertThat(moreLocks[0]).isSameAs(locks[0]); + assertThat(moreLocks[1]).isSameAs(locks[1]); + assertThat(moreLocks[2]).isSameAs(locks[2]); + assertThat(moreLocks[3]).isSameAs(locks[3]); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/management/DefaultMessageChannelMetricsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/management/DefaultMessageChannelMetricsTests.java index edc3a3ffdb..9639664c96 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/management/DefaultMessageChannelMetricsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/management/DefaultMessageChannelMetricsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2018 the original author or authors. + * Copyright 2017-2019 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,8 @@ package org.springframework.integration.support.management; -import org.junit.Assert; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.springframework.integration.channel.QueueChannel; @@ -45,14 +46,9 @@ public class DefaultMessageChannelMetricsTests { theMessageChannel.send(theInputMessage, SEND_TIMEOUT); } - Assert.assertEquals( - "Message count should match number of sent messages", - MESSAGE_COUNT, - theMessageChannel.getSendCount()); - Assert.assertEquals( - "Error count should indicate no errors", - 0, - theMessageChannel.getSendErrorCount()); + assertThat(theMessageChannel.getSendCount()).as("Message count should match number of sent messages") + .isEqualTo(MESSAGE_COUNT); + assertThat(theMessageChannel.getSendErrorCount()).as("Error count should indicate no errors").isEqualTo(0); } @Test @@ -66,14 +62,10 @@ public class DefaultMessageChannelMetricsTests { theMessageChannel.send(theInputMessage, SEND_TIMEOUT); } - Assert.assertEquals( - "Message count should match number of sent messages", - MESSAGE_COUNT, - theMessageChannel.getSendCount()); - Assert.assertEquals( - "Error count should indicate errors half the messages", - MESSAGE_COUNT / 2, - theMessageChannel.getSendErrorCount()); + assertThat(theMessageChannel.getSendCount()).as("Message count should match number of sent messages") + .isEqualTo(MESSAGE_COUNT); + assertThat(theMessageChannel.getSendErrorCount()).as("Error count should indicate errors half the messages") + .isEqualTo(MESSAGE_COUNT / 2); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRateTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRateTests.java index 296560f165..5faf2b4dcb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRateTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,13 @@ package org.springframework.integration.support.management; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Deque; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.assertj.core.data.Offset; import org.junit.Ignore; import org.junit.Test; @@ -47,9 +44,9 @@ public class ExponentialMovingAverageRateTests { @Test public void testGetCount() { - assertEquals(0, history.getCount()); + assertThat(history.getCount()).isEqualTo(0); history.increment(); - assertEquals(1, history.getCount()); + assertThat(history.getCount()).isEqualTo(1); } @Test @@ -63,12 +60,12 @@ public class ExponentialMovingAverageRateTests { history.increment(now); } final Deque times = TestUtils.getPropertyValue(history, "times", Deque.class); - assertEquals(Long.valueOf(now), times.peekFirst()); - assertEquals(Long.valueOf(now), times.peekLast()); + assertThat(times.peekFirst()).isEqualTo(Long.valueOf(now)); + assertThat(times.peekLast()).isEqualTo(Long.valueOf(now)); //increment just so we'll have a different value between first and last history.increment(System.nanoTime() - sleepTime * 1000000); - assertNotEquals(times.peekFirst(), times.peekLast()); + assertThat(times.peekLast()).isNotEqualTo(times.peekFirst()); /* * We've called Thread.sleep twice with the same value in quick @@ -78,19 +75,19 @@ public class ExponentialMovingAverageRateTests { * time. */ double timeSinceLastMeasurement = history.getTimeSinceLastMeasurement(); - assertTrue(timeSinceLastMeasurement > sleepTime); - assertTrue(timeSinceLastMeasurement <= (1.5 * sleepTime)); + assertThat(timeSinceLastMeasurement > sleepTime).isTrue(); + assertThat(timeSinceLastMeasurement <= (1.5 * sleepTime)).isTrue(); } @Test public void testGetEarlyMean() throws Exception { long t0 = System.currentTimeMillis(); - assertEquals(0, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(0, Offset.offset(0.01)); Thread.sleep(20L); history.increment(); long elapsed = System.currentTimeMillis() - t0; if (elapsed < 30L) { - assertTrue(history.getMean() > 10); + assertThat(history.getMean() > 10).isTrue(); } else { logger.warn("Test took too long to verify mean"); @@ -100,7 +97,7 @@ public class ExponentialMovingAverageRateTests { @Test public void testGetMean() throws Exception { long t0 = System.currentTimeMillis(); - assertEquals(0, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(0, Offset.offset(0.01)); Thread.sleep(20L); history.increment(); Thread.sleep(20L); @@ -109,12 +106,12 @@ public class ExponentialMovingAverageRateTests { Statistics statisticsBefore = history.getStatistics(); long elapsed = System.currentTimeMillis() - t0; if (elapsed < 50L) { - assertTrue(before > 10); + assertThat(before > 10).isTrue(); Thread.sleep(20L); elapsed = System.currentTimeMillis() - t0; if (elapsed < 80L) { - assertThat(history.getMean(), lessThan(before)); - assertThat(history.getStatistics().getMean(), lessThan(statisticsBefore.getMean())); + assertThat(history.getMean()).isLessThan(before); + assertThat(history.getStatistics().getMean()).isLessThan(statisticsBefore.getMean()); } else { logger.warn("Test took too long to verify mean"); @@ -127,29 +124,29 @@ public class ExponentialMovingAverageRateTests { @Test public void testGetStandardDeviation() throws Exception { - assertEquals(0, history.getStandardDeviation(), 0.01); + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); Thread.sleep(20L); history.increment(); Thread.sleep(22L); history.increment(); Thread.sleep(18L); - assertTrue("Standard deviation should be non-zero: " + history, history.getStandardDeviation() > 0); + assertThat(history.getStandardDeviation() > 0).as("Standard deviation should be non-zero: " + history).isTrue(); } @Test public void testReset() throws Exception { - assertEquals(0, history.getStandardDeviation(), 0.01); + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); history.increment(); Thread.sleep(30L); history.increment(); - assertNotEquals(0, history.getStandardDeviation(), 0.0); + assertThat(0.0).isNotEqualTo(history.getStandardDeviation()); history.reset(); - assertEquals(0, history.getStandardDeviation(), 0.01); - assertEquals(0, history.getCount()); - assertEquals(0, history.getTimeSinceLastMeasurement(), 0.01); - assertEquals(0, history.getMean(), 0.01); - assertEquals(0, history.getMin(), 0.01); - assertEquals(0, history.getMax(), 0.01); + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); + assertThat(history.getCount()).isEqualTo(0); + assertThat(history.getTimeSinceLastMeasurement()).isCloseTo(0, Offset.offset(0.01)); + assertThat(history.getMean()).isCloseTo(0, Offset.offset(0.01)); + assertThat(history.getMin()).isCloseTo(0, Offset.offset(0.01)); + assertThat(history.getMax()).isCloseTo(0, Offset.offset(0.01)); } @Test @@ -163,7 +160,7 @@ public class ExponentialMovingAverageRateTests { } watch.stop(); double calculatedRate = count / (double) watch.getTotalTimeMillis() * 1000; - assertEquals(calculatedRate, rate.getMean(), 4000000); + assertThat(rate.getMean()).isEqualTo(calculatedRate, Offset.offset(4000000d)); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRatioTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRatioTests.java index eac2396346..79f422ef98 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRatioTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageRatioTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 @@ package org.springframework.integration.support.management; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThan; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Deque; -import org.hamcrest.Matchers; +import org.assertj.core.data.Offset; import org.junit.Ignore; import org.junit.Test; @@ -40,19 +35,18 @@ import org.springframework.integration.test.util.TestUtils; @Ignore("Very sensitive to the time. Don't forget to test after some changes.") public class ExponentialMovingAverageRatioTests { - private final ExponentialMovingAverageRatio history = new ExponentialMovingAverageRatio( - 0.5, 10, true); + private final ExponentialMovingAverageRatio history = new ExponentialMovingAverageRatio(0.5, 10, true); @Test public void testGetCount() { - assertEquals(0, history.getCount()); + assertThat(history.getCount()).isEqualTo(0); history.success(); - assertEquals(1, history.getCount()); + assertThat(history.getCount()).isEqualTo(1); } @Test @SuppressWarnings("unchecked") - public void testGetTimeSinceLastMeasurement() throws Exception { + public void testGetTimeSinceLastMeasurement() { long sleepTime = 20L; // fill history with the same value. long now = System.nanoTime() - 2 * sleepTime * 1000000; @@ -60,12 +54,12 @@ public class ExponentialMovingAverageRatioTests { history.success(now); } final Deque times = TestUtils.getPropertyValue(history, "times", Deque.class); - assertEquals(Long.valueOf(now), times.peekFirst()); - assertEquals(Long.valueOf(now), times.peekLast()); + assertThat(times.peekFirst()).isEqualTo(Long.valueOf(now)); + assertThat(times.peekLast()).isEqualTo(Long.valueOf(now)); //increment just so we'll have a different value between first and last history.success(System.nanoTime() - sleepTime * 1000000); - assertNotEquals(times.peekFirst(), times.peekLast()); + assertThat(times.peekLast()).isNotEqualTo(times.peekFirst()); /* * We've called Thread.sleep twice with the same value in quick @@ -75,94 +69,94 @@ public class ExponentialMovingAverageRatioTests { * time. */ double timeSinceLastMeasurement = history.getTimeSinceLastMeasurement(); - assertThat(timeSinceLastMeasurement, Matchers.greaterThan((double) (sleepTime / 100))); - assertThat(timeSinceLastMeasurement, Matchers.lessThanOrEqualTo(1.5 * sleepTime / 100)); + assertThat(timeSinceLastMeasurement).isGreaterThan((double) (sleepTime / 100)); + assertThat(timeSinceLastMeasurement).isLessThanOrEqualTo(1.5 * sleepTime / 100); } @Test - public void testGetEarlyMean() throws Exception { - assertEquals(1, history.getMean(), 0.01); + public void testGetEarlyMean() { + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); history.success(); - assertEquals(1, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); } @Test - public void testGetEarlyFailure() throws Exception { - assertEquals(1, history.getMean(), 0.01); + public void testGetEarlyFailure() { + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); history.failure(); - assertEquals(0, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(0, Offset.offset(0.01)); } @Test public void testDecayedMean() throws Exception { history.failure(System.nanoTime() - 200000000); - assertEquals(average(0, Math.exp(-0.4)), history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(average(0, Math.exp(-0.4)), Offset.offset(0.01)); history.success(); history.failure(); double mean = history.getMean(); Statistics statistics = history.getStatistics(); Thread.sleep(50); - assertThat(history.getMean(), greaterThan(mean)); - assertThat(history.getStatistics().getMean(), greaterThan(statistics.getMean())); + assertThat(history.getMean()).isGreaterThan(mean); + assertThat(history.getStatistics().getMean()).isGreaterThan(statistics.getMean()); } @Test - public void testGetMean() throws Exception { - assertEquals(1, history.getMean(), 0.01); + public void testGetMean() { + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); history.success(); - assertEquals(1, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); history.success(); - assertEquals(1, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); history.success(); - assertEquals(1, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); } @Test - public void testGetMeanFailuresHighRate() throws Exception { - assertEquals(1, history.getMean(), 0.01); + public void testGetMeanFailuresHighRate() { + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); history.success(); // need an extra now that we can't determine the time between the first and previous history.success(); - assertEquals(average(1), history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(average(1), Offset.offset(0.01)); history.failure(); - assertEquals(average(1, 0.5), history.getMean(), 0.1); + assertThat(history.getMean()).isCloseTo(average(1, 0.5), Offset.offset(0.1)); history.success(); - assertEquals(average(1, 0.5, 0.67), history.getMean(), 0.1); + assertThat(history.getMean()).isCloseTo(average(1, 0.5, 0.67), Offset.offset(0.1)); } @Test - public void testGetMeanFailuresLowRate() throws Exception { - assertEquals(1, history.getMean(), 0.01); + public void testGetMeanFailuresLowRate() { + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); history.failure(); // need an extra now that we can't determine the time between the first and previous history.failure(); - assertEquals(average(0), history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(average(0), Offset.offset(0.01)); history.failure(); - assertEquals(average(0, 0), history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(average(0, 0), Offset.offset(0.01)); history.success(); - assertEquals(average(0, 0, 0.33), history.getMean(), 0.1); + assertThat(history.getMean()).isCloseTo(average(0, 0, 0.33), Offset.offset(0.1)); } @Test - public void testGetStandardDeviation() throws Exception { - assertEquals(0, history.getStandardDeviation(), 0.01); + public void testGetStandardDeviation() { + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); history.success(); - assertEquals(0, history.getStandardDeviation(), 1); + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(1d)); } @Test - public void testReset() throws Exception { - assertEquals(0, history.getStandardDeviation(), 0.01); + public void testReset() { + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); history.success(); history.failure(); - assertThat(history.getStandardDeviation(), not(equalTo(0))); + assertThat(history.getStandardDeviation()).isNotEqualTo(0); history.reset(); - assertEquals(0, history.getStandardDeviation(), 0.01); - assertEquals(0, history.getCount()); - assertEquals(0, history.getTimeSinceLastMeasurement(), 0.01); - assertEquals(1, history.getMean(), 0.01); - assertEquals(0, history.getMin(), 0.01); - assertEquals(0, history.getMax(), 0.01); + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); + assertThat(history.getCount()).isEqualTo(0); + assertThat(history.getTimeSinceLastMeasurement()).isCloseTo(0, Offset.offset(0.01)); + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); + assertThat(history.getMin()).isCloseTo(0, Offset.offset(0.01)); + assertThat(history.getMax()).isCloseTo(0, Offset.offset(0.01)); history.success(); - assertEquals(1, history.getMin(), 0.01); + assertThat(history.getMin()).isCloseTo(1, Offset.offset(0.01)); } private double average(double... values) { @@ -186,8 +180,8 @@ public class ExponentialMovingAverageRatioTests { ratio.success(); } } - assertEquals(0.9, ratio.getMax(), 0.02); - assertEquals(0.9, ratio.getMean(), 0.03); + assertThat(ratio.getMax()).isCloseTo(0.9, Offset.offset(0.02)); + assertThat(ratio.getMean()).isCloseTo(0.9, Offset.offset(0.03)); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageTests.java index 1a1ca1f5f5..de16416bd7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/management/ExponentialMovingAverageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,9 @@ package org.springframework.integration.support.management; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; +import org.assertj.core.data.Offset; import org.junit.Ignore; import org.junit.Test; @@ -33,7 +33,8 @@ public class ExponentialMovingAverageTests { private final ExponentialMovingAverage history = new ExponentialMovingAverage(10); - @Test @Ignore // used to compare LinkedList to ArrayDeque which was 35% faster + @Test + @Ignore // used to compare LinkedList to ArrayDeque which was 35% faster public void perf() { for (int i = 0; i < 100000000; i++) { history.append(0.0); @@ -42,43 +43,44 @@ public class ExponentialMovingAverageTests { @Test public void testGetCount() { - assertEquals(0, history.getCount()); + assertThat(history.getCount()).isEqualTo(0); history.append(1); - assertEquals(1, history.getCount()); + assertThat(history.getCount()).isEqualTo(1); } @Test - public void testGetMean() throws Exception { - assertEquals(0, history.getMean(), 0.01); + public void testGetMean() { + assertThat(history.getMean()).isCloseTo(0, Offset.offset(0.01)); history.append(1); history.append(1); - assertEquals(1, history.getMean(), 0.01); + assertThat(history.getMean()).isCloseTo(1, Offset.offset(0.01)); } @Test - public void testGetStandardDeviation() throws Exception { - assertEquals(0, history.getStandardDeviation(), 0.01); + public void testGetStandardDeviation() { + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); history.append(1); history.append(1); - assertEquals(0, history.getStandardDeviation(), 0.01); + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); } @Test - public void testReset() throws Exception { - assertEquals(0, history.getStandardDeviation(), 0.01); + public void testReset() { + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); history.append(1); history.append(2); - assertFalse(0 == history.getStandardDeviation()); + assertThat(0 == history.getStandardDeviation()).isFalse(); history.reset(); - assertEquals(0, history.getStandardDeviation(), 0.01); + assertThat(history.getStandardDeviation()).isCloseTo(0, Offset.offset(0.01)); // INT-2165 - assertEquals(String.format("[N=%d, min=%f, max=%f, mean=%f, sigma=%f]", 0, 0d, 0d, 0d, 0d), history.toString()); + assertThat(history.toString()) + .isEqualTo(String.format("[N=%d, min=%f, max=%f, mean=%f, sigma=%f]", 0, 0d, 0d, 0d, 0d)); history.append(1); - assertEquals(1, history.getMin(), 0.01); + assertThat(history.getMin()).isCloseTo(1, Offset.offset(0.01)); } @Test - public void testAv() throws Exception { + public void testAv() { ExponentialMovingAverage av = new ExponentialMovingAverage(10); for (int i = 0; i < 10000; i++) { switch (i % 3) { @@ -93,29 +95,30 @@ public class ExponentialMovingAverageTests { break; } } - assertEquals(40, av.getMax(), 0.1); - assertEquals(20, av.getMin(), 0.1); - assertEquals(30, av.getMean(), 1.0); + assertThat(av.getMax()).isCloseTo(40, Offset.offset(0.1)); + assertThat(av.getMin()).isCloseTo(20, Offset.offset(0.1)); + assertThat(av.getMean()).isCloseTo(30, Offset.offset(1.0)); } - @Test @Ignore - public void testPerf() throws Exception { + @Test + @Ignore + public void testPerf() { ExponentialMovingAverage av = new ExponentialMovingAverage(10); for (int i = 0; i < 10000000; i++) { switch (i % 4) { - case 0: - av.append(20); - break; - case 1: - av.append(30); - break; - case 2: - av.append(40); - break; + case 0: + av.append(20); + break; + case 1: + av.append(30); + break; + case 2: + av.append(40); + break; - case 3: - av.append(50); - break; + case 3: + av.append(50); + break; } } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/management/IntegrationManagementConfigurerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/management/IntegrationManagementConfigurerTests.java index d01772cbb6..2947a22278 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/management/IntegrationManagementConfigurerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/management/IntegrationManagementConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 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,10 +16,7 @@ package org.springframework.integration.support.management; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -67,9 +64,9 @@ public class IntegrationManagementConfigurerTests { return null; } }; - assertTrue(channel.isLoggingEnabled()); - assertTrue(handler.isLoggingEnabled()); - assertTrue(source.isLoggingEnabled()); + assertThat(channel.isLoggingEnabled()).isTrue(); + assertThat(handler.isLoggingEnabled()).isTrue(); + assertThat(source.isLoggingEnabled()).isTrue(); channel.setCountsEnabled(true); channel.setStatsEnabled(true); ApplicationContext ctx = mock(ApplicationContext.class); @@ -83,11 +80,11 @@ public class IntegrationManagementConfigurerTests { configurer.setApplicationContext(ctx); configurer.setDefaultLoggingEnabled(false); configurer.afterSingletonsInstantiated(); - assertFalse(channel.isLoggingEnabled()); - assertFalse(handler.isLoggingEnabled()); - assertFalse(source.isLoggingEnabled()); - assertTrue(channel.isCountsEnabled()); - assertTrue(channel.isStatsEnabled()); + assertThat(channel.isLoggingEnabled()).isFalse(); + assertThat(handler.isLoggingEnabled()).isFalse(); + assertThat(source.isLoggingEnabled()).isFalse(); + assertThat(channel.isCountsEnabled()).isTrue(); + assertThat(channel.isStatsEnabled()).isTrue(); } @Test @@ -95,12 +92,12 @@ public class IntegrationManagementConfigurerTests { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigEmptyAnnotation.class); AbstractMessageChannel channel = ctx.getBean("channel", AbstractMessageChannel.class); - assertTrue(channel.isCountsEnabled()); - assertTrue(channel.isStatsEnabled()); - assertThat(TestUtils.getPropertyValue(channel, "channelMetrics"), - instanceOf(DefaultMessageChannelMetrics.class)); + assertThat(channel.isCountsEnabled()).isTrue(); + assertThat(channel.isStatsEnabled()).isTrue(); + assertThat(TestUtils.getPropertyValue(channel, "channelMetrics")) + .isInstanceOf(DefaultMessageChannelMetrics.class); channel = ctx.getBean("loggingOffChannel", AbstractMessageChannel.class); - assertFalse(channel.isLoggingEnabled()); + assertThat(channel.isLoggingEnabled()).isFalse(); ctx.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/mutable/MutableMessageBuilderFactoryTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/mutable/MutableMessageBuilderFactoryTests.java index 253f1e319c..a42825eb82 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/mutable/MutableMessageBuilderFactoryTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/mutable/MutableMessageBuilderFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2019 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,7 @@ package org.springframework.integration.support.mutable; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -63,7 +63,7 @@ public class MutableMessageBuilderFactoryTests { boolean result = this.latch.await(2L, TimeUnit.SECONDS); - assertTrue("A failure means that that MMBF wasn't used", result); + assertThat(result).as("A failure means that that MMBF wasn't used").isTrue(); } @Configuration diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transaction/TransactionInterceptorBuilderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transaction/TransactionInterceptorBuilderTests.java index 415612bb7b..85c0ed09de 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transaction/TransactionInterceptorBuilderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transaction/TransactionInterceptorBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 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,11 +16,8 @@ package org.springframework.integration.transaction; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -59,13 +56,13 @@ public class TransactionInterceptorBuilderTests { } private void verify(TransactionInterceptor interceptor, PlatformTransactionManager txm) throws Exception { - assertSame(txm, interceptor.getTransactionManager()); + assertThat(interceptor.getTransactionManager()).isSameAs(txm); TransactionAttribute atts = interceptor.getTransactionAttributeSource() .getTransactionAttribute(TransactionInterceptorBuilderTests.class.getDeclaredMethod("test"), null); - Assert.assertThat(atts.getPropagationBehavior(), equalTo(Propagation.REQUIRES_NEW.value())); - Assert.assertThat(atts.getIsolationLevel(), equalTo(Isolation.SERIALIZABLE.value())); - Assert.assertThat(atts.getTimeout(), equalTo(42)); - assertTrue(atts.isReadOnly()); + assertThat(atts.getPropagationBehavior()).isEqualTo(Propagation.REQUIRES_NEW.value()); + assertThat(atts.getIsolationLevel()).isEqualTo(Isolation.SERIALIZABLE.value()); + assertThat(atts.getTimeout()).isEqualTo(42); + assertThat(atts.isReadOnly()).isTrue(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ClaimCheckTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ClaimCheckTransformerTests.java index 069b6ae6d5..3d94a84ca5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ClaimCheckTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ClaimCheckTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.UUID; @@ -41,7 +41,7 @@ public class ClaimCheckTransformerTests { ClaimCheckInTransformer transformer = new ClaimCheckInTransformer(store); Message input = MessageBuilder.withPayload("test").build(); Message output = transformer.transform(input); - assertEquals(input.getHeaders().getId(), output.getPayload()); + assertThat(output.getPayload()).isEqualTo(input.getHeaders().getId()); } @Test @@ -53,7 +53,7 @@ public class ClaimCheckTransformerTests { ClaimCheckOutTransformer transformer = new ClaimCheckOutTransformer(store); Message input = MessageBuilder.withPayload(storedId).build(); Message output = transformer.transform(input); - assertEquals("test", output.getPayload()); + assertThat(output.getPayload()).isEqualTo("test"); } @Test(expected = MessageTransformationException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/CodecTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/CodecTransformerTests.java index d2c33d95dd..e8bee72720 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/CodecTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/CodecTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.io.InputStream; @@ -45,18 +44,18 @@ public class CodecTransformerTests { EncodingPayloadTransformer enc = new EncodingPayloadTransformer(codec); Message message = new GenericMessage("bar"); byte[] transformed = enc.doTransform(message); - assertArrayEquals("foo".getBytes(), transformed); + assertThat(transformed).isEqualTo("foo".getBytes()); DecodingTransformer dec = new DecodingTransformer(codec, String.class); - assertEquals("foo", dec.doTransform(new GenericMessage(transformed))); + assertThat(dec.doTransform(new GenericMessage(transformed))).isEqualTo("foo"); dec = new DecodingTransformer(codec, new SpelExpressionParser().parseExpression("T(Integer)")); dec.setEvaluationContext(new StandardEvaluationContext()); - assertEquals(42, dec.doTransform(new GenericMessage(transformed))); + assertThat(dec.doTransform(new GenericMessage(transformed))).isEqualTo(42); dec = new DecodingTransformer(codec, new SpelExpressionParser().parseExpression("headers['type']")); dec.setEvaluationContext(new StandardEvaluationContext()); - assertEquals(42, dec.doTransform(new GenericMessage(transformed, - Collections.singletonMap("type", Integer.class)))); + assertThat(dec.doTransform(new GenericMessage(transformed, + Collections.singletonMap("type", Integer.class)))).isEqualTo(42); } public static class MyCodec implements Codec { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java index cd5cfea576..5663f99353 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ContentEnricherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.transformer; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalToIgnoringCase; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.util.Collections; @@ -150,8 +142,8 @@ public class ContentEnricherTests { enricher.handleMessage(requestMessage); } catch (ReplyRequiredException e) { - assertEquals("No reply produced by handler 'Enricher', and its 'requiresReply' property is set to true.", - e.getMessage()); + assertThat(e.getMessage()) + .isEqualTo("No reply produced by handler 'Enricher', and its 'requiresReply' property is set to true."); return; } finally { @@ -186,8 +178,8 @@ public class ContentEnricherTests { enricher.handleMessage(requestMessage); } catch (MessageDeliveryException e) { - assertThat(e.getMessage(), equalToIgnoringCase("failed to send message to channel '" + requestChannelName - + "' within timeout: " + requestTimeout)); + assertThat(e.getMessage()).isEqualToIgnoringCase("failed to send message to channel '" + requestChannelName + + "' within timeout: " + requestTimeout); } } @@ -217,7 +209,7 @@ public class ContentEnricherTests { Message requestMessage = MessageBuilder.withPayload(target).setReplyChannel(replyChannel).build(); enricher.handleMessage(requestMessage); Message reply = replyChannel.receive(0); - assertEquals("Doe, John", ((Target) reply.getPayload()).getName()); + assertThat(((Target) reply.getPayload()).getName()).isEqualTo("Doe, John"); } @Test @@ -233,7 +225,8 @@ public class ContentEnricherTests { enricher.afterPropertiesSet(); } catch (IllegalStateException e) { - assertEquals("If the replyChannel is set, then the requestChannel must not be null", e.getMessage()); + assertThat(e.getMessage()) + .isEqualTo("If the replyChannel is set, then the requestChannel must not be null"); return; } @@ -250,7 +243,7 @@ public class ContentEnricherTests { enricher.setReplyTimeout(null); } catch (IllegalArgumentException e) { - assertEquals("replyTimeout must not be null", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("replyTimeout must not be null"); return; } @@ -267,7 +260,7 @@ public class ContentEnricherTests { enricher.setRequestTimeout(null); } catch (IllegalArgumentException e) { - assertEquals("requestTimeout must not be null", e.getMessage()); + assertThat(e.getMessage()).isEqualTo("requestTimeout must not be null"); return; } @@ -288,7 +281,7 @@ public class ContentEnricherTests { Message requestMessage = MessageBuilder.withPayload(target).setReplyChannel(replyChannel).build(); enricher.handleMessage(requestMessage); Message reply = replyChannel.receive(0); - assertEquals("just a static string", ((Target) reply.getPayload()).getName()); + assertThat(((Target) reply.getPayload()).getName()).isEqualTo("just a static string"); } @Test @@ -302,7 +295,8 @@ public class ContentEnricherTests { enricher.afterPropertiesSet(); } catch (IllegalStateException e) { - assertEquals("If the replyChannel is set, then the requestChannel must not be null", e.getMessage()); + assertThat(e.getMessage()) + .isEqualTo("If the replyChannel is set, then the requestChannel must not be null"); return; } @@ -334,8 +328,8 @@ public class ContentEnricherTests { enricher.handleMessage(requestMessage); Message reply = replyChannel.receive(0); Target result = (Target) reply.getPayload(); - assertEquals("test", result.getName()); - assertEquals("Doe, John", result.getChild().getName()); + assertThat(result.getName()).isEqualTo("test"); + assertThat(result.getChild().getName()).isEqualTo("Doe, John"); } @Test @@ -364,8 +358,8 @@ public class ContentEnricherTests { enricher.handleMessage(requestMessage); Message reply = replyChannel.receive(0); Target result = (Target) reply.getPayload(); - assertEquals("Doe, John", result.getName()); - assertNotSame(target, result); + assertThat(result.getName()).isEqualTo("Doe, John"); + assertThat(result).isNotSameAs(target); } @Test @@ -396,9 +390,9 @@ public class ContentEnricherTests { enricher.handleMessage(requestMessage); Message reply = replyChannel.receive(0); TargetUser result = (TargetUser) reply.getPayload(); - assertEquals("Doe, John", result.getName()); + assertThat(result.getName()).isEqualTo("Doe, John"); - assertSame(target, result); + assertThat(result).isSameAs(target); } @Test @@ -431,7 +425,7 @@ public class ContentEnricherTests { enricher.handleMessage(requestMessage); } catch (MessageHandlingException e) { - assertThat(e.getMessage(), containsString("Failed to clone payload object")); + assertThat(e.getMessage()).contains("Failed to clone payload object"); return; } @@ -446,9 +440,9 @@ public class ContentEnricherTests { enricher.afterPropertiesSet(); - assertTrue(enricher.isRunning()); + assertThat(enricher.isRunning()).isTrue(); enricher.stop(); - assertTrue(enricher.isRunning()); + assertThat(enricher.isRunning()).isTrue(); } @Test @@ -469,11 +463,11 @@ public class ContentEnricherTests { enricher.afterPropertiesSet(); enricher.start(); - assertTrue(enricher.isRunning()); + assertThat(enricher.isRunning()).isTrue(); enricher.stop(); - assertFalse(enricher.isRunning()); + assertThat(enricher.isRunning()).isFalse(); enricher.start(); - assertTrue(enricher.isRunning()); + assertThat(enricher.isRunning()).isTrue(); enricher.stop(); } @@ -525,7 +519,7 @@ public class ContentEnricherTests { enricher.handleMessage(requestMessage); Message reply = replyChannel.receive(10000); Target result = (Target) reply.getPayload(); - assertEquals("failed target", result.getName()); + assertThat(result.getName()).isEqualTo("failed target"); } @Test @@ -540,8 +534,9 @@ public class ContentEnricherTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), containsString("ContentEnricher cannot override 'id' and 'timestamp' read-only headers.")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()) + .contains("ContentEnricher cannot override 'id' and 'timestamp' read-only headers."); } } @@ -557,8 +552,9 @@ public class ContentEnricherTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), containsString("ContentEnricher cannot override 'id' and 'timestamp' read-only headers.")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()) + .contains("ContentEnricher cannot override 'id' and 'timestamp' read-only headers."); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionHeaderEnricherIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionHeaderEnricherIntegrationTests.java index c1d685a79c..4fedc1642b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionHeaderEnricherIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionHeaderEnricherIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,7 +49,7 @@ public class DynamicExpressionHeaderEnricherIntegrationTests { Message message = MessageBuilder.withPayload("test").build(); this.input.send(message); Message result = output.receive(0); - assertEquals("foo", result.getHeaders().get("testHeader")); + assertThat(result.getHeaders().get("testHeader")).isEqualTo("foo"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionTransformerIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionTransformerIntegrationTests.java index 0ab10c0f83..40d0758687 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionTransformerIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/DynamicExpressionTransformerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -49,7 +49,7 @@ public class DynamicExpressionTransformerIntegrationTests { Message message = MessageBuilder.withPayload(new TestBean()).setHeader("bar", 123).build(); this.input.send(message); Message result = output.receive(0); - assertEquals("test123", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test123"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java index 43dd2453d7..d4c655144a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/HeaderFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,9 @@ package org.springframework.integration.transformer; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeaderKey; import java.util.Date; import java.util.UUID; @@ -56,10 +49,10 @@ public class HeaderFilterTests { .build(); HeaderFilter filter = new HeaderFilter("x", "z"); Message result = filter.transform(message); - assertNotNull(result); - assertNotNull(result.getHeaders().get("y")); - assertNull(result.getHeaders().get("x")); - assertNull(result.getHeaders().get("z")); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("y")).isNotNull(); + assertThat(result.getHeaders().get("x")).isNull(); + assertThat(result.getHeaders().get("z")).isNull(); } @Test @@ -78,13 +71,13 @@ public class HeaderFilterTests { handler.afterPropertiesSet(); handler.handleMessage(message); Message result = replyChannel.receive(0); - assertNotNull(result); - assertNotNull(result.getHeaders().get("y")); - assertNull(result.getHeaders().get("x")); - assertNull(result.getHeaders().get("z")); - assertEquals("testErrorChannel", result.getHeaders().getErrorChannel()); - assertEquals(replyChannel, result.getHeaders().getReplyChannel()); - assertEquals(correlationId, new IntegrationMessageHeaderAccessor(result).getCorrelationId()); + assertThat(result).isNotNull(); + assertThat(result.getHeaders().get("y")).isNotNull(); + assertThat(result.getHeaders().get("x")).isNull(); + assertThat(result.getHeaders().get("z")).isNull(); + assertThat(result.getHeaders().getErrorChannel()).isEqualTo("testErrorChannel"); + assertThat(result.getHeaders().getReplyChannel()).isEqualTo(replyChannel); + assertThat(new IntegrationMessageHeaderAccessor(result).getCorrelationId()).isEqualTo(correlationId); } @Test @@ -95,8 +88,8 @@ public class HeaderFilterTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), containsString("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers.")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()).contains("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers."); } } @@ -108,8 +101,8 @@ public class HeaderFilterTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), containsString("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers.")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()).contains("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers."); } } @@ -122,8 +115,8 @@ public class HeaderFilterTests { fail("BeanInitializationException expected"); } catch (Exception e) { - assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e.getMessage(), containsString("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers.")); + assertThat(e).isInstanceOf(BeanInitializationException.class); + assertThat(e.getMessage()).contains("HeaderFilter cannot remove 'id' and 'timestamp' read-only headers."); } } @@ -139,8 +132,9 @@ public class HeaderFilterTests { Message result = filter.transform(message); - assertThat(result, hasHeaderKey(MessageHeaders.TIMESTAMP)); - assertThat(result, not(hasHeaderKey("time"))); + assertThat(result.getHeaders()) + .containsKey(MessageHeaders.TIMESTAMP) + .doesNotContainKey("time"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java index 5f775c468e..c581512636 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.Map; @@ -75,12 +73,12 @@ public class MapToObjectTransformerTests { transformer.setBeanFactory(this.context); Message newMessage = transformer.transform(message); Person person = (Person) newMessage.getPayload(); - assertNotNull(person); - assertEquals("Justin", person.getFname()); - assertEquals("Case", person.getLname()); - assertNull(person.getSsn()); - assertNotNull(person.getAddress()); - assertEquals("1123 Main st", person.getAddress().getStreet()); + assertThat(person).isNotNull(); + assertThat(person.getFname()).isEqualTo("Justin"); + assertThat(person.getLname()).isEqualTo("Case"); + assertThat(person.getSsn()).isNull(); + assertThat(person.getAddress()).isNotNull(); + assertThat(person.getAddress().getStreet()).isEqualTo("1123 Main st"); } @Test @@ -99,12 +97,12 @@ public class MapToObjectTransformerTests { transformer.setBeanFactory(ac.getBeanFactory()); Message newMessage = transformer.transform(message); Person person = (Person) newMessage.getPayload(); - assertNotNull(person); - assertEquals("Justin", person.getFname()); - assertEquals("Case", person.getLname()); - assertNull(person.getSsn()); - assertNotNull(person.getAddress()); - assertEquals("1123 Main st", person.getAddress().getStreet()); + assertThat(person).isNotNull(); + assertThat(person.getFname()).isEqualTo("Justin"); + assertThat(person.getLname()).isEqualTo("Case"); + assertThat(person.getSsn()).isNull(); + assertThat(person.getAddress()).isNotNull(); + assertThat(person.getAddress().getStreet()).isEqualTo("1123 Main st"); ac.close(); } @@ -126,11 +124,11 @@ public class MapToObjectTransformerTests { Message newMessage = transformer.transform(message); Person person = (Person) newMessage.getPayload(); - assertNotNull(person); - assertEquals("Justin", person.getFname()); - assertEquals("Case", person.getLname()); - assertNotNull(person.getAddress()); - assertEquals("1123 Main st", person.getAddress().getStreet()); + assertThat(person).isNotNull(); + assertThat(person.getFname()).isEqualTo("Justin"); + assertThat(person.getLname()).isEqualTo("Case"); + assertThat(person.getAddress()).isNotNull(); + assertThat(person.getAddress().getStreet()).isEqualTo("1123 Main st"); } public static class Person { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java index 83ef1e37dc..e052e642a4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -52,7 +52,7 @@ public class MessageHistoryParameterTests { @Test public void test() { input.send(new GenericMessage("foo")); - assertNotNull(output.receive(10000)); + assertThat(output.receive(10000)).isNotNull(); } public static class MessageHistoryAwareTransformer { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java index 22442307b0..65efd64c79 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java @@ -16,8 +16,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.lang.reflect.Method; @@ -48,7 +47,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage<>("foo"); Message result = transformer.transform(message); - assertEquals("FOO!", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("FOO!"); } @Test @@ -58,7 +57,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage("foo"); Message result = transformer.transform(message); - assertEquals("FOO!", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("FOO!"); } @Test @@ -69,7 +68,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage<>(123); Message result = transformer.transform(message); - assertEquals("123!", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("123!"); } @Test @@ -79,7 +78,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage<>(123); Message result = transformer.transform(message); - assertEquals("123!", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("123!"); } @Test(expected = MessageHandlingException.class) @@ -108,7 +107,7 @@ public class MethodInvokingTransformerTests { Message message = MessageBuilder.withPayload("foo") .setHeader("number", 123).build(); Message result = transformer.transform(message); - assertEquals("foo123", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo123"); } @Test @@ -119,7 +118,7 @@ public class MethodInvokingTransformerTests { Message message = MessageBuilder.withPayload("foo") .setHeader("number", 123).build(); Message result = transformer.transform(message); - assertEquals("foo123", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo123"); } @Test(expected = MessageHandlingException.class) @@ -140,7 +139,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").setHeader("number", 99).build(); Message result = transformer.transform(message); - assertEquals("foo99", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo99"); } @Test @@ -151,7 +150,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").build(); Message result = transformer.transform(message); - assertEquals("foonull", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foonull"); } @Test @@ -162,7 +161,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test").build(); Message result = transformer.transform(message); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); } @Test @@ -172,7 +171,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test").build(); Message result = transformer.transform(message); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); } @Test @@ -187,14 +186,14 @@ public class MethodInvokingTransformerTests { props.setProperty("prop3", "baz"); Message message = new GenericMessage<>(props); Message result = (Message) transformer.transform(message); - assertEquals(Properties.class, result.getPayload().getClass()); + assertThat(result.getPayload().getClass()).isEqualTo(Properties.class); Properties payload = result.getPayload(); - assertEquals("foo", payload.getProperty("prop1")); - assertEquals("bar", payload.getProperty("prop2")); - assertEquals("baz", payload.getProperty("prop3")); - assertNull(result.getHeaders().get("prop1")); - assertNull(result.getHeaders().get("prop2")); - assertNull(result.getHeaders().get("prop3")); + assertThat(payload.getProperty("prop1")).isEqualTo("foo"); + assertThat(payload.getProperty("prop2")).isEqualTo("bar"); + assertThat(payload.getProperty("prop3")).isEqualTo("baz"); + assertThat(result.getHeaders().get("prop1")).isNull(); + assertThat(result.getHeaders().get("prop2")).isNull(); + assertThat(result.getHeaders().get("prop3")).isNull(); } @Test @@ -208,14 +207,14 @@ public class MethodInvokingTransformerTests { props.setProperty("prop3", "baz"); Message message = new GenericMessage<>(props); Message result = (Message) transformer.transform(message); - assertEquals(Properties.class, result.getPayload().getClass()); + assertThat(result.getPayload().getClass()).isEqualTo(Properties.class); Properties payload = result.getPayload(); - assertEquals("foo", payload.getProperty("prop1")); - assertEquals("bar", payload.getProperty("prop2")); - assertEquals("baz", payload.getProperty("prop3")); - assertNull(result.getHeaders().get("prop1")); - assertNull(result.getHeaders().get("prop2")); - assertNull(result.getHeaders().get("prop3")); + assertThat(payload.getProperty("prop1")).isEqualTo("foo"); + assertThat(payload.getProperty("prop2")).isEqualTo("bar"); + assertThat(payload.getProperty("prop3")).isEqualTo("baz"); + assertThat(result.getHeaders().get("prop1")).isNull(); + assertThat(result.getHeaders().get("prop2")).isNull(); + assertThat(result.getHeaders().get("prop3")).isNull(); } @Test @@ -225,7 +224,7 @@ public class MethodInvokingTransformerTests { transformer.setBeanFactory(mock(BeanFactory.class)); GenericMessage message = new GenericMessage<>("test"); Message result = transformer.transform(message); - assertNull(result); + assertThat(result).isNull(); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -242,10 +241,10 @@ public class MethodInvokingTransformerTests { .setHeader("prop1", "bad") .setHeader("prop3", "baz").build(); Message result = transformer.transform(message); - assertEquals("test", result.getPayload()); - assertEquals("foo", result.getHeaders().get("prop1")); - assertEquals("bar", result.getHeaders().get("prop2")); - assertEquals("baz", result.getHeaders().get("prop3")); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get("prop1")).isEqualTo("foo"); + assertThat(result.getHeaders().get("prop2")).isEqualTo("bar"); + assertThat(result.getHeaders().get("prop3")).isEqualTo("baz"); } @SuppressWarnings({ "rawtypes", "unchecked" }) @@ -262,10 +261,10 @@ public class MethodInvokingTransformerTests { .setHeader("prop1", "bad") .setHeader("prop3", "baz").build(); Message result = transformer.transform(message); - assertEquals("test", result.getPayload()); - assertEquals("foo", result.getHeaders().get("prop1")); - assertEquals("bar", result.getHeaders().get("prop2")); - assertEquals("baz", result.getHeaders().get("prop3")); + assertThat(result.getPayload()).isEqualTo("test"); + assertThat(result.getHeaders().get("prop1")).isEqualTo("foo"); + assertThat(result.getHeaders().get("prop2")).isEqualTo("bar"); + assertThat(result.getHeaders().get("prop3")).isEqualTo("baz"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToMapTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToMapTransformerTests.java index 6805f8abe3..8deaf835fa 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToMapTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToMapTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.transformer; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.math.BigDecimal; @@ -70,7 +66,7 @@ public class ObjectToMapTransformerTests { Message transformedMessage = transformer.transform(message); Map transformedMap = (Map) transformedMessage.getPayload(); - assertNotNull(transformedMap); + assertThat(transformedMap).isNotNull(); Object valueFromTheMap = null; Object valueFromExpression = null; @@ -79,78 +75,78 @@ public class ObjectToMapTransformerTests { expression = parser.parseExpression("departments[0]"); valueFromTheMap = transformedMap.get("departments[0]"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.address.coordinates"); valueFromTheMap = transformedMap.get("person.address.coordinates"); valueFromExpression = expression.getValue(context, employee, Map.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.akaNames[0]"); valueFromTheMap = transformedMap.get("person.akaNames[0]"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("testMapInMapData.internalMapA.bar"); valueFromTheMap = transformedMap.get("testMapInMapData.internalMapA.bar"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("companyAddress.street"); valueFromTheMap = transformedMap.get("companyAddress.street"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.lname"); valueFromTheMap = transformedMap.get("person.lname"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.address.mapWithListData.mapWithListTestData[1]"); valueFromTheMap = transformedMap.get("person.address.mapWithListData.mapWithListTestData[1]"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("companyAddress.city"); valueFromTheMap = transformedMap.get("companyAddress.city"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.akaNames[2]"); valueFromTheMap = transformedMap.get("person.akaNames[2]"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.child"); valueFromTheMap = transformedMap.get("person.child"); valueFromExpression = expression.getValue(context, employee, String.class); - assertNull(valueFromTheMap); - assertNull(valueFromExpression); + assertThat(valueFromTheMap).isNull(); + assertThat(valueFromExpression).isNull(); expression = parser.parseExpression("testMapInMapData.internalMapA.foo"); valueFromTheMap = transformedMap.get("testMapInMapData.internalMapA.foo"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.address.city"); valueFromTheMap = transformedMap.get("person.address.city"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("companyAddress.coordinates.latitude[0]"); valueFromTheMap = transformedMap.get("companyAddress.coordinates.latitude[0]"); valueFromExpression = expression.getValue(context, employee, Integer.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("person.remarks[1].baz"); valueFromTheMap = transformedMap.get("person.remarks[1].baz"); valueFromExpression = expression.getValue(context, employee, String.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); expression = parser.parseExpression("listOfDates[0][1]"); valueFromTheMap = new Date((Long) transformedMap.get("listOfDates[0][1]")); valueFromExpression = expression.getValue(context, employee, Date.class); - assertEquals(valueFromTheMap, valueFromExpression); + assertThat(valueFromExpression).isEqualTo(valueFromTheMap); } @Test(expected = MessageTransformationException.class) @@ -177,7 +173,7 @@ public class ObjectToMapTransformerTests { // If JSR310 support is enabled by calling findAndRegisterModules() on the Jackson mapper, // Instant field should not be broken. Thus the count should exactly be 1 here. - assertEquals(1L, transformedMap.values().stream().filter(Objects::nonNull).count()); + assertThat(transformedMap.values().stream().filter(Objects::nonNull).count()).isEqualTo(1L); } @Test @@ -191,13 +187,13 @@ public class ObjectToMapTransformerTests { new ObjectToMapTransformer(new Jackson2JsonObjectMapper(customMapper)) .transformPayload(employee); - assertThat(transformedMap.get("listOfDates[0][0]"), instanceOf(String.class)); + assertThat(transformedMap.get("listOfDates[0][0]")).isInstanceOf(String.class); - assertThat(transformedMap.get("listOfDates[0][1]"), instanceOf(String.class)); + assertThat(transformedMap.get("listOfDates[0][1]")).isInstanceOf(String.class); - assertThat(transformedMap.get("listOfDates[1][0]"), instanceOf(String.class)); + assertThat(transformedMap.get("listOfDates[1][0]")).isInstanceOf(String.class); - assertThat(transformedMap.get("listOfDates[1][1]"), instanceOf(String.class)); + assertThat(transformedMap.get("listOfDates[1][1]")).isInstanceOf(String.class); } @SuppressWarnings({ "unchecked", "rawtypes" }) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java index cf04f44b39..86abd0432a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.Charset; @@ -36,21 +36,21 @@ public class ObjectToStringTransformerTests { public void stringPayload() { Transformer transformer = new ObjectToStringTransformer(); Message result = transformer.transform(new GenericMessage("foo")); - assertEquals("foo", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo"); } @Test public void objectPayload() { Transformer transformer = new ObjectToStringTransformer(); Message result = transformer.transform(new GenericMessage(new TestBean())); - assertEquals("test", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test"); } @Test public void byteArrayPayload() throws Exception { Transformer transformer = new ObjectToStringTransformer(); Message result = transformer.transform(new GenericMessage(("foo" + '\u0fff').getBytes("UTF-8"))); - assertEquals("foo" + '\u0fff', result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo" + '\u0fff'); } @Test @@ -58,14 +58,14 @@ public class ObjectToStringTransformerTests { String defaultCharsetName = Charset.defaultCharset().toString(); Transformer transformer = new ObjectToStringTransformer(defaultCharsetName); Message result = transformer.transform(new GenericMessage("foo".getBytes(defaultCharsetName))); - assertEquals("foo", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo"); } @Test public void charArrayPayload() { Transformer transformer = new ObjectToStringTransformer(); Message result = transformer.transform(new GenericMessage("foo".toCharArray())); - assertEquals("foo", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo"); } private static class TestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java index e6c8710d40..249b02c802 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,12 +16,8 @@ package org.springframework.integration.transformer; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; @@ -47,9 +43,9 @@ public class PayloadDeserializingTransformerTests { PayloadDeserializingTransformer transformer = new PayloadDeserializingTransformer(); Message result = transformer.transform(new GenericMessage(serialized)); Object payload = result.getPayload(); - assertNotNull(payload); - assertEquals(String.class, payload.getClass()); - assertEquals("foo", payload); + assertThat(payload).isNotNull(); + assertThat(payload.getClass()).isEqualTo(String.class); + assertThat(payload).isEqualTo("foo"); } @Test @@ -62,9 +58,9 @@ public class PayloadDeserializingTransformerTests { PayloadDeserializingTransformer transformer = new PayloadDeserializingTransformer(); Message result = transformer.transform(new GenericMessage(serialized)); Object payload = result.getPayload(); - assertNotNull(payload); - assertEquals(TestBean.class, payload.getClass()); - assertEquals(testBean.name, ((TestBean) payload).name); + assertThat(payload).isNotNull(); + assertThat(payload.getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) payload).name).isEqualTo(testBean.name); } @Test @@ -81,15 +77,15 @@ public class PayloadDeserializingTransformerTests { fail("expected security exception"); } catch (MessageTransformationException e) { - assertThat(e.getCause().getCause(), instanceOf(SecurityException.class)); - assertThat(e.getCause().getCause().getMessage(), startsWith("Attempt to deserialize unauthorized")); + assertThat(e.getCause().getCause()).isInstanceOf(SecurityException.class); + assertThat(e.getCause().getCause().getMessage()).startsWith("Attempt to deserialize unauthorized"); } transformer.setWhiteListPatterns("org.*"); Message result = transformer.transform(new GenericMessage(serialized)); Object payload = result.getPayload(); - assertNotNull(payload); - assertEquals(TestBean.class, payload.getClass()); - assertEquals(testBean.name, ((TestBean) payload).name); + assertThat(payload).isNotNull(); + assertThat(payload.getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) payload).name).isEqualTo(testBean.name); } @Test(expected = MessageTransformationException.class) @@ -104,7 +100,7 @@ public class PayloadDeserializingTransformerTests { PayloadDeserializingTransformer transformer = new PayloadDeserializingTransformer(); transformer.setConverter(source -> "Converted"); Message message = transformer.transform(MessageBuilder.withPayload("Test".getBytes()).build()); - assertEquals("Converted", message.getPayload()); + assertThat(message.getPayload()).isEqualTo("Converted"); } @SuppressWarnings("serial") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java index c300b4376c..29bec2f2e2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; @@ -40,12 +38,12 @@ public class PayloadSerializingTransformerTests { PayloadSerializingTransformer transformer = new PayloadSerializingTransformer(); Message result = transformer.transform(new GenericMessage("foo")); Object payload = result.getPayload(); - assertNotNull(payload); - assertTrue(payload instanceof byte[]); + assertThat(payload).isNotNull(); + assertThat(payload instanceof byte[]).isTrue(); ByteArrayInputStream byteStream = new ByteArrayInputStream((byte[]) payload); ObjectInputStream objectStream = new ObjectInputStream(byteStream); Object deserialized = objectStream.readObject(); - assertEquals("foo", deserialized); + assertThat(deserialized).isEqualTo("foo"); } @Test @@ -54,13 +52,13 @@ public class PayloadSerializingTransformerTests { TestBean testBean = new TestBean("test"); Message result = transformer.transform(new GenericMessage(testBean)); Object payload = result.getPayload(); - assertNotNull(payload); - assertTrue(payload instanceof byte[]); + assertThat(payload).isNotNull(); + assertThat(payload instanceof byte[]).isTrue(); ByteArrayInputStream byteStream = new ByteArrayInputStream((byte[]) payload); ObjectInputStream objectStream = new ObjectInputStream(byteStream); Object deserialized = objectStream.readObject(); - assertEquals(TestBean.class, deserialized.getClass()); - assertEquals(testBean.name, ((TestBean) deserialized).name); + assertThat(deserialized.getClass()).isEqualTo(TestBean.class); + assertThat(((TestBean) deserialized).name).isEqualTo(testBean.name); } @Test(expected = MessageTransformationException.class) @@ -74,7 +72,7 @@ public class PayloadSerializingTransformerTests { PayloadSerializingTransformer transformer = new PayloadSerializingTransformer(); transformer.setConverter(source -> "Converted".getBytes()); Message message = transformer.transform(MessageBuilder.withPayload("Test").build()); - assertEquals("Converted", new String((byte[]) message.getPayload())); + assertThat(new String((byte[]) message.getPayload())).isEqualTo("Converted"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java index 49723295d8..7153bb23d2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; @@ -36,7 +36,7 @@ public class PayloadTransformerTests { TestPayloadTransformer transformer = new TestPayloadTransformer(); Message message = new GenericMessage("foo"); Message result = transformer.transform(message); - assertEquals(3, result.getPayload()); + assertThat(result.getPayload()).isEqualTo(3); } @Test(expected = MessagingException.class) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java index 50005ae5cb..f23fad765c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -38,7 +38,7 @@ public class PayloadTypeConvertingTransformerTests { tx.setConverter(source -> source.toUpperCase()); String in = "abcd"; String out = tx.transformPayload(in); - assertEquals("ABCD", out); + assertThat(out).isEqualTo("ABCD"); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelHeaderEnricherIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelHeaderEnricherIntegrationTests.java index 3b4df128da..46fb0a6804 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelHeaderEnricherIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelHeaderEnricherIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -64,7 +63,7 @@ public class SpelHeaderEnricherIntegrationTests { Message message = MessageBuilder.withPayload("test").build(); this.simpleInput.send(message); Message result = output.receive(0); - assertEquals(8, result.getHeaders().get("testHeader")); + assertThat(result.getHeaders().get("testHeader")).isEqualTo(8); } @Test @@ -72,7 +71,7 @@ public class SpelHeaderEnricherIntegrationTests { Message message = MessageBuilder.withPayload("test").setHeader("num", 3).build(); this.beanResolvingInput.send(message); Message result = output.receive(0); - assertEquals(243, result.getHeaders().get("num")); + assertThat(result.getHeaders().get("num")).isEqualTo(243); } @Test @@ -80,7 +79,7 @@ public class SpelHeaderEnricherIntegrationTests { Message message = MessageBuilder.withPayload("test").setHeader("num", 3).build(); this.expressionNotExecutedInput.send(message); Message result = output.receive(0); - assertEquals(3, result.getHeaders().get("num")); + assertThat(result.getHeaders().get("num")).isEqualTo(3); } @Test @@ -88,7 +87,7 @@ public class SpelHeaderEnricherIntegrationTests { Message message = MessageBuilder.withPayload("test").setHeader("num", 3).build(); this.headerNotRemovedInput.send(message); Message result = output.receive(0); - assertEquals(3, result.getHeaders().get("num")); + assertThat(result.getHeaders().get("num")).isEqualTo(3); } @Test @@ -96,7 +95,7 @@ public class SpelHeaderEnricherIntegrationTests { Message message = MessageBuilder.withPayload("test").setHeader("num", 3).build(); this.headerRemovedInput.send(message); Message result = output.receive(0); - assertNull(result.getHeaders().get("num")); + assertThat(result.getHeaders().get("num")).isNull(); } static class TestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelTransformerIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelTransformerIntegrationTests.java index 9d3ec8e594..145581119f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelTransformerIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SpelTransformerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,14 +16,10 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -86,7 +82,7 @@ public class SpelTransformerIntegrationTests { Message message = MessageBuilder.withPayload(new TestBean()).setHeader("bar", 123).build(); this.simpleInput.send(message); Message result = output.receive(0); - assertEquals("test123", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("test123"); } @Test @@ -94,7 +90,7 @@ public class SpelTransformerIntegrationTests { Message message = MessageBuilder.withPayload("foo").build(); this.beanResolvingInput.send(message); Message result = output.receive(0); - assertEquals("testFOO", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("testFOO"); } @Test @@ -103,7 +99,7 @@ public class SpelTransformerIntegrationTests { this.transformerChainInput.send(new GenericMessage("foo")); } catch (ReplyRequiredException e) { - assertThat(e.getMessage(), Matchers.containsString("No reply produced by handler 'transformerChain$child#0'")); + assertThat(e.getMessage()).contains("No reply produced by handler 'transformerChain$child#0'"); } } @@ -114,10 +110,11 @@ public class SpelTransformerIntegrationTests { Foo foo = new Foo("baz"); fooHandler.handleMessage(new GenericMessage(foo)); Message reply = outputChannel.receive(0); - assertNotNull(reply); - assertTrue(reply.getPayload() instanceof String); - assertEquals("baz", reply.getPayload()); - assertEquals(3, TestUtils.getPropertyValue(this.evaluationContextFactoryBean, "propertyAccessors", Map.class).size()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload() instanceof String).isTrue(); + assertThat(reply.getPayload()).isEqualTo("baz"); + assertThat(TestUtils.getPropertyValue(this.evaluationContextFactoryBean, "propertyAccessors", Map.class).size()) + .isEqualTo(3); } @Test @@ -126,8 +123,8 @@ public class SpelTransformerIntegrationTests { barHandler.setOutputChannel(outputChannel); barHandler.handleMessage(new GenericMessage("foo")); Message reply = outputChannel.receive(0); - assertNotNull(reply); - assertEquals("bar", reply.getPayload()); + assertThat(reply).isNotNull(); + assertThat(reply.getPayload()).isEqualTo("bar"); } @Test @@ -135,7 +132,7 @@ public class SpelTransformerIntegrationTests { Message message = MessageBuilder.withPayload(" foo ").build(); this.spelFunctionInput.send(message); Message result = output.receive(0); - assertEquals("foo", result.getPayload()); + assertThat(result.getPayload()).isEqualTo("foo"); } static class TestBean { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java index c49362e89b..720a58ea37 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; import java.util.Map; @@ -40,14 +38,14 @@ public class SysLogTransformerTests { public void testMap() throws Exception { String syslog = "<158>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE"; Map transformed = sut.transformPayload(syslog.getBytes()); - assertEquals(6, transformed.size()); - assertEquals(19, transformed.get(SyslogToMapTransformer.FACILITY)); - assertEquals(6, transformed.get(SyslogToMapTransformer.SEVERITY)); + assertThat(transformed.size()).isEqualTo(6); + assertThat(transformed.get(SyslogToMapTransformer.FACILITY)).isEqualTo(19); + assertThat(transformed.get(SyslogToMapTransformer.SEVERITY)).isEqualTo(6); Object date = transformed.get(SyslogToMapTransformer.TIMESTAMP); - assertTrue(date instanceof Date || date instanceof String); - assertEquals("WEBERN", transformed.get(SyslogToMapTransformer.HOST)); - assertEquals("TESTING", transformed.get(SyslogToMapTransformer.TAG)); - assertEquals("[70729]: TEST SYSLOG MESSAGE", transformed.get(SyslogToMapTransformer.MESSAGE)); + assertThat(date instanceof Date || date instanceof String).isTrue(); + assertThat(transformed.get(SyslogToMapTransformer.HOST)).isEqualTo("WEBERN"); + assertThat(transformed.get(SyslogToMapTransformer.TAG)).isEqualTo("TESTING"); + assertThat(transformed.get(SyslogToMapTransformer.MESSAGE)).isEqualTo("[70729]: TEST SYSLOG MESSAGE"); String[] fields = { SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, SyslogToMapTransformer.TIMESTAMP, SyslogToMapTransformer.HOST, @@ -60,30 +58,30 @@ public class SysLogTransformerTests { public void testBadPattern() throws Exception { String syslog = "&158>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE"; Map transformed = sut.transformPayload(syslog.getBytes()); - assertEquals(1, transformed.size()); - assertEquals(syslog, transformed.get(SyslogToMapTransformer.UNDECODED)); + assertThat(transformed.size()).isEqualTo(1); + assertThat(transformed.get(SyslogToMapTransformer.UNDECODED)).isEqualTo(syslog); } @Test public void testBadFacilitySeverity() throws Exception { String syslog = "JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE"; Map transformed = sut.transformPayload(syslog.getBytes()); - assertEquals(1, transformed.size()); - assertEquals(syslog, transformed.get(SyslogToMapTransformer.UNDECODED)); + assertThat(transformed.size()).isEqualTo(1); + assertThat(transformed.get(SyslogToMapTransformer.UNDECODED)).isEqualTo(syslog); } @Test public void testWithoutTag() throws Exception { String syslog = "<158>JUL 26 22:08:35 WEBERN [70729]: TEST SYSLOG MESSAGE"; Map transformed = sut.transformPayload(syslog.getBytes()); - assertEquals(5, transformed.size()); - assertEquals(19, transformed.get(SyslogToMapTransformer.FACILITY)); - assertEquals(6, transformed.get(SyslogToMapTransformer.SEVERITY)); + assertThat(transformed.size()).isEqualTo(5); + assertThat(transformed.get(SyslogToMapTransformer.FACILITY)).isEqualTo(19); + assertThat(transformed.get(SyslogToMapTransformer.SEVERITY)).isEqualTo(6); Object date = transformed.get(SyslogToMapTransformer.TIMESTAMP); - assertTrue(date instanceof Date || date instanceof String); - assertEquals("WEBERN", transformed.get(SyslogToMapTransformer.HOST)); - assertFalse(transformed.containsKey(SyslogToMapTransformer.TAG)); - assertEquals("[70729]: TEST SYSLOG MESSAGE", transformed.get(SyslogToMapTransformer.MESSAGE)); + assertThat(date instanceof Date || date instanceof String).isTrue(); + assertThat(transformed.get(SyslogToMapTransformer.HOST)).isEqualTo("WEBERN"); + assertThat(transformed.containsKey(SyslogToMapTransformer.TAG)).isFalse(); + assertThat(transformed.get(SyslogToMapTransformer.MESSAGE)).isEqualTo("[70729]: TEST SYSLOG MESSAGE"); String[] fields = { SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, SyslogToMapTransformer.TIMESTAMP, SyslogToMapTransformer.HOST, @@ -96,14 +94,14 @@ public class SysLogTransformerTests { public void testTagMaxLength() throws Exception { String syslog = "<158>JUL 26 22:08:35 WEBERN ABCDE1234567890ABCDE1234567890UVXYZ TEST SYSLOG MESSAGE"; Map transformed = sut.transformPayload(syslog.getBytes()); - assertEquals(6, transformed.size()); - assertEquals(19, transformed.get(SyslogToMapTransformer.FACILITY)); - assertEquals(6, transformed.get(SyslogToMapTransformer.SEVERITY)); + assertThat(transformed.size()).isEqualTo(6); + assertThat(transformed.get(SyslogToMapTransformer.FACILITY)).isEqualTo(19); + assertThat(transformed.get(SyslogToMapTransformer.SEVERITY)).isEqualTo(6); Object date = transformed.get(SyslogToMapTransformer.TIMESTAMP); - assertTrue(date instanceof Date || date instanceof String); - assertEquals("WEBERN", transformed.get(SyslogToMapTransformer.HOST)); - assertEquals("ABCDE1234567890ABCDE1234567890UV", transformed.get(SyslogToMapTransformer.TAG)); - assertEquals("XYZ TEST SYSLOG MESSAGE", transformed.get(SyslogToMapTransformer.MESSAGE)); + assertThat(date instanceof Date || date instanceof String).isTrue(); + assertThat(transformed.get(SyslogToMapTransformer.HOST)).isEqualTo("WEBERN"); + assertThat(transformed.get(SyslogToMapTransformer.TAG)).isEqualTo("ABCDE1234567890ABCDE1234567890UV"); + assertThat(transformed.get(SyslogToMapTransformer.MESSAGE)).isEqualTo("XYZ TEST SYSLOG MESSAGE"); String[] fields = { SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, SyslogToMapTransformer.TIMESTAMP, SyslogToMapTransformer.HOST, @@ -116,15 +114,15 @@ public class SysLogTransformerTests { Map actualTransformed) { int n = 0; for (Entry entry : actualTransformed.entrySet()) { - assertEquals(expectedFields[n++], entry.getKey()); + assertThat(entry.getKey()).isEqualTo(expectedFields[n++]); } n = 0; for (String key : actualTransformed.keySet()) { - assertEquals(expectedFields[n++], key); + assertThat(key).isEqualTo(expectedFields[n++]); } n = 0; for (Object value : actualTransformed.values()) { - assertEquals(expectedValues[n++], value); + assertThat(value).isEqualTo(expectedValues[n++]); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/TransformerContextTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/TransformerContextTests.java index af93832242..c02f19f9ba 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/TransformerContextTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/TransformerContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.transformer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -71,29 +68,29 @@ public class TransformerContextTests { public void methodInvokingTransformer() { this.input.send(new GenericMessage("foo")); Message reply = this.output.receive(0); - assertEquals("FOO", reply.getPayload()); - assertEquals(1, adviceCalled); + assertThat(reply.getPayload()).isEqualTo("FOO"); + assertThat(adviceCalled).isEqualTo(1); this.direct.send(new GenericMessage("foo")); reply = this.output.receive(0); - assertEquals("FOO", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("FOO"); StackTraceElement[] st = (StackTraceElement[]) reply.getHeaders().get("callStack"); - assertEquals("doSend", st[6].getMethodName()); // no MethodInvokerHelper + assertThat(st[6].getMethodName()).isEqualTo("doSend"); // no MethodInvokerHelper this.directRef.send(new GenericMessage("foo")); reply = this.output.receive(0); - assertEquals("FOO", reply.getPayload()); + assertThat(reply.getPayload()).isEqualTo("FOO"); st = (StackTraceElement[]) reply.getHeaders().get("callStack"); - assertEquals("doSend", st[6].getMethodName()); // no MethodInvokerHelper + assertThat(st[6].getMethodName()).isEqualTo("doSend"); // no MethodInvokerHelper - assertTrue(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isTrue(); this.pojoTransformer.stop(); - assertFalse(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isFalse(); this.pojoTransformer.start(); - assertTrue(this.testBean.isRunning()); + assertThat(this.testBean.isRunning()).isTrue(); this.directRef.send(new GenericMessage("bar")); - assertNull(this.output.receive(0)); + assertThat(this.output.receive(0)).isNull(); } public static class FooAdvice extends AbstractRequestHandlerAdvice { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java index dd896e981d..918b33c95d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java @@ -16,14 +16,7 @@ package org.springframework.integration.util; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -80,10 +73,10 @@ public class BeanFactoryTypeConverterTests { BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(); List sourceObject = new ArrayList<>(); ArrayList convertedCollection = - (ArrayList) typeConverter.convertValue(sourceObject, - TypeDescriptor.forObject(sourceObject), - TypeDescriptor.forObject(new ArrayList())); - assertEquals(sourceObject, convertedCollection); + (ArrayList) typeConverter.convertValue(sourceObject, + TypeDescriptor.forObject(sourceObject), + TypeDescriptor.forObject(new ArrayList())); + assertThat(convertedCollection).isEqualTo(sourceObject); } @Test @@ -92,7 +85,7 @@ public class BeanFactoryTypeConverterTests { typeConverter.setBeanFactory(new DefaultListableBeanFactory()); String converted = (String) typeConverter.convertValue(1234, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.valueOf(String.class)); - assertEquals("1234", converted); + assertThat(converted).isEqualTo("1234"); } @Test @@ -103,7 +96,7 @@ public class BeanFactoryTypeConverterTests { Collection converted = (Collection) typeConverter.convertValue(1234, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.forObject(new ArrayList<>(Arrays.asList(1)))); - assertEquals(Collections.singletonList(1234), converted); + assertThat(converted).isEqualTo(Collections.singletonList(1234)); } @Test @@ -111,8 +104,8 @@ public class BeanFactoryTypeConverterTests { BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(); typeConverter.setBeanFactory(new DefaultListableBeanFactory()); MessageHeaders headers = new GenericMessage<>("foo").getHeaders(); - assertSame(headers, typeConverter.convertValue(headers, TypeDescriptor.valueOf(MessageHeaders.class), - TypeDescriptor.valueOf(MessageHeaders.class))); + assertThat(typeConverter.convertValue(headers, TypeDescriptor.valueOf(MessageHeaders.class), + TypeDescriptor.valueOf(MessageHeaders.class))).isSameAs(headers); } @Test @@ -121,6 +114,7 @@ public class BeanFactoryTypeConverterTests { typeConverter.setBeanFactory(new DefaultListableBeanFactory()); Message message = new GenericMessage<>("foo"); message = MessageHistory.write(message, new NamedComponent() { + @Override public String getComponentName() { return "bar"; @@ -132,8 +126,8 @@ public class BeanFactoryTypeConverterTests { } }); MessageHistory history = MessageHistory.read(message); - assertSame(history, typeConverter.convertValue(history, TypeDescriptor.valueOf(MessageHistory.class), - TypeDescriptor.valueOf(MessageHistory.class))); + assertThat(typeConverter.convertValue(history, TypeDescriptor.valueOf(MessageHistory.class), + TypeDescriptor.valueOf(MessageHistory.class))).isSameAs(history); } @Test @@ -141,8 +135,8 @@ public class BeanFactoryTypeConverterTests { BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(); typeConverter.setBeanFactory(new DefaultListableBeanFactory()); byte[] bytes = new byte[1]; - assertSame(bytes, typeConverter.convertValue(bytes, TypeDescriptor.valueOf(byte[].class), - TypeDescriptor.valueOf(byte[].class))); + assertThat(typeConverter.convertValue(bytes, TypeDescriptor.valueOf(byte[].class), + TypeDescriptor.valueOf(byte[].class))).isSameAs(bytes); } @Test @@ -150,22 +144,22 @@ public class BeanFactoryTypeConverterTests { BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(); typeConverter.setBeanFactory(new DefaultListableBeanFactory()); String string = "foo"; - assertSame(string, typeConverter.convertValue(string, TypeDescriptor.valueOf(String.class), - TypeDescriptor.valueOf(Object.class))); + assertThat(typeConverter.convertValue(string, TypeDescriptor.valueOf(String.class), + TypeDescriptor.valueOf(Object.class))).isSameAs(string); } @Test public void testObjectToStringIsConverted() { ConversionService conversionService = mock(ConversionService.class); when(conversionService.canConvert(any(TypeDescriptor.class), any(TypeDescriptor.class))) - .thenReturn(true); + .thenReturn(true); when(conversionService.convert(any(), any(TypeDescriptor.class), any(TypeDescriptor.class))) - .thenReturn("foo"); + .thenReturn("foo"); BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(conversionService); typeConverter.setBeanFactory(new DefaultListableBeanFactory()); Object object = new Object(); - assertEquals("foo", typeConverter.convertValue(object, TypeDescriptor.valueOf(Object.class), - TypeDescriptor.valueOf(String.class))); + assertThat(typeConverter.convertValue(object, TypeDescriptor.valueOf(Object.class), + TypeDescriptor.valueOf(String.class))).isEqualTo("foo"); } @SuppressWarnings("unchecked") @@ -174,6 +168,7 @@ public class BeanFactoryTypeConverterTests { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); DefaultConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new Converter() { // Must be explicit type with generics + @Override public Bar convert(Foo source) { return new Bar(); @@ -198,10 +193,10 @@ public class BeanFactoryTypeConverterTests { foos.put("foo", fooMap); bars = (Map>>) typeConverter.convertValue(foos, sourceType, targetType); - assertThat(bars.get("foo").get("foo").iterator().next(), instanceOf(Bar.class)); + assertThat(bars.get("foo").get("foo").iterator().next()).isInstanceOf(Bar.class); Service service = new Service(); - MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor<>(service, "handle"); + MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor<>(service, "handle"); processor.setConversionService(conversionService); processor.setUseSpelInvoker(true); processor.setBeanFactory(beanFactory); @@ -210,8 +205,8 @@ public class BeanFactoryTypeConverterTests { handler.setOutputChannel(replyChannel); handler.handleMessage(new GenericMessage<>(foos)); Message message = replyChannel.receive(0); - assertNotNull(message); - assertEquals("bar", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("bar"); } @Test @@ -219,6 +214,7 @@ public class BeanFactoryTypeConverterTests { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); DefaultConversionService conversionService = new DefaultConversionService(); conversionService.addConverter(new Converter() { // Must be explicit type with generics + @Override public Bar convert(Foo source) { return new Bar(); @@ -229,7 +225,7 @@ public class BeanFactoryTypeConverterTests { typeConverter.setBeanFactory(beanFactory); Service service = new Service(); - MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor<>(service, "handle"); + MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor<>(service, "handle"); processor.setConversionService(conversionService); processor.setUseSpelInvoker(true); processor.setBeanFactory(beanFactory); @@ -238,8 +234,8 @@ public class BeanFactoryTypeConverterTests { handler.setOutputChannel(replyChannel); handler.handleMessage(new GenericMessage>(Collections.singletonList(new Foo()))); Message message = replyChannel.receive(10000); - assertNotNull(message); - assertEquals("baz", message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("baz"); } @Test @@ -247,7 +243,7 @@ public class BeanFactoryTypeConverterTests { DefaultConversionService conversionService = new DefaultConversionService(); BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(conversionService); Object foo = typeConverter.convertValue(null, null, TypeDescriptor.valueOf(Bar.class)); - assertNull(foo); + assertThat(foo).isNull(); } @Test @@ -255,9 +251,9 @@ public class BeanFactoryTypeConverterTests { DefaultConversionService conversionService = new DefaultConversionService(); BeanFactoryTypeConverter typeConverter = new BeanFactoryTypeConverter(conversionService); Object foo = typeConverter.convertValue(null, null, TypeDescriptor.valueOf(Void.class)); - assertNull(foo); + assertThat(foo).isNull(); foo = typeConverter.convertValue(null, null, TypeDescriptor.valueOf(Void.TYPE)); - assertNull(foo); + assertThat(foo).isNull(); } @Test @@ -267,7 +263,7 @@ public class BeanFactoryTypeConverterTests { UUID uuid = UUID.randomUUID(); Object foo = typeConverter.convertValue(uuid, TypeDescriptor.valueOf(UUID.class), TypeDescriptor.valueOf(String.class)); - assertEquals(uuid.toString(), foo); + assertThat(foo).isEqualTo(uuid.toString()); } @Test @@ -275,6 +271,7 @@ public class BeanFactoryTypeConverterTests { DefaultConversionService conversionService = new DefaultConversionService(); final Foo foo = new Foo(); conversionService.addConverter(new Converter() { // Must be explicit type with generics + @Override public Foo convert(String source) { return foo; @@ -284,7 +281,7 @@ public class BeanFactoryTypeConverterTests { UUID uuid = UUID.randomUUID(); Object convertedFoo = typeConverter.convertValue(uuid, TypeDescriptor.valueOf(UUID.class), TypeDescriptor.valueOf(Foo.class)); - assertSame(foo, convertedFoo); + assertThat(convertedFoo).isSameAs(foo); } @Test @@ -294,13 +291,14 @@ public class BeanFactoryTypeConverterTests { UUID uuid = UUID.randomUUID(); Object converted = typeConverter.convertValue(uuid.toString(), TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(UUID.class)); - assertEquals(uuid, converted); + assertThat(converted).isEqualTo(uuid); } @Test @Ignore("Too sensitive for the time") public void initialConcurrency() throws Exception { - ConversionService conversionService = mock(ConversionService.class); // can convert nothing so we drop down to P.E.s + ConversionService conversionService = mock(ConversionService.class); // can convert nothing so we drop down to + // P.E.s final BeanFactoryTypeConverter beanFactoryTypeConverter = new BeanFactoryTypeConverter(conversionService); ConfigurableBeanFactory beanFactory = mock(ConfigurableBeanFactory.class); SimpleTypeConverter typeConverter = spy(new SimpleTypeConverter()); @@ -327,9 +325,9 @@ public class BeanFactoryTypeConverterTests { exec.execute(test); exec.execute(test); exec.shutdown(); - assertTrue(exec.awaitTermination(10, TimeUnit.SECONDS)); - assertEquals(4, count.get()); - assertFalse(concurrentlyInGetDefaultEditor.get()); + assertThat(exec.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + assertThat(count.get()).isEqualTo(4); + assertThat(concurrentlyInGetDefaultEditor.get()).isFalse(); } public static class Foo { @@ -343,12 +341,12 @@ public class BeanFactoryTypeConverterTests { public static class Service { public String handle(Map>> payload) { - assertThat(payload.get("foo").get("foo").iterator().next(), instanceOf(Bar.class)); + assertThat(payload.get("foo").get("foo").iterator().next()).isInstanceOf(Bar.class); return "bar"; } public String handle(Collection payload) { - assertThat(payload.iterator().next(), instanceOf(Bar.class)); + assertThat(payload.iterator().next()).isInstanceOf(Bar.class); return "baz"; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java index 8785d62e33..044ebc24fd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,11 +16,7 @@ package org.springframework.integration.util; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionException; @@ -65,9 +61,9 @@ public class CallerBlocksPolicyTests { } }; te.execute(task); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertThat(e.get(), instanceOf(RejectedExecutionException.class)); - assertEquals("Max wait time expired to queue task", e.get().getMessage()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(e.get()).isInstanceOf(RejectedExecutionException.class); + assertThat(e.get().getMessage()).isEqualTo("Max wait time expired to queue task"); te.destroy(); } @@ -101,8 +97,8 @@ public class CallerBlocksPolicyTests { e.set(tre.getCause()); } }); - assertTrue(latch.await(10, TimeUnit.SECONDS)); - assertNull(e.get()); + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(e.get()).isNull(); te.destroy(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/util/SimplePoolTests.java b/spring-integration-core/src/test/java/org/springframework/integration/util/SimplePoolTests.java index 6ee5a10222..7c5d3f5b6e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/util/SimplePoolTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/util/SimplePoolTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.HashSet; import java.util.Set; @@ -45,16 +42,16 @@ public class SimplePoolTests { SimplePool pool = stringPool(2, strings, stale); String s1 = pool.getItem(); String s2 = pool.getItem(); - assertNotSame(s1, s2); + assertThat(s2).isNotSameAs(s1); pool.releaseItem(s1); String s3 = pool.getItem(); - assertSame(s1, s3); + assertThat(s3).isSameAs(s1); stale.set(true); pool.releaseItem(s3); s3 = pool.getItem(); - assertNotSame(s1, s3); - assertFalse(strings.remove(s1)); - assertEquals(2, pool.getAllocatedCount()); + assertThat(s3).isNotSameAs(s1); + assertThat(strings.remove(s1)).isFalse(); + assertThat(pool.getAllocatedCount()).isEqualTo(2); } @Test @@ -63,23 +60,23 @@ public class SimplePoolTests { final AtomicBoolean stale = new AtomicBoolean(); SimplePool pool = stringPool(2, strings, stale); String s1 = pool.getItem(); - assertEquals(0, pool.getIdleCount()); - assertEquals(1, pool.getActiveCount()); - assertEquals(1, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(0); + assertThat(pool.getActiveCount()).isEqualTo(1); + assertThat(pool.getAllocatedCount()).isEqualTo(1); pool.releaseItem(s1); - assertEquals(1, pool.getIdleCount()); - assertEquals(0, pool.getActiveCount()); - assertEquals(1, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(1); + assertThat(pool.getActiveCount()).isEqualTo(0); + assertThat(pool.getAllocatedCount()).isEqualTo(1); s1 = pool.getItem(); - assertEquals(0, pool.getIdleCount()); - assertEquals(1, pool.getActiveCount()); - assertEquals(1, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(0); + assertThat(pool.getActiveCount()).isEqualTo(1); + assertThat(pool.getAllocatedCount()).isEqualTo(1); String s2 = pool.getItem(); - assertNotSame(s1, s2); + assertThat(s2).isNotSameAs(s1); pool.setWaitTimeout(1); - assertEquals(0, pool.getIdleCount()); - assertEquals(2, pool.getActiveCount()); - assertEquals(2, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(0); + assertThat(pool.getActiveCount()).isEqualTo(2); + assertThat(pool.getAllocatedCount()).isEqualTo(2); try { pool.getItem(); fail("Expected exception"); @@ -89,39 +86,39 @@ public class SimplePoolTests { // resize up pool.setPoolSize(4); - assertEquals(0, pool.getIdleCount()); - assertEquals(2, pool.getActiveCount()); - assertEquals(2, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(0); + assertThat(pool.getActiveCount()).isEqualTo(2); + assertThat(pool.getAllocatedCount()).isEqualTo(2); String s3 = pool.getItem(); String s4 = pool.getItem(); - assertEquals(0, pool.getIdleCount()); - assertEquals(4, pool.getActiveCount()); - assertEquals(4, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(0); + assertThat(pool.getActiveCount()).isEqualTo(4); + assertThat(pool.getAllocatedCount()).isEqualTo(4); pool.releaseItem(s4); - assertEquals(1, pool.getIdleCount()); - assertEquals(3, pool.getActiveCount()); - assertEquals(4, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(1); + assertThat(pool.getActiveCount()).isEqualTo(3); + assertThat(pool.getAllocatedCount()).isEqualTo(4); // resize down pool.setPoolSize(2); - assertEquals(0, pool.getIdleCount()); - assertEquals(3, pool.getActiveCount()); - assertEquals(3, pool.getPoolSize()); - assertEquals(3, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(0); + assertThat(pool.getActiveCount()).isEqualTo(3); + assertThat(pool.getPoolSize()).isEqualTo(3); + assertThat(pool.getAllocatedCount()).isEqualTo(3); pool.releaseItem(s3); - assertEquals(0, pool.getIdleCount()); - assertEquals(2, pool.getActiveCount()); - assertEquals(2, pool.getPoolSize()); - assertEquals(2, pool.getAllocatedCount()); - assertEquals(2, strings.size()); + assertThat(pool.getIdleCount()).isEqualTo(0); + assertThat(pool.getActiveCount()).isEqualTo(2); + assertThat(pool.getPoolSize()).isEqualTo(2); + assertThat(pool.getAllocatedCount()).isEqualTo(2); + assertThat(strings.size()).isEqualTo(2); pool.releaseItem(s2); pool.releaseItem(s1); - assertEquals(2, pool.getIdleCount()); - assertEquals(0, pool.getActiveCount()); - assertEquals(2, pool.getPoolSize()); - assertEquals(2, strings.size()); - assertEquals(2, pool.getAllocatedCount()); + assertThat(pool.getIdleCount()).isEqualTo(2); + assertThat(pool.getActiveCount()).isEqualTo(0); + assertThat(pool.getPoolSize()).isEqualTo(2); + assertThat(strings.size()).isEqualTo(2); + assertThat(pool.getAllocatedCount()).isEqualTo(2); } @Test(expected = IllegalArgumentException.class) @@ -139,13 +136,13 @@ public class SimplePoolTests { final AtomicBoolean stale = new AtomicBoolean(); SimplePool pool = stringPool(2, strings, stale); Semaphore permits = TestUtils.getPropertyValue(pool, "permits", Semaphore.class); - assertEquals(2, permits.availablePermits()); + assertThat(permits.availablePermits()).isEqualTo(2); String s1 = pool.getItem(); - assertEquals(1, permits.availablePermits()); + assertThat(permits.availablePermits()).isEqualTo(1); pool.releaseItem(s1); - assertEquals(2, permits.availablePermits()); + assertThat(permits.availablePermits()).isEqualTo(2); pool.releaseItem(s1); - assertEquals(2, permits.availablePermits()); + assertThat(permits.availablePermits()).isEqualTo(2); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/util/UUIDConverterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/util/UUIDConverterTests.java index 5942ebe482..74c1702fdc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/util/UUIDConverterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/util/UUIDConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,8 @@ package org.springframework.integration.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.Date; import java.util.UUID; @@ -35,58 +32,58 @@ import org.junit.Test; public class UUIDConverterTests { @Test - public void testConvertNull() throws Exception { - assertNull(UUIDConverter.getUUID(null)); + public void testConvertNull() { + assertThat(UUIDConverter.getUUID(null)).isNull(); } @Test - public void testConvertUUID() throws Exception { + public void testConvertUUID() { UUID uuid = UUID.randomUUID(); - assertEquals(uuid, UUIDConverter.getUUID(uuid)); + assertThat(UUIDConverter.getUUID(uuid)).isEqualTo(uuid); } @Test - public void testConvertUUIDString() throws Exception { + public void testConvertUUIDString() { UUID uuid = UUID.randomUUID(); - assertEquals(uuid, UUIDConverter.getUUID(uuid.toString())); + assertThat(UUIDConverter.getUUID(uuid.toString())).isEqualTo(uuid); } @Test - public void testConvertAlmostUUIDString() throws Exception { + public void testConvertAlmostUUIDString() { String name = "1-2-3-4"; try { UUID.fromString(name); - fail(); + fail("IllegalArgumentException expected"); } catch (IllegalArgumentException e) { String message = e.getMessage(); - assertTrue("Wrong message: " + message, message.contains("Invalid UUID string")); + assertThat(message.contains("Invalid UUID string")).as("Wrong message: " + message).isTrue(); } - assertNotNull(UUIDConverter.getUUID(name)); + assertThat(UUIDConverter.getUUID(name)).isNotNull(); } @Test - public void testConvertRandomString() throws Exception { + public void testConvertRandomString() { UUID uuid = UUIDConverter.getUUID("foo"); - assertNotNull(uuid); + assertThat(uuid).isNotNull(); String uuidString = uuid.toString(); - assertEquals(uuidString, UUIDConverter.getUUID("foo").toString()); - assertEquals(uuidString, UUIDConverter.getUUID(uuid).toString()); + assertThat(UUIDConverter.getUUID("foo").toString()).isEqualTo(uuidString); + assertThat(UUIDConverter.getUUID(uuid).toString()).isEqualTo(uuidString); } @Test - public void testConvertPrimitive() throws Exception { - assertNotNull(UUIDConverter.getUUID(1L)); + public void testConvertPrimitive() { + assertThat(UUIDConverter.getUUID(1L)).isNotNull(); } @Test - public void testConvertSerializable() throws Exception { - assertNotNull(UUIDConverter.getUUID(new Date())); + public void testConvertSerializable() { + assertThat(UUIDConverter.getUUID(new Date())).isNotNull(); } @Test(expected = IllegalArgumentException.class) - public void testConvertNonSerializable() throws Exception { - assertNotNull(UUIDConverter.getUUID(new Object())); + public void testConvertNonSerializable() { + assertThat(UUIDConverter.getUUID(new Object())).isNotNull(); } } diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventInboundChannelAdapterParserTests.java b/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventInboundChannelAdapterParserTests.java index 200919178c..5935560730 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventInboundChannelAdapterParserTests.java +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventInboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,12 @@ package org.springframework.integration.event.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.assertj.core.api.Assertions.assertThat; import java.util.Date; import java.util.Properties; import java.util.Set; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -75,73 +70,74 @@ public class EventInboundChannelAdapterParserTests { @Test public void validateEventParser() { Object adapter = context.getBean("eventAdapterSimple"); - Assert.assertNotNull(adapter); - Assert.assertTrue(adapter instanceof ApplicationEventListeningMessageProducer); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof ApplicationEventListeningMessageProducer).isTrue(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); - Assert.assertEquals(context.getBean("input"), adapterAccessor.getPropertyValue("outputChannel")); - Assert.assertSame(errorChannel, adapterAccessor.getPropertyValue("errorChannel")); + assertThat(adapterAccessor.getPropertyValue("outputChannel")).isEqualTo(context.getBean("input")); + assertThat(adapterAccessor.getPropertyValue("errorChannel")).isSameAs(errorChannel); } @Test @SuppressWarnings("unchecked") public void validateEventParserWithEventTypes() { Object adapter = context.getBean("eventAdapterFiltered"); - Assert.assertNotNull(adapter); - Assert.assertTrue(adapter instanceof ApplicationEventListeningMessageProducer); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof ApplicationEventListeningMessageProducer).isTrue(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); - Assert.assertEquals(context.getBean("inputFiltered"), adapterAccessor.getPropertyValue("outputChannel")); + assertThat(adapterAccessor.getPropertyValue("outputChannel")).isEqualTo(context.getBean("inputFiltered")); Set eventTypes = (Set) adapterAccessor.getPropertyValue("eventTypes"); - assertNotNull(eventTypes); - assertTrue(eventTypes.size() == 3); - assertTrue(eventTypes.contains(ResolvableType.forClass(SampleEvent.class))); - assertTrue(eventTypes.contains(ResolvableType.forClass(AnotherSampleEvent.class))); - assertTrue(eventTypes.contains(ResolvableType.forClass(Date.class))); - assertNull(adapterAccessor.getPropertyValue("errorChannel")); + assertThat(eventTypes).isNotNull(); + assertThat(eventTypes.size() == 3).isTrue(); + assertThat(eventTypes.contains(ResolvableType.forClass(SampleEvent.class))).isTrue(); + assertThat(eventTypes.contains(ResolvableType.forClass(AnotherSampleEvent.class))).isTrue(); + assertThat(eventTypes.contains(ResolvableType.forClass(Date.class))).isTrue(); + assertThat(adapterAccessor.getPropertyValue("errorChannel")).isNull(); } @Test @SuppressWarnings("unchecked") public void validateEventParserWithEventTypesAndPlaceholder() { Object adapter = context.getBean("eventAdapterFilteredPlaceHolder"); - Assert.assertNotNull(adapter); - Assert.assertTrue(adapter instanceof ApplicationEventListeningMessageProducer); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof ApplicationEventListeningMessageProducer).isTrue(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); - Assert.assertEquals(context.getBean("inputFilteredPlaceHolder"), adapterAccessor.getPropertyValue("outputChannel")); + assertThat(adapterAccessor.getPropertyValue("outputChannel")) + .isEqualTo(context.getBean("inputFilteredPlaceHolder")); Set eventTypes = (Set) adapterAccessor.getPropertyValue("eventTypes"); - assertNotNull(eventTypes); - assertTrue(eventTypes.size() == 2); - assertTrue(eventTypes.contains(ResolvableType.forClass(SampleEvent.class))); - assertTrue(eventTypes.contains(ResolvableType.forClass(AnotherSampleEvent.class))); + assertThat(eventTypes).isNotNull(); + assertThat(eventTypes.size() == 2).isTrue(); + assertThat(eventTypes.contains(ResolvableType.forClass(SampleEvent.class))).isTrue(); + assertThat(eventTypes.contains(ResolvableType.forClass(AnotherSampleEvent.class))).isTrue(); } @Test public void validateUsageWithHistory() { PollableChannel channel = context.getBean("input", PollableChannel.class); - assertEquals(ContextRefreshedEvent.class, channel.receive(0).getPayload().getClass()); + assertThat(channel.receive(0).getPayload().getClass()).isEqualTo(ContextRefreshedEvent.class); context.publishEvent(new SampleEvent("hello")); Message message = channel.receive(0); MessageHistory history = MessageHistory.read(message); - assertNotNull(history); + assertThat(history).isNotNull(); Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "eventAdapterSimple", 0); - assertNotNull(componentHistoryRecord); - assertEquals("event:inbound-channel-adapter", componentHistoryRecord.get("type")); - assertNotNull(message); - assertEquals(SampleEvent.class, message.getPayload().getClass()); + assertThat(componentHistoryRecord).isNotNull(); + assertThat(componentHistoryRecord.get("type")).isEqualTo("event:inbound-channel-adapter"); + assertThat(message).isNotNull(); + assertThat(message.getPayload().getClass()).isEqualTo(SampleEvent.class); } @Test public void validatePayloadExpression() { Object adapter = context.getBean("eventAdapterSpel"); - Assert.assertNotNull(adapter); - Assert.assertTrue(adapter instanceof ApplicationEventListeningMessageProducer); + assertThat(adapter).isNotNull(); + assertThat(adapter instanceof ApplicationEventListeningMessageProducer).isTrue(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); Expression expression = (Expression) adapterAccessor.getPropertyValue("payloadExpression"); - Assert.assertEquals("source + '-test'", expression.getExpressionString()); + assertThat(expression.getExpressionString()).isEqualTo("source + '-test'"); } @Test public void testAutoCreateChannel() { - assertSame(autoChannel, TestUtils.getPropertyValue(eventListener, "outputChannel")); + assertThat(TestUtils.getPropertyValue(eventListener, "outputChannel")).isSameAs(autoChannel); } @SuppressWarnings("serial") diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventOutboundChannelAdapterParserTests.java b/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventOutboundChannelAdapterParserTests.java index ecb5fb52e5..23dc9ee8c2 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventOutboundChannelAdapterParserTests.java +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/config/EventOutboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,10 +16,11 @@ package org.springframework.integration.event.config; +import static org.assertj.core.api.Assertions.assertThat; + import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -62,12 +63,12 @@ public class EventOutboundChannelAdapterParserTests { @Test public void validateEventParser() { EventDrivenConsumer adapter = this.context.getBean("eventAdapter", EventDrivenConsumer.class); - Assert.assertNotNull(adapter); + assertThat(adapter).isNotNull(); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); MessageHandler handler = (MessageHandler) adapterAccessor.getPropertyValue("handler"); - Assert.assertTrue(handler instanceof ApplicationEventPublishingMessageHandler); - Assert.assertEquals(this.context.getBean("input"), adapterAccessor.getPropertyValue("inputChannel")); - Assert.assertTrue(TestUtils.getPropertyValue(handler, "publishPayload", Boolean.class)); + assertThat(handler instanceof ApplicationEventPublishingMessageHandler).isTrue(); + assertThat(adapterAccessor.getPropertyValue("inputChannel")).isEqualTo(this.context.getBean("input")); + assertThat(TestUtils.getPropertyValue(handler, "publishPayload", Boolean.class)).isTrue(); } @Test @@ -83,7 +84,7 @@ public class EventOutboundChannelAdapterParserTests { this.context.addApplicationListener(listener); DirectChannel channel = context.getBean("input", DirectChannel.class); channel.send(new GenericMessage("hello")); - Assert.assertTrue(this.receivedEvent); + assertThat(this.receivedEvent).isTrue(); } @Test @@ -101,8 +102,8 @@ public class EventOutboundChannelAdapterParserTests { context.addApplicationListener(listener); DirectChannel channel = context.getBean("inputAdvice", DirectChannel.class); channel.send(new GenericMessage("hello")); - Assert.assertTrue(this.receivedEvent); - Assert.assertEquals(1, adviceCalled); + assertThat(this.receivedEvent).isTrue(); + assertThat(adviceCalled).isEqualTo(1); } @Test //INT-2275 @@ -120,7 +121,7 @@ public class EventOutboundChannelAdapterParserTests { this.context.addApplicationListener(listener); DirectChannel channel = context.getBean("inputChain", DirectChannel.class); channel.send(new GenericMessage("foo")); - Assert.assertTrue(this.receivedEvent); + assertThat(this.receivedEvent).isTrue(); } @Test(timeout = 10000) @@ -153,7 +154,7 @@ public class EventOutboundChannelAdapterParserTests { QueueChannel channel = context.getBean("input", QueueChannel.class); channel.send(new GenericMessage("hello")); barrier.await(); - Assert.assertTrue(this.receivedEvent); + assertThat(this.receivedEvent).isTrue(); context.close(); } diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/dsl/IntegrationFlowEventsTests.java b/spring-integration-event/src/test/java/org/springframework/integration/event/dsl/IntegrationFlowEventsTests.java index 68e771c106..0a45c48e94 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/dsl/IntegrationFlowEventsTests.java +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/dsl/IntegrationFlowEventsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,11 +16,7 @@ package org.springframework.integration.event.dsl; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.atomic.AtomicReference; @@ -91,32 +87,32 @@ public class IntegrationFlowEventsTests { @Test public void testEventsFlow() { - assertNull(this.eventHolder.get()); + assertThat(this.eventHolder.get()).isNull(); this.flow3Input.send(new GenericMessage<>("2")); - assertNotNull(this.eventHolder.get()); - assertEquals(4, this.eventHolder.get()); + assertThat(this.eventHolder.get()).isNotNull(); + assertThat(this.eventHolder.get()).isEqualTo(4); } @Test public void testRawApplicationEventListeningMessageProducer() { this.applicationContext.publishEvent(new TestApplicationEvent1()); Message receive = this.resultsChannel.receive(10000); - assertNotNull(receive); - assertThat(receive.getPayload(), instanceOf(TestApplicationEvent1.class)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isInstanceOf(TestApplicationEvent1.class); this.applicationContext.publishEvent(new TestApplicationEvent2()); receive = this.resultsChannel.receive(10000); - assertNotNull(receive); - assertThat(receive.getPayload(), instanceOf(TestApplicationEvent2.class)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isInstanceOf(TestApplicationEvent2.class); } @Test public void testDelayRescheduling() { Message receive = this.delayedResults.receive(10000); - assertNotNull(receive); - assertEquals("foo", receive.getPayload()); - assertEquals(1, messageGroupStore.getMessageGroupCount()); - assertEquals(0, messageGroupStore.getMessageCountForAllMessageGroups()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("foo"); + assertThat(messageGroupStore.getMessageGroupCount()).isEqualTo(1); + assertThat(messageGroupStore.getMessageCountForAllMessageGroups()).isEqualTo(0); } diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java index 4aaeb783f3..f96c01c9ce 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java @@ -16,21 +16,12 @@ package org.springframework.integration.event.inbound; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isOneOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; -import org.hamcrest.Matchers; import org.junit.Test; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; @@ -73,17 +64,17 @@ public class ApplicationEventListeningMessageProducerTests { adapter.setOutputChannel(channel); adapter.start(); Message message1 = channel.receive(0); - assertNull(message1); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))); + assertThat(message1).isNull(); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))).isTrue(); adapter.onApplicationEvent(new TestApplicationEvent1()); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))).isTrue(); adapter.onApplicationEvent(new TestApplicationEvent2()); Message message2 = channel.receive(20); - assertNotNull(message2); - assertEquals("event1", ((ApplicationEvent) message2.getPayload()).getSource()); + assertThat(message2).isNotNull(); + assertThat(((ApplicationEvent) message2.getPayload()).getSource()).isEqualTo("event1"); Message message3 = channel.receive(20); - assertNotNull(message3); - assertEquals("event2", ((ApplicationEvent) message3.getPayload()).getSource()); + assertThat(message3).isNotNull(); + assertThat(((ApplicationEvent) message3.getPayload()).getSource()).isEqualTo("event2"); } @Test @@ -94,26 +85,26 @@ public class ApplicationEventListeningMessageProducerTests { adapter.setEventTypes(TestApplicationEvent1.class); adapter.start(); Message message1 = channel.receive(0); - assertNull(message1); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))); + assertThat(message1).isNull(); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))).isTrue(); adapter.onApplicationEvent(new TestApplicationEvent1()); - assertFalse(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))).isFalse(); Message message2 = channel.receive(20); - assertNotNull(message2); - assertEquals("event1", ((ApplicationEvent) message2.getPayload()).getSource()); - assertNull(channel.receive(0)); + assertThat(message2).isNotNull(); + assertThat(((ApplicationEvent) message2.getPayload()).getSource()).isEqualTo("event1"); + assertThat(channel.receive(0)).isNull(); adapter.setEventTypes((Class) null); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))).isTrue(); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))).isTrue(); adapter.setEventTypes(null, TestApplicationEvent2.class, null); - assertFalse(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))).isFalse(); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))).isTrue(); adapter.setEventTypes(null, null); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))); - assertTrue(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent1.class))).isTrue(); + assertThat(adapter.supportsEventType(ResolvableType.forClass(TestApplicationEvent2.class))).isTrue(); } @Test @@ -122,20 +113,20 @@ public class ApplicationEventListeningMessageProducerTests { "applicationEventInboundChannelAdapterTests.xml", this.getClass()); PollableChannel channel = (PollableChannel) context.getBean("channel"); Message contextRefreshedEventMessage = channel.receive(0); - assertNotNull(contextRefreshedEventMessage); - assertEquals(ContextRefreshedEvent.class, contextRefreshedEventMessage.getPayload().getClass()); + assertThat(contextRefreshedEventMessage).isNotNull(); + assertThat(contextRefreshedEventMessage.getPayload().getClass()).isEqualTo(ContextRefreshedEvent.class); context.start(); Message startedEventMessage = channel.receive(0); - assertNotNull(startedEventMessage); - assertEquals(ContextStartedEvent.class, startedEventMessage.getPayload().getClass()); + assertThat(startedEventMessage).isNotNull(); + assertThat(startedEventMessage.getPayload().getClass()).isEqualTo(ContextStartedEvent.class); context.stop(); Message contextStoppedEventMessage = channel.receive(0); - assertNotNull(contextStoppedEventMessage); - assertEquals(ContextStoppedEvent.class, contextStoppedEventMessage.getPayload().getClass()); + assertThat(contextStoppedEventMessage).isNotNull(); + assertThat(contextStoppedEventMessage.getPayload().getClass()).isEqualTo(ContextStoppedEvent.class); context.close(); Message closedEventMessage = channel.receive(0); - assertNotNull(closedEventMessage); - assertEquals(ContextClosedEvent.class, closedEventMessage.getPayload().getClass()); + assertThat(closedEventMessage).isNotNull(); + assertThat(closedEventMessage.getPayload().getClass()).isEqualTo(ContextClosedEvent.class); } @Test @@ -158,18 +149,18 @@ public class ApplicationEventListeningMessageProducerTests { Message message1 = channel.receive(0); // ContextRefreshedEvent - assertNotNull(message1); - assertTrue(message1.getPayload().toString() - .contains("org.springframework.integration.test.util.TestUtils$TestApplicationContext")); + assertThat(message1).isNotNull(); + assertThat(message1.getPayload().toString() + .contains("org.springframework.integration.test.util.TestUtils$TestApplicationContext")).isTrue(); adapter.onApplicationEvent(new TestApplicationEvent1()); adapter.onApplicationEvent(new TestApplicationEvent2()); Message message2 = channel.receive(20); - assertNotNull(message2); - assertEquals("received: event1", message2.getPayload()); + assertThat(message2).isNotNull(); + assertThat(message2.getPayload()).isEqualTo("received: event1"); Message message3 = channel.receive(20); - assertNotNull(message3); - assertEquals("received: event2", message3.getPayload()); + assertThat(message3).isNotNull(); + assertThat(message3.getPayload()).isEqualTo("received: event2"); ctx.close(); } @@ -181,11 +172,11 @@ public class ApplicationEventListeningMessageProducerTests { adapter.setOutputChannel(channel); adapter.start(); Message message1 = channel.receive(0); - assertNull(message1); + assertThat(message1).isNull(); adapter.onApplicationEvent(new MessagingEvent(new GenericMessage<>("test"))); Message message2 = channel.receive(20); - assertNotNull(message2); - assertEquals("test", message2.getPayload()); + assertThat(message2).isNotNull(); + assertThat(message2.getPayload()).isEqualTo("test"); } @Test @@ -195,11 +186,11 @@ public class ApplicationEventListeningMessageProducerTests { adapter.setOutputChannel(channel); adapter.start(); Message message1 = channel.receive(0); - assertNull(message1); + assertThat(message1).isNull(); adapter.onApplicationEvent(new TestMessagingEvent(new GenericMessage<>("test"))); Message message2 = channel.receive(20); - assertNotNull(message2); - assertEquals("test", message2.getPayload()); + assertThat(message2).isNotNull(); + assertThat(message2.getPayload()).isEqualTo("test"); } @Test(expected = MessageHandlingException.class) @@ -219,8 +210,8 @@ public class ApplicationEventListeningMessageProducerTests { adapter.start(); adapter.onApplicationEvent(new TestApplicationEvent1()); Message message = errorChannel.receive(10000); - assertNotNull(message); - assertEquals("Failed", ((Exception) message.getPayload()).getCause().getMessage()); + assertThat(message).isNotNull(); + assertThat(((Exception) message.getPayload()).getCause().getMessage()).isEqualTo("Failed"); adapter.setErrorChannel(null); adapter.onApplicationEvent(new TestApplicationEvent1()); } @@ -254,27 +245,27 @@ public class ApplicationEventListeningMessageProducerTests { * Previously, the retrieverCache grew unnecessarily; the adapter was added to the cache for each event type, * event if not supported. */ - assertEquals(2, retrieverCache.size()); + assertThat(retrieverCache.size()).isEqualTo(2); for (Map.Entry entry : retrieverCache.entrySet()) { Class event = TestUtils.getPropertyValue(entry.getKey(), "eventType.resolved", Class.class); - assertThat(event, Matchers.is(Matchers.isOneOf(ContextRefreshedEvent.class, TestApplicationEvent1.class))); + assertThat(event).isIn(ContextRefreshedEvent.class, TestApplicationEvent1.class); Set listeners = TestUtils.getPropertyValue(entry.getValue(), "applicationListeners", Set.class); - assertEquals(1, listeners.size()); - assertSame(ctx.getBean("testListener"), listeners.iterator().next()); + assertThat(listeners.size()).isEqualTo(1); + assertThat(listeners.iterator().next()).isSameAs(ctx.getBean("testListener")); } TestApplicationEvent2 event2 = new TestApplicationEvent2(); ctx.publishEvent(event2); - assertEquals(3, retrieverCache.size()); + assertThat(retrieverCache.size()).isEqualTo(3); for (Map.Entry entry : retrieverCache.entrySet()) { Class event = TestUtils.getPropertyValue(entry.getKey(), "eventType.resolved", Class.class); if (TestApplicationEvent2.class.isAssignableFrom(event)) { Set listeners = TestUtils.getPropertyValue(entry.getValue(), "applicationListeners", Set.class); - assertEquals(2, listeners.size()); + assertThat(listeners.size()).isEqualTo(2); for (Object listener : listeners) { - assertThat(listener, - is(isOneOf(ctx.getBean("testListenerMessageProducer"), ctx.getBean("testListener")))); + assertThat(listener) + .isIn(ctx.getBean("testListenerMessageProducer"), ctx.getBean("testListener")); } break; } @@ -284,12 +275,12 @@ public class ApplicationEventListeningMessageProducerTests { }); - assertEquals(4, listenerCounter.get()); + assertThat(listenerCounter.get()).isEqualTo(4); final Message receive = channel.receive(10); - assertNotNull(receive); - assertSame(event2, receive.getPayload()); - assertNull(channel.receive(1)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isSameAs(event2); + assertThat(channel.receive(1)).isNull(); ctx.close(); } @@ -310,8 +301,8 @@ public class ApplicationEventListeningMessageProducerTests { ctx.publishEvent("foo"); Message receive = channel.receive(10000); - assertNotNull(receive); - assertEquals("foo", receive.getPayload()); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isEqualTo("foo"); ctx.close(); } diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/outbound/ApplicationEventPublishingMessageHandlerTests.java b/spring-integration-event/src/test/java/org/springframework/integration/event/outbound/ApplicationEventPublishingMessageHandlerTests.java index d90a767e07..2463e8c141 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/outbound/ApplicationEventPublishingMessageHandlerTests.java +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/outbound/ApplicationEventPublishingMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.event.outbound; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -37,12 +36,12 @@ public class ApplicationEventPublishingMessageHandlerTests { TestApplicationEventPublisher publisher = new TestApplicationEventPublisher(); ApplicationEventPublishingMessageHandler handler = new ApplicationEventPublishingMessageHandler(); handler.setApplicationEventPublisher(publisher); - assertNull(publisher.getLastEvent()); + assertThat(publisher.getLastEvent()).isNull(); Message message = new GenericMessage("testing"); handler.handleMessage(message); ApplicationEvent event = publisher.getLastEvent(); - assertEquals(MessagingEvent.class, event.getClass()); - assertEquals(message, ((MessagingEvent) event).getMessage()); + assertThat(event.getClass()).isEqualTo(MessagingEvent.class); + assertThat(((MessagingEvent) event).getMessage()).isEqualTo(message); } @Test @@ -50,12 +49,12 @@ public class ApplicationEventPublishingMessageHandlerTests { TestApplicationEventPublisher publisher = new TestApplicationEventPublisher(); ApplicationEventPublishingMessageHandler handler = new ApplicationEventPublishingMessageHandler(); handler.setApplicationEventPublisher(publisher); - assertNull(publisher.getLastEvent()); + assertThat(publisher.getLastEvent()).isNull(); Message message = new GenericMessage(new TestEvent("foo")); handler.handleMessage(message); ApplicationEvent event = publisher.getLastEvent(); - assertEquals(TestEvent.class, event.getClass()); - assertEquals("foo", ((TestEvent) event).getSource()); + assertThat(event.getClass()).isEqualTo(TestEvent.class); + assertThat(((TestEvent) event).getSource()).isEqualTo("foo"); } diff --git a/spring-integration-feed/src/test/java/org/springframework/integration/feed/config/FeedInboundChannelAdapterParserTests.java b/spring-integration-feed/src/test/java/org/springframework/integration/feed/config/FeedInboundChannelAdapterParserTests.java index f038d568d9..9e0da2b561 100644 --- a/spring-integration-feed/src/test/java/org/springframework/integration/feed/config/FeedInboundChannelAdapterParserTests.java +++ b/spring-integration-feed/src/test/java/org/springframework/integration/feed/config/FeedInboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.feed.config; -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.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; @@ -74,10 +70,10 @@ public class FeedInboundChannelAdapterParserTests { "FeedInboundChannelAdapterParserTests-file-context.xml", this.getClass()); SourcePollingChannelAdapter adapter = context.getBean("feedAdapter", SourcePollingChannelAdapter.class); FeedEntryMessageSource source = (FeedEntryMessageSource) TestUtils.getPropertyValue(adapter, "source"); - assertSame(context.getBean(MetadataStore.class), TestUtils.getPropertyValue(source, "metadataStore")); + assertThat(TestUtils.getPropertyValue(source, "metadataStore")).isSameAs(context.getBean(MetadataStore.class)); SyndFeedInput syndFeedInput = TestUtils.getPropertyValue(source, "syndFeedInput", SyndFeedInput.class); - assertSame(context.getBean(SyndFeedInput.class), syndFeedInput); - assertFalse(syndFeedInput.isPreserveWireFeed()); + assertThat(syndFeedInput).isSameAs(context.getBean(SyndFeedInput.class)); + assertThat(syndFeedInput.isPreserveWireFeed()).isFalse(); context.close(); } @@ -88,7 +84,7 @@ public class FeedInboundChannelAdapterParserTests { "FeedInboundChannelAdapterParserTests-http-context.xml", this.getClass()); SourcePollingChannelAdapter adapter = context.getBean("feedAdapter", SourcePollingChannelAdapter.class); FeedEntryMessageSource source = (FeedEntryMessageSource) TestUtils.getPropertyValue(adapter, "source"); - assertNotNull(TestUtils.getPropertyValue(source, "metadataStore")); + assertThat(TestUtils.getPropertyValue(source, "metadataStore")).isNotNull(); context.close(); } @@ -111,7 +107,8 @@ public class FeedInboundChannelAdapterParserTests { verify(latch, times(0)).countDown(); SourcePollingChannelAdapter adapter = context.getBean("feedAdapterUsage", SourcePollingChannelAdapter.class); - assertTrue(TestUtils.getPropertyValue(adapter, "source.syndFeedInput.preserveWireFeed", Boolean.class)); + assertThat(TestUtils.getPropertyValue(adapter, "source.syndFeedInput.preserveWireFeed", Boolean.class)) + .isTrue(); context.close(); } @@ -135,8 +132,9 @@ public class FeedInboundChannelAdapterParserTests { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "FeedInboundChannelAdapterParserTests-autoChannel-context.xml", this.getClass()); MessageChannel autoChannel = context.getBean("autoChannel", MessageChannel.class); - SourcePollingChannelAdapter adapter = context.getBean("autoChannel.adapter", SourcePollingChannelAdapter.class); - assertSame(autoChannel, TestUtils.getPropertyValue(adapter, "outputChannel")); + SourcePollingChannelAdapter adapter = context.getBean("autoChannel.adapter", + SourcePollingChannelAdapter.class); + assertThat(TestUtils.getPropertyValue(adapter, "outputChannel")).isSameAs(autoChannel); context.close(); } @@ -144,20 +142,24 @@ public class FeedInboundChannelAdapterParserTests { public void receiveFeedEntry(Message message) { MessageHistory history = MessageHistory.read(message); - assertEquals(3, history.size()); + assertThat(history).hasSize(3); Properties historyItem = history.get(0); - assertEquals("feedAdapterUsage", historyItem.get("name")); - assertEquals("feed:inbound-channel-adapter", historyItem.get("type")); + assertThat(historyItem) + .containsEntry("name", "feedAdapterUsage") + .containsEntry("type", "feed:inbound-channel-adapter"); historyItem = history.get(1); - assertEquals("feedChannelUsage", historyItem.get("name")); - assertEquals("channel", historyItem.get("type")); + assertThat(historyItem) + .containsEntry("name", "feedChannelUsage") + .containsEntry("type", "channel"); historyItem = history.get(2); - assertEquals("sampleActivator", historyItem.get("name")); - assertEquals("service-activator", historyItem.get("type")); + assertThat(historyItem) + .containsEntry("name", "sampleActivator") + .containsEntry("type", "service-activator"); latch.countDown(); } + } diff --git a/spring-integration-feed/src/test/java/org/springframework/integration/feed/dsl/FeedDslTests.java b/spring-integration-feed/src/test/java/org/springframework/integration/feed/dsl/FeedDslTests.java index ef51f8bdb5..375b3da26d 100644 --- a/spring-integration-feed/src/test/java/org/springframework/integration/feed/dsl/FeedDslTests.java +++ b/spring-integration-feed/src/test/java/org/springframework/integration/feed/dsl/FeedDslTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,10 +17,6 @@ package org.springframework.integration.feed.dsl; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import java.io.FileReader; import java.util.Properties; @@ -77,9 +73,9 @@ public class FeedDslTests { long time1 = message1.getPayload().getPublishedDate().getTime(); long time2 = message2.getPayload().getPublishedDate().getTime(); long time3 = message3.getPayload().getPublishedDate().getTime(); - assertTrue(time1 < time2); - assertTrue(time2 < time3); - assertNull(this.entries.receive(10)); + assertThat(time1 < time2).isTrue(); + assertThat(time2 < time3).isTrue(); + assertThat(this.entries.receive(10)).isNull(); this.metadataStore.flush(); @@ -87,9 +83,9 @@ public class FeedDslTests { new FileReader(tempFolder.getRoot().getAbsolutePath() + "/metadata-store.properties"); Properties metadataStoreProperties = new Properties(); metadataStoreProperties.load(metadataStoreFile); - assertFalse(metadataStoreProperties.isEmpty()); - assertEquals(1, metadataStoreProperties.size()); - assertTrue(metadataStoreProperties.containsKey("feedTest")); + assertThat(metadataStoreProperties.isEmpty()).isFalse(); + assertThat(metadataStoreProperties.size()).isEqualTo(1); + assertThat(metadataStoreProperties.containsKey("feedTest")).isTrue(); } @Configuration diff --git a/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java b/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java index 66ca4a4289..355063a614 100644 --- a/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java +++ b/spring-integration-feed/src/test/java/org/springframework/integration/feed/inbound/FeedEntryMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.feed.inbound; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.io.File; @@ -68,7 +66,7 @@ public class FeedEntryMessageSourceTests { feedEntrySource.setBeanName("feedReader"); feedEntrySource.setBeanFactory(mock(BeanFactory.class)); feedEntrySource.afterPropertiesSet(); - assertNull(feedEntrySource.receive()); + assertThat(feedEntrySource.receive()).isNull(); } @Test @@ -84,9 +82,9 @@ public class FeedEntryMessageSourceTests { long time1 = message1.getPayload().getPublishedDate().getTime(); long time2 = message2.getPayload().getPublishedDate().getTime(); long time3 = message3.getPayload().getPublishedDate().getTime(); - assertTrue(time1 < time2); - assertTrue(time2 < time3); - assertNull(source.receive()); + assertThat(time1 < time2).isTrue(); + assertThat(time2 < time3).isTrue(); + assertThat(source.receive()).isNull(); } // verifies that when entry has been updated since publish, that is taken into @@ -103,11 +101,11 @@ public class FeedEntryMessageSourceTests { feedEntrySource.afterPropertiesSet(); SyndEntry entry1 = feedEntrySource.receive().getPayload(); - assertNull(feedEntrySource.receive()); // only 1 entries in the test feed + assertThat(feedEntrySource.receive()).isNull(); // only 1 entries in the test feed - assertEquals("Atom draft-07 snapshot", entry1.getTitle().trim()); - assertEquals(1071318569000L, entry1.getPublishedDate().getTime()); - assertEquals(1122812969000L, entry1.getUpdatedDate().getTime()); + assertThat(entry1.getTitle().trim()).isEqualTo("Atom draft-07 snapshot"); + assertThat(entry1.getPublishedDate().getTime()).isEqualTo(1071318569000L); + assertThat(entry1.getUpdatedDate().getTime()).isEqualTo(1122812969000L); metadataStore.destroy(); metadataStore.afterPropertiesSet(); @@ -120,7 +118,7 @@ public class FeedEntryMessageSourceTests { feedEntrySource.setMetadataStore(metadataStore); feedEntrySource.setBeanFactory(mock(BeanFactory.class)); feedEntrySource.afterPropertiesSet(); - assertNull(feedEntrySource.receive()); + assertThat(feedEntrySource.receive()).isNull(); } // will test that last feed entry is remembered between the sessions @@ -138,16 +136,16 @@ public class FeedEntryMessageSourceTests { SyndEntry entry1 = feedEntrySource.receive().getPayload(); SyndEntry entry2 = feedEntrySource.receive().getPayload(); SyndEntry entry3 = feedEntrySource.receive().getPayload(); - assertNull(feedEntrySource.receive()); // only 3 entries in the test feed + assertThat(feedEntrySource.receive()).isNull(); // only 3 entries in the test feed - assertEquals("Spring Integration download", entry1.getTitle().trim()); - assertEquals(1266088337000L, entry1.getPublishedDate().getTime()); + assertThat(entry1.getTitle().trim()).isEqualTo("Spring Integration download"); + assertThat(entry1.getPublishedDate().getTime()).isEqualTo(1266088337000L); - assertEquals("Check out Spring Integration forums", entry2.getTitle().trim()); - assertEquals(1268469501000L, entry2.getPublishedDate().getTime()); + assertThat(entry2.getTitle().trim()).isEqualTo("Check out Spring Integration forums"); + assertThat(entry2.getPublishedDate().getTime()).isEqualTo(1268469501000L); - assertEquals("Spring Integration adapters", entry3.getTitle().trim()); - assertEquals(1272044098000L, entry3.getPublishedDate().getTime()); + assertThat(entry3.getTitle().trim()).isEqualTo("Spring Integration adapters"); + assertThat(entry3.getPublishedDate().getTime()).isEqualTo(1272044098000L); metadataStore.destroy(); metadataStore.afterPropertiesSet(); @@ -160,9 +158,9 @@ public class FeedEntryMessageSourceTests { feedEntrySource.setMetadataStore(metadataStore); feedEntrySource.setBeanFactory(mock(BeanFactory.class)); feedEntrySource.afterPropertiesSet(); - assertNull(feedEntrySource.receive()); - assertNull(feedEntrySource.receive()); - assertNull(feedEntrySource.receive()); + assertThat(feedEntrySource.receive()).isNull(); + assertThat(feedEntrySource.receive()).isNull(); + assertThat(feedEntrySource.receive()).isNull(); } // will test that last feed entry is NOT remembered between the sessions, since @@ -177,16 +175,16 @@ public class FeedEntryMessageSourceTests { SyndEntry entry1 = feedEntrySource.receive().getPayload(); SyndEntry entry2 = feedEntrySource.receive().getPayload(); SyndEntry entry3 = feedEntrySource.receive().getPayload(); - assertNull(feedEntrySource.receive()); // only 3 entries in the test feed + assertThat(feedEntrySource.receive()).isNull(); // only 3 entries in the test feed - assertEquals("Spring Integration download", entry1.getTitle().trim()); - assertEquals(1266088337000L, entry1.getPublishedDate().getTime()); + assertThat(entry1.getTitle().trim()).isEqualTo("Spring Integration download"); + assertThat(entry1.getPublishedDate().getTime()).isEqualTo(1266088337000L); - assertEquals("Check out Spring Integration forums", entry2.getTitle().trim()); - assertEquals(1268469501000L, entry2.getPublishedDate().getTime()); + assertThat(entry2.getTitle().trim()).isEqualTo("Check out Spring Integration forums"); + assertThat(entry2.getPublishedDate().getTime()).isEqualTo(1268469501000L); - assertEquals("Spring Integration adapters", entry3.getTitle().trim()); - assertEquals(1272044098000L, entry3.getPublishedDate().getTime()); + assertThat(entry3.getTitle().trim()).isEqualTo("Spring Integration adapters"); + assertThat(entry3.getPublishedDate().getTime()).isEqualTo(1272044098000L); // UNLIKE the previous test // now test that what's been read is read AGAIN @@ -197,16 +195,16 @@ public class FeedEntryMessageSourceTests { entry1 = feedEntrySource.receive().getPayload(); entry2 = feedEntrySource.receive().getPayload(); entry3 = feedEntrySource.receive().getPayload(); - assertNull(feedEntrySource.receive()); // only 3 entries in the test feed + assertThat(feedEntrySource.receive()).isNull(); // only 3 entries in the test feed - assertEquals("Spring Integration download", entry1.getTitle().trim()); - assertEquals(1266088337000L, entry1.getPublishedDate().getTime()); + assertThat(entry1.getTitle().trim()).isEqualTo("Spring Integration download"); + assertThat(entry1.getPublishedDate().getTime()).isEqualTo(1266088337000L); - assertEquals("Check out Spring Integration forums", entry2.getTitle().trim()); - assertEquals(1268469501000L, entry2.getPublishedDate().getTime()); + assertThat(entry2.getTitle().trim()).isEqualTo("Check out Spring Integration forums"); + assertThat(entry2.getPublishedDate().getTime()).isEqualTo(1268469501000L); - assertEquals("Spring Integration adapters", entry3.getTitle().trim()); - assertEquals(1272044098000L, entry3.getPublishedDate().getTime()); + assertThat(entry3.getTitle().trim()).isEqualTo("Spring Integration adapters"); + assertThat(entry3.getPublishedDate().getTime()).isEqualTo(1272044098000L); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java index 3619cec826..328019f3b0 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/AutoCreateDirectoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.io.File; @@ -67,7 +67,7 @@ public class AutoCreateDirectoryTests { source.setBeanFactory(mock(BeanFactory.class)); source.afterPropertiesSet(); source.start(); - assertTrue(new File(INBOUND_PATH).exists()); + assertThat(new File(INBOUND_PATH).exists()).isTrue(); } @Test(expected = IllegalArgumentException.class) @@ -86,7 +86,7 @@ public class AutoCreateDirectoryTests { new File(OUTBOUND_PATH)); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); - assertTrue(new File(OUTBOUND_PATH).exists()); + assertThat(new File(OUTBOUND_PATH).exists()).isTrue(); } @Test(expected = IllegalArgumentException.class) diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java index 0e4ff70dbd..db90216d38 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.io.File; @@ -39,7 +39,7 @@ public class DefaultFileNameGeneratorTests { generator.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, "foo").build(); String filename = generator.generateFileName(message); - assertEquals("foo", filename); + assertThat(filename).isEqualTo("foo"); } @Test @@ -48,7 +48,7 @@ public class DefaultFileNameGeneratorTests { generator.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test").build(); String filename = generator.generateFileName(message); - assertEquals(message.getHeaders().getId() + ".msg", filename); + assertThat(filename).isEqualTo(message.getHeaders().getId() + ".msg"); } @Test @@ -58,7 +58,7 @@ public class DefaultFileNameGeneratorTests { Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, new Integer(123)) .build(); String filename = generator.generateFileName(message); - assertEquals(message.getHeaders().getId() + ".msg", filename); + assertThat(filename).isEqualTo(message.getHeaders().getId() + ".msg"); } @Test @@ -68,7 +68,7 @@ public class DefaultFileNameGeneratorTests { generator.setHeaderName("foo"); Message message = MessageBuilder.withPayload("test").setHeader("foo", "bar").build(); String filename = generator.generateFileName(message); - assertEquals("bar", filename); + assertThat(filename).isEqualTo("bar"); } @Test @@ -78,7 +78,7 @@ public class DefaultFileNameGeneratorTests { generator.setHeaderName("foo"); Message message = MessageBuilder.withPayload("test").build(); String filename = generator.generateFileName(message); - assertEquals(message.getHeaders().getId() + ".msg", filename); + assertThat(filename).isEqualTo(message.getHeaders().getId() + ".msg"); } @Test @@ -88,7 +88,7 @@ public class DefaultFileNameGeneratorTests { generator.setHeaderName("foo"); Message message = MessageBuilder.withPayload("test").setHeader("foo", new Integer(123)).build(); String filename = generator.generateFileName(message); - assertEquals(message.getHeaders().getId() + ".msg", filename); + assertThat(filename).isEqualTo(message.getHeaders().getId() + ".msg"); } @Test @@ -98,7 +98,7 @@ public class DefaultFileNameGeneratorTests { File payload = new File("/some/path/foo"); Message message = MessageBuilder.withPayload(payload).build(); String filename = generator.generateFileName(message); - assertEquals("foo", filename); + assertThat(filename).isEqualTo("foo"); } @Test @@ -108,7 +108,7 @@ public class DefaultFileNameGeneratorTests { File payload = new File("/some/path/ignore"); Message message = MessageBuilder.withPayload(payload).setHeader(FileHeaders.FILENAME, "foo").build(); String filename = generator.generateFileName(message); - assertEquals("foo", filename); + assertThat(filename).isEqualTo("foo"); } @Test @@ -119,7 +119,7 @@ public class DefaultFileNameGeneratorTests { File payload = new File("/some/path/ignore"); Message message = MessageBuilder.withPayload(payload).setHeader("foo", "bar").build(); String filename = generator.generateFileName(message); - assertEquals("bar", filename); + assertThat(filename).isEqualTo("bar"); } @Test @@ -130,7 +130,7 @@ public class DefaultFileNameGeneratorTests { File payload = new File("/some/path/ignore"); Message message = MessageBuilder.withPayload(payload).build(); String filename = generator.generateFileName(message); - assertEquals("foobar", filename); + assertThat(filename).isEqualTo("foobar"); } @Test @@ -141,7 +141,7 @@ public class DefaultFileNameGeneratorTests { Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, "ignore") .setHeader("foo", "bar").build(); String filename = generator.generateFileName(message); - assertEquals("bar", filename); + assertThat(filename).isEqualTo("bar"); } @Test @@ -153,7 +153,7 @@ public class DefaultFileNameGeneratorTests { Message message = MessageBuilder.withPayload(payload).setHeader(FileHeaders.FILENAME, "ignore2") .setHeader("foo", "bar").build(); String filename = generator.generateFileName(message); - assertEquals("bar", filename); + assertThat(filename).isEqualTo("bar"); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileInboundTransactionTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileInboundTransactionTests.java index a0326fadaa..e72854efc5 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileInboundTransactionTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileInboundTransactionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.file; -import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @@ -90,7 +85,7 @@ public class FileInboundTransactionTests { public void testNoTx() throws Exception { Object scanner = TestUtils.getPropertyValue(pseudoTx.getMessageSource(), "scanner"); - assertThat(scanner.getClass().getName(), containsString("FileReadingMessageSource$WatchServiceDirectoryScanner")); + assertThat(scanner.getClass().getName()).contains("FileReadingMessageSource$WatchServiceDirectoryScanner"); @SuppressWarnings("unchecked") ResettableFileListFilter fileListFilter = @@ -110,19 +105,19 @@ public class FileInboundTransactionTests { File file = new File(tmpDir.getRoot(), "si-test1/foo"); file.createNewFile(); Message result = successChannel.receive(60000); - assertNotNull(result); - assertEquals(Boolean.TRUE, result.getPayload()); - assertFalse(file.delete()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(Boolean.TRUE); + assertThat(file.delete()).isFalse(); crash.set(true); file = new File(tmpDir.getRoot(), "si-test1/bar"); file.createNewFile(); result = failureChannel.receive(60000); - assertNotNull(result); - assertTrue(file.delete()); - assertEquals("foo", result.getPayload()); + assertThat(result).isNotNull(); + assertThat(file.delete()).isTrue(); + assertThat(result.getPayload()).isEqualTo("foo"); pseudoTx.stop(); - assertFalse(transactionManager.getCommitted()); - assertFalse(transactionManager.getRolledBack()); + assertThat(transactionManager.getCommitted()).isFalse(); + assertThat(transactionManager.getRolledBack()).isFalse(); verify(fileListFilter).remove(new File(tmpDir.getRoot(), "si-test1/foo")); } @@ -141,19 +136,19 @@ public class FileInboundTransactionTests { File file = new File(tmpDir.getRoot(), "si-test2/baz"); file.createNewFile(); Message result = successChannel.receive(60000); - assertNotNull(result); - assertEquals(Boolean.TRUE, result.getPayload()); - assertTrue(file.delete()); - assertTrue(transactionManager.getCommitted()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(Boolean.TRUE); + assertThat(file.delete()).isTrue(); + assertThat(transactionManager.getCommitted()).isTrue(); crash.set(true); file = new File(tmpDir.getRoot(), "si-test2/qux"); file.createNewFile(); result = failureChannel.receive(60000); - assertNotNull(result); - assertTrue(file.delete()); - assertEquals(Boolean.TRUE, result.getPayload()); + assertThat(result).isNotNull(); + assertThat(file.delete()).isTrue(); + assertThat(result.getPayload()).isEqualTo(Boolean.TRUE); realTx.stop(); - assertTrue(transactionManager.getRolledBack()); + assertThat(transactionManager.getRolledBack()).isTrue(); } public static class DummyTxManager extends AbstractPlatformTransactionManager { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterInsideChainTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterInsideChainTests.java index 8bdc724374..41f1fda835 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterInsideChainTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterInsideChainTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; @@ -86,9 +85,9 @@ public class FileOutboundChannelAdapterInsideChainTests { Message message = MessageBuilder.withPayload(SAMPLE_CONTENT).build(); outboundChainChannel.send(message); File testFile = new File(workDir, TEST_FILE_NAME); - assertTrue(testFile.exists()); + assertThat(testFile.exists()).isTrue(); byte[] testFileContent = FileCopyUtils.copyToByteArray(testFile); - assertEquals(new String(testFileContent), SAMPLE_CONTENT); + assertThat(SAMPLE_CONTENT).isEqualTo(new String(testFileContent)); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterIntegrationTests.java index 31c1f0f36e..ab10524e4a 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundChannelAdapterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 +16,13 @@ package org.springframework.integration.file; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + import java.io.File; import java.io.FileOutputStream; import org.junit.After; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -94,22 +96,22 @@ public class FileOutboundChannelAdapterIntegrationTests { public void saveToBaseDir() throws Exception { this.inputChannelSaveToBaseDir.send(message); - Assert.assertTrue(new File("target/base-directory/foo.txt").exists()); + assertThat(new File("target/base-directory/foo.txt").exists()).isTrue(); } @Test public void saveToBaseDirDeleteSourceFile() throws Exception { - Assert.assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); this.inputChannelSaveToBaseDirDeleteSource.send(message); - Assert.assertTrue(new File("target/base-directory/foo.txt").exists()); - Assert.assertFalse(sourceFile.exists()); + assertThat(new File("target/base-directory/foo.txt").exists()).isTrue(); + assertThat(sourceFile.exists()).isFalse(); } @Test public void saveToSubDir() throws Exception { this.inputChannelSaveToSubDir.send(message); - Assert.assertTrue(new File("target/base-directory/sub-directory/foo.txt").exists()); + assertThat(new File("target/base-directory/sub-directory/foo.txt").exists()).isTrue(); } @Test @@ -119,13 +121,13 @@ public class FileOutboundChannelAdapterIntegrationTests { this.inputChannelSaveToSubDirWrongExpression.send(message); } catch (MessageHandlingException e) { - Assert.assertEquals( - TestUtils.applySystemFileSeparator("Destination path [target/base-directory/sub-directory/foo.txt] does not point to a directory."), - e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo(TestUtils + .applySystemFileSeparator("Destination path [target/base-directory/sub-directory/foo.txt] does not" + + " point to a directory.")); return; } - Assert.fail("Was expecting a MessageHandlingException to be thrown"); + fail("Was expecting a MessageHandlingException to be thrown"); } @Test @@ -135,12 +137,12 @@ public class FileOutboundChannelAdapterIntegrationTests { this.inputChannelSaveToSubDirEmptyStringExpression.send(message); } catch (MessageHandlingException e) { - Assert.assertEquals("Unable to resolve Destination Directory for the provided Expression '' ''.", - e.getCause().getMessage()); + assertThat(e.getCause().getMessage()) + .isEqualTo("Unable to resolve Destination Directory for the provided Expression '' ''."); return; } - Assert.fail("Was expecting a MessageHandlingException to be thrown"); + fail("Was expecting a MessageHandlingException to be thrown"); } @Test @@ -151,7 +153,7 @@ public class FileOutboundChannelAdapterIntegrationTests { .build(); this.inputChannelSaveToSubDirWithHeader.send(message2); - Assert.assertTrue(new File("target/base-directory/headerdir/foo.txt").exists()); + assertThat(new File("target/base-directory/headerdir/foo.txt").exists()).isTrue(); } @Test @@ -161,13 +163,13 @@ public class FileOutboundChannelAdapterIntegrationTests { this.inputChannelSaveToSubDirAutoCreateOff.send(message); } catch (MessageHandlingException e) { - Assert.assertEquals( - TestUtils.applySystemFileSeparator("Destination directory [target/base-directory2/sub-directory2] does not exist."), - e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo(TestUtils + .applySystemFileSeparator("Destination directory [target/base-directory2/sub-directory2] does not " + + "exist.")); return; } - Assert.fail("Was expecting a MessageHandlingException to be thrown"); + fail("Was expecting a MessageHandlingException to be thrown"); } @Test @@ -178,7 +180,7 @@ public class FileOutboundChannelAdapterIntegrationTests { .setHeader("subDirectory", directory) .build(); this.inputChannelSaveToSubDirWithFile.send(messageWithFileHeader); - Assert.assertTrue(new File("target/base-directory/sub-directory/foo.txt").exists()); + assertThat(new File("target/base-directory/sub-directory/foo.txt").exists()).isTrue(); } @Test @@ -193,14 +195,13 @@ public class FileOutboundChannelAdapterIntegrationTests { this.inputChannelSaveToSubDirWithFile.send(messageWithFileHeader); } catch (MessageHandlingException e) { - Assert.assertEquals("The provided Destination Directory expression " + - "(headers['subDirectory']) must not evaluate to null.", - e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("The provided Destination Directory expression " + + "(headers['subDirectory']) must not evaluate to null."); return; } - Assert.fail("Was expecting a MessageHandlingException to be thrown"); + fail("Was expecting a MessageHandlingException to be thrown"); } @Test @@ -215,15 +216,14 @@ public class FileOutboundChannelAdapterIntegrationTests { this.inputChannelSaveToSubDirWithFile.send(messageWithFileHeader); } catch (MessageHandlingException e) { - Assert.assertEquals("The provided Destination Directory expression" + + assertThat(e.getCause().getMessage()).isEqualTo("The provided Destination Directory expression" + " (headers['subDirectory']) must evaluate to type " + - "java.io.File or String, not java.lang.Integer.", - e.getCause().getMessage()); + "java.io.File or String, not java.lang.Integer."); return; } - Assert.fail("Was expecting a MessageHandlingException to be thrown"); + fail("Was expecting a MessageHandlingException to be thrown"); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundGatewayIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundGatewayIntegrationTests.java index 5af446dffa..fff2b40bf5 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundGatewayIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileOutboundGatewayIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.file; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileOutputStream; @@ -74,7 +70,7 @@ public class FileOutboundGatewayIntegrationTests { static final String DEFAULT_ENCODING = "UTF-8"; - static final String SAMPLE_CONTENT = "HelloWorld\n��������"; + static final String SAMPLE_CONTENT = "HelloWorld\n????????"; Message message; @@ -115,55 +111,54 @@ public class FileOutboundGatewayIntegrationTests { @Test - public void instancesCreated() throws Exception { - assertThat(beanFactory.getBean("copier"), is(notNullValue())); - assertThat(beanFactory.getBean("mover"), is(notNullValue())); + public void instancesCreated() { + assertThat(beanFactory.getBean("copier")).isNotNull(); + assertThat(beanFactory.getBean("mover")).isNotNull(); } @Test - public void copy() throws Exception { + public void copy() { copyInputChannel.send(message); List> result = outputChannel.clear(); - assertThat(result.size(), is(1)); + assertThat(result.size()).isEqualTo(1); Message resultMessage = result.get(0); File payloadFile = (File) resultMessage.getPayload(); - assertThat(payloadFile, is(not(sourceFile))); - assertThat(resultMessage.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class), - is(sourceFile)); - assertThat(sourceFile.exists(), is(true)); - assertThat(payloadFile.exists(), is(true)); + assertThat(payloadFile).isNotEqualTo(sourceFile); + assertThat(resultMessage.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class)).isEqualTo(sourceFile); + assertThat(sourceFile.exists()).isTrue(); + assertThat(payloadFile.exists()).isTrue(); } @Test - public void move() throws Exception { + public void move() { moveInputChannel.send(message); List> result = outputChannel.clear(); - assertThat(result.size(), is(1)); + assertThat(result.size()).isEqualTo(1); Message resultMessage = result.get(0); File payloadFile = (File) resultMessage.getPayload(); - assertThat(payloadFile, is(not(sourceFile))); - assertThat(resultMessage.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class), - is(sourceFile)); - assertThat(sourceFile.exists(), is(false)); - assertThat(payloadFile.exists(), is(true)); + assertThat(payloadFile).isNotEqualTo(sourceFile); + assertThat(resultMessage.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class)).isEqualTo(sourceFile); + assertThat(sourceFile.exists()).isFalse(); + assertThat(payloadFile.exists()).isTrue(); } @Test //INT-1029 - public void moveInsideTheChain() throws Exception { + public void moveInsideTheChain() { // INT-2755 - Object bean = this.beanFactory.getBean("org.springframework.integration.handler.MessageHandlerChain#0$child.file-outbound-gateway-within-chain.handler"); - assertTrue(bean instanceof FileWritingMessageHandler); + Object bean = this.beanFactory + .getBean("org.springframework.integration.handler.MessageHandlerChain#0$child" + + ".file-outbound-gateway-within-chain.handler"); + assertThat(bean instanceof FileWritingMessageHandler).isTrue(); fileOutboundGatewayInsideChain.send(message); List> result = outputChannel.clear(); - assertThat(result.size(), is(1)); + assertThat(result.size()).isEqualTo(1); Message resultMessage = result.get(0); File payloadFile = (File) resultMessage.getPayload(); - assertThat(payloadFile, is(not(sourceFile))); - assertThat(resultMessage.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class), - is(sourceFile)); - assertThat(sourceFile.exists(), is(false)); - assertThat(payloadFile.exists(), is(true)); + assertThat(payloadFile).isNotEqualTo(sourceFile); + assertThat(resultMessage.getHeaders().get(FileHeaders.ORIGINAL_FILE, File.class)).isEqualTo(sourceFile); + assertThat(sourceFile.exists()).isFalse(); + assertThat(payloadFile.exists()).isTrue(); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java index 8325ec5e63..f5832ed168 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.file; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.concurrent.CountDownLatch; @@ -104,20 +101,20 @@ public class FileReadingMessageSourceIntegrationTests { @Test public void configured() throws Exception { DirectFieldAccessor accessor = new DirectFieldAccessor(pollableFileSource); - assertEquals(inputDir, accessor.getPropertyValue("directory")); + assertThat(accessor.getPropertyValue("directory")).isEqualTo(inputDir); } @Test public void getFiles() throws Exception { Message received1 = pollableFileSource.receive(); - assertNotNull("This should return the first message", received1); + assertThat(received1).as("This should return the first message").isNotNull(); Message received2 = pollableFileSource.receive(); - assertNotNull(received2); + assertThat(received2).isNotNull(); Message received3 = pollableFileSource.receive(); - assertNotNull(received3); - assertNotSame(received1 + " == " + received2, received1.getPayload(), received2.getPayload()); - assertNotSame(received1 + " == " + received3, received1.getPayload(), received3.getPayload()); - assertNotSame(received2 + " == " + received3, received2.getPayload(), received3.getPayload()); + assertThat(received3).isNotNull(); + assertThat(received2.getPayload()).as(received1 + " == " + received2).isNotSameAs(received1.getPayload()); + assertThat(received3.getPayload()).as(received1 + " == " + received3).isNotSameAs(received1.getPayload()); + assertThat(received3.getPayload()).as(received2 + " == " + received3).isNotSameAs(received2.getPayload()); } @Test @@ -125,22 +122,22 @@ public class FileReadingMessageSourceIntegrationTests { Message received1 = pollableFileSource.receive(); Message received2 = pollableFileSource.receive(); Message received3 = pollableFileSource.receive(); - assertNotSame(received1 + " == " + received2, received1, received2); - assertNotSame(received1 + " == " + received3, received1, received3); - assertNotSame(received2 + " == " + received3, received2, received3); + assertThat(received2).as(received1 + " == " + received2).isNotSameAs(received1); + assertThat(received3).as(received1 + " == " + received3).isNotSameAs(received1); + assertThat(received3).as(received2 + " == " + received3).isNotSameAs(received2); } @Test public void inputDirExhausted() throws Exception { - assertNotNull(pollableFileSource.receive()); - assertNotNull(pollableFileSource.receive()); + assertThat(pollableFileSource.receive()).isNotNull(); + assertThat(pollableFileSource.receive()).isNotNull(); Message receive = pollableFileSource.receive(); - assertNotNull(receive); + assertThat(receive).isNotNull(); File payload = receive.getPayload(); - assertEquals(payload, receive.getHeaders().get(FileHeaders.ORIGINAL_FILE)); - assertEquals(payload.getName(), receive.getHeaders().get(FileHeaders.FILENAME)); - assertEquals(payload.getName(), receive.getHeaders().get(FileHeaders.RELATIVE_PATH)); - assertNull(pollableFileSource.receive()); + assertThat(receive.getHeaders().get(FileHeaders.ORIGINAL_FILE)).isEqualTo(payload); + assertThat(receive.getHeaders().get(FileHeaders.FILENAME)).isEqualTo(payload.getName()); + assertThat(receive.getHeaders().get(FileHeaders.RELATIVE_PATH)).isEqualTo(payload.getName()); + assertThat(pollableFileSource.receive()).isNull(); } @Test @@ -172,7 +169,7 @@ public class FileReadingMessageSourceIntegrationTests { } // make sure three different files were taken Message received = pollableFileSource.receive(); - assertNull(received); + assertThat(received).isNull(); } /** diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java index 3ac32c67e8..a97b69601b 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2017 the original author or authors. + * Copyright 2013-2019 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,10 +16,7 @@ package org.springframework.integration.file; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -97,25 +94,25 @@ public class FileReadingMessageSourcePersistentFilterIntegrationTests { @Test public void configured() throws Exception { DirectFieldAccessor accessor = new DirectFieldAccessor(this.pollableFileSource); - assertEquals(inputDir, accessor.getPropertyValue("directory")); + assertThat(accessor.getPropertyValue("directory")).isEqualTo(inputDir); } @Test public void getFiles() throws Exception { Message received1 = this.pollableFileSource.receive(); - assertNotNull("This should return the first message", received1); + assertThat(received1).as("This should return the first message").isNotNull(); Message received2 = this.pollableFileSource.receive(); - assertNotNull(received2); + assertThat(received2).isNotNull(); Message received3 = this.pollableFileSource.receive(); - assertNotNull(received3); - assertNotSame(received1 + " == " + received2, received1.getPayload(), received2.getPayload()); - assertNotSame(received1 + " == " + received3, received1.getPayload(), received3.getPayload()); - assertNotSame(received2 + " == " + received3, received2.getPayload(), received3.getPayload()); + assertThat(received3).isNotNull(); + assertThat(received2.getPayload()).as(received1 + " == " + received2).isNotSameAs(received1.getPayload()); + assertThat(received3.getPayload()).as(received1 + " == " + received3).isNotSameAs(received1.getPayload()); + assertThat(received3.getPayload()).as(received2 + " == " + received3).isNotSameAs(received2.getPayload()); this.context.close(); loadContextAndGetMessageSource(); Message received4 = this.pollableFileSource.receive(); - assertNull(received4); + assertThat(received4).isNull(); this.context.close(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java index 2d9082bcfb..6829c52efe 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.file; -import static org.hamcrest.CoreMatchers.is; -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.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -84,16 +79,16 @@ public class FileReadingMessageSourceTests { @Test public void straightProcess() throws Exception { when(inputDirectoryMock.listFiles()).thenReturn(new File[] { fileMock }); - assertThat(source.receive().getPayload(), is(fileMock)); + assertThat(source.receive().getPayload()).isEqualTo(fileMock); } @Test public void requeueOnFailure() throws Exception { when(inputDirectoryMock.listFiles()).thenReturn(new File[] { fileMock }); Message received = source.receive(); - assertNotNull(received); + assertThat(received).isNotNull(); source.onFailure(received); - assertEquals(received.getPayload(), source.receive().getPayload()); + assertThat(source.receive().getPayload()).isEqualTo(received.getPayload()); verify(inputDirectoryMock, times(1)).listFiles(); } @@ -103,9 +98,9 @@ public class FileReadingMessageSourceTests { when(anotherFileMock.getAbsolutePath()).thenReturn("foo/bar/anotherFileMock"); when(inputDirectoryMock.listFiles()).thenReturn(new File[] { fileMock, anotherFileMock }); source.setScanEachPoll(true); - assertNotNull(source.receive()); - assertNotNull(source.receive()); - assertNull(source.receive()); + assertThat(source.receive()).isNotNull(); + assertThat(source.receive()).isNotNull(); + assertThat(source.receive()).isNull(); verify(inputDirectoryMock, times(3)).listFiles(); } @@ -113,9 +108,9 @@ public class FileReadingMessageSourceTests { public void noDuplication() throws Exception { when(inputDirectoryMock.listFiles()).thenReturn(new File[] { fileMock }); Message received = source.receive(); - assertNotNull(received); - assertEquals(fileMock, received.getPayload()); - assertNull(source.receive()); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo(fileMock); + assertThat(source.receive()).isNull(); verify(inputDirectoryMock, times(2)).listFiles(); } @@ -128,8 +123,8 @@ public class FileReadingMessageSourceTests { public void lockIsAcquired() throws IOException { when(inputDirectoryMock.listFiles()).thenReturn(new File[] { fileMock }); Message received = source.receive(); - assertNotNull(received); - assertEquals(fileMock, received.getPayload()); + assertThat(received).isNotNull(); + assertThat(received.getPayload()).isEqualTo(fileMock); verify(locker).lock(fileMock); } @@ -138,7 +133,7 @@ public class FileReadingMessageSourceTests { when(inputDirectoryMock.listFiles()).thenReturn(new File[] { fileMock }); when(locker.lock(fileMock)).thenReturn(false); Message received = source.receive(); - assertNull(received); + assertThat(received).isNull(); verify(locker).lock(fileMock); } @@ -157,10 +152,10 @@ public class FileReadingMessageSourceTests { when(comparator.compare(file3, file2)).thenReturn(-1); when(inputDirectoryMock.listFiles()).thenReturn(new File[]{file2, file3, file1}); - assertSame(file3, source.receive().getPayload()); - assertSame(file2, source.receive().getPayload()); - assertSame(file1, source.receive().getPayload()); - assertNull(source.receive()); + assertThat(source.receive().getPayload()).isSameAs(file3); + assertThat(source.receive().getPayload()).isSameAs(file2); + assertThat(source.receive().getPayload()).isSameAs(file1); + assertThat(source.receive()).isNull(); verify(inputDirectoryMock, times(2)).listFiles(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileToChannelIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileToChannelIntegrationTests.java index b3327418d2..9c0be47de0 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileToChannelIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileToChannelIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.file; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -58,19 +55,19 @@ public class FileToChannelIntegrationTests { file.setLastModified(System.currentTimeMillis() - 1000); Message received = this.fileMessages.receive(10000); - assertNotNull(received); + assertThat(received).isNotNull(); Message result = this.resultChannel.receive(10000); - assertNotNull(result); - assertEquals(Boolean.TRUE, result.getPayload()); - assertTrue(!file.exists()); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(Boolean.TRUE); + assertThat(!file.exists()).isTrue(); } @Test public void directoryExhaustion() throws Exception { File.createTempFile("test", null, inputDirectory).setLastModified(System.currentTimeMillis() - 1000); Message received = this.fileMessages.receive(10000); - assertNotNull(received); - assertNull(fileMessages.receive(200)); + assertThat(received).isNotNull(); + assertThat(fileMessages.receive(200)).isNull(); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java index b72743fca0..47e304479b 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileWritingMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,19 +16,8 @@ package org.springframework.integration.file; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.startsWith; @@ -90,7 +79,7 @@ public class FileWritingMessageHandlerTests { static final String DEFAULT_ENCODING = "UTF-8"; - static final String SAMPLE_CONTENT = "HelloWorld\näöüß"; + static final String SAMPLE_CONTENT = "HelloWorld\n????"; private File sourceFile; @@ -119,7 +108,7 @@ public class FileWritingMessageHandlerTests { @Test(expected = MessageHandlingException.class) public void unsupportedType() { this.handler.handleMessage(new GenericMessage<>(99)); - assertThat(this.outputDirectory.listFiles()[0], nullValue()); + assertThat(this.outputDirectory.listFiles()[0]).isNull(); } @Test @@ -128,18 +117,18 @@ public class FileWritingMessageHandlerTests { FileWritingMessageHandler handler = new FileWritingMessageHandler(mock(Expression.class)); handler.setChmod(0421); Set permissions = TestUtils.getPropertyValue(handler, "permissions", Set.class); - assertThat(permissions.size(), equalTo(3)); - assertTrue(permissions.contains(PosixFilePermission.OWNER_READ)); - assertTrue(permissions.contains(PosixFilePermission.GROUP_WRITE)); - assertTrue(permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); + assertThat(permissions.size()).isEqualTo(3); + assertThat(permissions.contains(PosixFilePermission.OWNER_READ)).isTrue(); + assertThat(permissions.contains(PosixFilePermission.GROUP_WRITE)).isTrue(); + assertThat(permissions.contains(PosixFilePermission.OTHERS_EXECUTE)).isTrue(); handler.setChmod(0600); permissions = TestUtils.getPropertyValue(handler, "permissions", Set.class); - assertThat(permissions.size(), equalTo(2)); - assertTrue(permissions.contains(PosixFilePermission.OWNER_READ)); - assertTrue(permissions.contains(PosixFilePermission.OWNER_WRITE)); + assertThat(permissions.size()).isEqualTo(2); + assertThat(permissions.contains(PosixFilePermission.OWNER_READ)).isTrue(); + assertThat(permissions.contains(PosixFilePermission.OWNER_WRITE)).isTrue(); handler.setChmod(0777); permissions = TestUtils.getPropertyValue(handler, "permissions", Set.class); - assertThat(permissions.size(), equalTo(9)); + assertThat(permissions.size()).isEqualTo(9); } } @@ -151,11 +140,11 @@ public class FileWritingMessageHandlerTests { handler.setOutputChannel(new NullChannel()); handler.handleMessage(new GenericMessage("test")); File[] output = outputDirectory.listFiles(); - assertThat(output.length, equalTo(1)); - assertThat(output[0], notNullValue()); + assertThat(output.length).isEqualTo(1); + assertThat(output[0]).isNotNull(); if (FileUtils.IS_POSIX) { Set permissions = Files.getPosixFilePermissions(output[0].toPath()); - assertThat(permissions.size(), equalTo(9)); + assertThat(permissions.size()).isEqualTo(9); } } @@ -187,7 +176,7 @@ public class FileWritingMessageHandlerTests { Message result = output.receive(0); assertFileContentIsMatching(result); File destFile = (File) result.getPayload(); - assertThat(destFile.getAbsolutePath(), containsString(TestUtils.applySystemFileSeparator("/dir1/dir2/test"))); + assertThat(destFile.getAbsolutePath()).contains(TestUtils.applySystemFileSeparator("/dir1/dir2/test")); } @Test @@ -286,7 +275,7 @@ public class FileWritingMessageHandlerTests { fail("Expected exception"); } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), containsString("[/foo] could not be created")); + assertThat(e.getMessage()).contains("[/foo] could not be created"); } } @@ -298,7 +287,7 @@ public class FileWritingMessageHandlerTests { handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); } @Test @@ -310,7 +299,7 @@ public class FileWritingMessageHandlerTests { handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertFalse(sourceFile.exists()); + assertThat(sourceFile.exists()).isFalse(); } @Test @@ -322,11 +311,11 @@ public class FileWritingMessageHandlerTests { Message message = MessageBuilder.withPayload(SAMPLE_CONTENT) .setHeader(FileHeaders.ORIGINAL_FILE, sourceFile) .build(); - assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertFalse(sourceFile.exists()); + assertThat(sourceFile.exists()).isFalse(); } @Test @@ -338,11 +327,11 @@ public class FileWritingMessageHandlerTests { Message message = MessageBuilder.withPayload(SAMPLE_CONTENT) .setHeader(FileHeaders.ORIGINAL_FILE, sourceFile.getAbsolutePath()) .build(); - assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertFalse(sourceFile.exists()); + assertThat(sourceFile.exists()).isFalse(); } @Test @@ -355,11 +344,11 @@ public class FileWritingMessageHandlerTests { SAMPLE_CONTENT.getBytes(DEFAULT_ENCODING)) .setHeader(FileHeaders.ORIGINAL_FILE, sourceFile) .build(); - assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertFalse(sourceFile.exists()); + assertThat(sourceFile.exists()).isFalse(); } @Test @@ -372,11 +361,11 @@ public class FileWritingMessageHandlerTests { SAMPLE_CONTENT.getBytes(DEFAULT_ENCODING)) .setHeader(FileHeaders.ORIGINAL_FILE, sourceFile.getAbsolutePath()) .build(); - assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertFalse(sourceFile.exists()); + assertThat(sourceFile.exists()).isFalse(); } @Test @@ -391,11 +380,11 @@ public class FileWritingMessageHandlerTests { Message message = MessageBuilder.withPayload(is) .setHeader(FileHeaders.ORIGINAL_FILE, sourceFile) .build(); - assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertFalse(sourceFile.exists()); + assertThat(sourceFile.exists()).isFalse(); } @Test @@ -410,11 +399,11 @@ public class FileWritingMessageHandlerTests { Message message = MessageBuilder.withPayload(is) .setHeader(FileHeaders.ORIGINAL_FILE, sourceFile.getAbsolutePath()) .build(); - assertTrue(sourceFile.exists()); + assertThat(sourceFile.exists()).isTrue(); handler.handleMessage(message); Message result = output.receive(0); assertFileContentIsMatching(result); - assertFalse(sourceFile.exists()); + assertThat(sourceFile.exists()).isFalse(); } @Test @@ -426,7 +415,7 @@ public class FileWritingMessageHandlerTests { Message message = MessageBuilder.withPayload("test").build(); handler.handleMessage(message); File result = (File) output.receive(0).getPayload(); - assertThat(result.getName(), is(anyFilename)); + assertThat(result.getName()).isEqualTo(anyFilename); } @Test @@ -455,9 +444,9 @@ public class FileWritingMessageHandlerTests { handler.handleMessage(message); Message result = output.receive(0); File destFile = (File) result.getPayload(); - assertNotSame(destFile, sourceFile); - assertThat(destFile.exists(), is(false)); - assertThat(outFile.exists(), is(true)); + assertThat(sourceFile).isNotSameAs(destFile); + assertThat(destFile.exists()).isFalse(); + assertThat(outFile.exists()).isTrue(); } @Test @@ -473,9 +462,9 @@ public class FileWritingMessageHandlerTests { handler.handleMessage(message); Message result = output.receive(0); File destFile = (File) result.getPayload(); - assertNotSame(destFile, sourceFile); + assertThat(sourceFile).isNotSameAs(destFile); assertFileContentIsMatching(result); - assertThat(outFile.exists(), is(true)); + assertThat(outFile.exists()).isTrue(); assertFileContentIs(outFile, "foo"); } @@ -498,9 +487,9 @@ public class FileWritingMessageHandlerTests { handler.handleMessage(new GenericMessage("bar")); handler.handleMessage(new GenericMessage("baz")); handler.handleMessage(new GenericMessage("qux".getBytes())); // change of payload type forces flush - assertThat(file.length(), greaterThanOrEqualTo(9L)); + assertThat(file.length()).isGreaterThanOrEqualTo(9L); handler.stop(); // forces flush - assertThat(file.length(), equalTo(12L)); + assertThat(file.length()).isEqualTo(12L); handler.setFlushInterval(100); handler.start(); handler.handleMessage(new GenericMessage(new ByteArrayInputStream("fiz".getBytes()))); @@ -508,11 +497,11 @@ public class FileWritingMessageHandlerTests { while (n++ < 100 && file.length() < 15) { Thread.sleep(100); } - assertThat(file.length(), equalTo(15L)); + assertThat(file.length()).isEqualTo(15L); handler.handleMessage(new GenericMessage(new ByteArrayInputStream("buz".getBytes()))); handler.trigger(new GenericMessage(Matcher.quoteReplacement(file.getAbsolutePath()))); - assertThat(file.length(), equalTo(18L)); - assertEquals(0, TestUtils.getPropertyValue(handler, "fileStates", Map.class).size()); + assertThat(file.length()).isEqualTo(18L); + assertThat(TestUtils.getPropertyValue(handler, "fileStates", Map.class).size()).isEqualTo(0); handler.setFlushInterval(30000); final AtomicBoolean called = new AtomicBoolean(); @@ -522,8 +511,8 @@ public class FileWritingMessageHandlerTests { }); handler.handleMessage(new GenericMessage(new ByteArrayInputStream("box".getBytes()))); handler.trigger(new GenericMessage("foo")); - assertThat(file.length(), equalTo(21L)); - assertTrue(called.get()); + assertThat(file.length()).isEqualTo(21L); + assertThat(called.get()).isTrue(); handler.handleMessage(new GenericMessage(new ByteArrayInputStream("bux".getBytes()))); called.set(false); @@ -531,8 +520,8 @@ public class FileWritingMessageHandlerTests { called.set(true); return true; }); - assertThat(file.length(), equalTo(24L)); - assertTrue(called.get()); + assertThat(file.length()).isEqualTo(24L); + assertThat(called.get()).isTrue(); handler.stop(); Log logger = spy(TestUtils.getPropertyValue(handler, "logger", Log.class)); @@ -550,7 +539,7 @@ public class FileWritingMessageHandlerTests { handler.handleMessage(new GenericMessage("foo")); Thread.sleep(5); } - assertThat(flushes.get(), greaterThanOrEqualTo(2)); + assertThat(flushes.get()).isGreaterThanOrEqualTo(2); handler.stop(); } @@ -593,7 +582,7 @@ public class FileWritingMessageHandlerTests { }).given(out).close(); handler.handleMessage(new GenericMessage<>("foo".getBytes())); verify(out).write(any(byte[].class), anyInt(), anyInt()); - assertFalse(closeWhileWriting.get()); + assertThat(closeWhileWriting.get()).isFalse(); handler.stop(); } @@ -689,19 +678,19 @@ public class FileWritingMessageHandlerTests { } void assertLastModifiedIs(Message result, long expected) { - assertThat(messageToFile(result).lastModified(), is(expected)); + assertThat(messageToFile(result).lastModified()).isEqualTo(expected); } void assertFileContentIs(File destFile, String expected) throws IOException { - assertNotSame(destFile, sourceFile); - assertThat(destFile.exists(), is(true)); + assertThat(sourceFile).isNotSameAs(destFile); + assertThat(destFile.exists()).isTrue(); byte[] destFileContent = FileCopyUtils.copyToByteArray(destFile); - assertThat(new String(destFileContent, DEFAULT_ENCODING), is(expected)); + assertThat(new String(destFileContent, DEFAULT_ENCODING)).isEqualTo(expected); } protected File messageToFile(Message result) { - assertThat(result, is(notNullValue())); - assertThat(result.getPayload(), is(instanceOf(File.class))); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isInstanceOf(File.class); File destFile = (File) result.getPayload(); return destFile; } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/PatternMatchingFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/PatternMatchingFileListFilterTests.java index a8bb53ae54..6d86148092 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/PatternMatchingFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/PatternMatchingFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.List; @@ -42,7 +41,7 @@ public class PatternMatchingFileListFilterTests { Pattern pattern = Pattern.compile("[a-z]+\\.txt"); RegexPatternFileListFilter filter = new RegexPatternFileListFilter(pattern); List accepted = filter.filterFiles(files); - assertEquals(1, accepted.size()); + assertThat(accepted.size()).isEqualTo(1); } @Test @@ -51,7 +50,7 @@ public class PatternMatchingFileListFilterTests { Pattern pattern = Pattern.compile("[a-z]+\\.txt"); RegexPatternFileListFilter filter = new RegexPatternFileListFilter(pattern); List accepted = filter.filterFiles(files); - assertEquals(0, accepted.size()); + assertThat(accepted.size()).isEqualTo(0); } @Test @@ -64,9 +63,9 @@ public class PatternMatchingFileListFilterTests { Pattern pattern = Pattern.compile("[a-z]+\\.txt"); RegexPatternFileListFilter filter = new RegexPatternFileListFilter(pattern); List accepted = filter.filterFiles(files); - assertEquals(2, accepted.size()); - assertTrue(accepted.contains(new File("/some/path/foo.txt"))); - assertTrue(accepted.contains(new File("/some/path/bar.txt"))); + assertThat(accepted.size()).isEqualTo(2); + assertThat(accepted.contains(new File("/some/path/foo.txt"))).isTrue(); + assertThat(accepted.contains(new File("/some/path/bar.txt"))).isTrue(); } @Test @@ -77,7 +76,7 @@ public class PatternMatchingFileListFilterTests { FileListFilter filter = (FileListFilter) context.getBean("filter"); File[] files = new File[] { new File("/some/path/foo.txt") }; List accepted = filter.filterFiles(files); - assertEquals(1, accepted.size()); + assertThat(accepted.size()).isEqualTo(1); context.close(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/RecursiveDirectoryScannerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/RecursiveDirectoryScannerTests.java index 6dfe5c3e54..7ff47b4fa4 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/RecursiveDirectoryScannerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/RecursiveDirectoryScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.file; -import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; @@ -71,17 +69,17 @@ public class RecursiveDirectoryScannerTests { RecursiveDirectoryScanner scanner = new RecursiveDirectoryScanner(); scanner.setFilter(new AcceptOnceFileListFilter<>()); List files = scanner.listFiles(this.recursivePath.getRoot()); - assertEquals(5, files.size()); - assertThat(files, hasItem(this.topLevelFile)); - assertThat(files, hasItem(this.subLevelFile)); - assertThat(files, hasItem(this.subSubLevelFile)); - assertThat(files, hasItem(this.subFolder)); - assertThat(files, hasItem(this.subSubFolder)); + assertThat(files.size()).isEqualTo(5); + assertThat(files).contains(this.topLevelFile); + assertThat(files).contains(this.subLevelFile); + assertThat(files).contains(this.subSubLevelFile); + assertThat(files).contains(this.subFolder); + assertThat(files).contains(this.subSubFolder); File file = new File(this.subSubFolder, "file4"); file.createNewFile(); files = scanner.listFiles(this.recursivePath.getRoot()); - assertEquals(1, files.size()); - assertThat(files, hasItem(file)); + assertThat(files.size()).isEqualTo(1); + assertThat(files).contains(file); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java index 5a1bd3c55f..d5552978b3 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/WatchServiceDirectoryScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 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,12 +16,7 @@ package org.springframework.integration.file; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.io.File; @@ -109,19 +104,18 @@ public class WatchServiceDirectoryScannerTests { fileReadingMessageSource.afterPropertiesSet(); fileReadingMessageSource.start(); DirectoryScanner scanner = fileReadingMessageSource.getScanner(); - assertThat(scanner.getClass().getName(), - containsString("FileReadingMessageSource$WatchServiceDirectoryScanner")); + assertThat(scanner.getClass().getName()).contains("FileReadingMessageSource$WatchServiceDirectoryScanner"); // Files are skipped by the LastModifiedFileListFilter List files = scanner.listFiles(folder.getRoot()); - assertEquals(0, files.size()); + assertThat(files.size()).isEqualTo(0); // Consider all the files as one day old fileLastModifiedFileListFilter.setAge(-60 * 60 * 24); files = scanner.listFiles(folder.getRoot()); - assertEquals(3, files.size()); - assertTrue(files.contains(top1)); - assertTrue(files.contains(foo1)); - assertTrue(files.contains(bar1)); + assertThat(files.size()).isEqualTo(3); + assertThat(files.contains(top1)).isTrue(); + assertThat(files.contains(foo1)).isTrue(); + assertThat(files.contains(bar1)).isTrue(); fileReadingMessageSource.start(); File top2 = this.folder.newFile(); File foo2 = File.createTempFile("foo", ".txt", this.foo); @@ -137,11 +131,11 @@ public class WatchServiceDirectoryScannerTests { files = scanner.listFiles(folder.getRoot()); accum.addAll(files); } - assertEquals(4, accum.size()); - assertTrue(accum.contains(top2)); - assertTrue(accum.contains(foo2)); - assertTrue(accum.contains(bar2)); - assertTrue(accum.contains(baz1)); + assertThat(accum.size()).isEqualTo(4); + assertThat(accum.contains(top2)).isTrue(); + assertThat(accum.contains(foo2)).isTrue(); + assertThat(accum.contains(bar2)).isTrue(); + assertThat(accum.contains(baz1)).isTrue(); /*See AbstractWatchKey#signalEvent source code: if(var5 >= 512) { @@ -162,7 +156,7 @@ public class WatchServiceDirectoryScannerTests { accum.addAll(files); } - assertEquals(604, accum.size()); + assertThat(accum.size()).isEqualTo(604); for (File fileForOverFlow : filesForOverflow) { accum.contains(fileForOverFlow); @@ -177,7 +171,7 @@ public class WatchServiceDirectoryScannerTests { accum.addAll(files); } - assertTrue(accum.contains(baz2)); + assertThat(accum.contains(baz2)).isTrue(); File baz2Copy = new File(baz2.getAbsolutePath()); @@ -191,8 +185,8 @@ public class WatchServiceDirectoryScannerTests { accum.addAll(files); } - assertEquals(1, files.size()); - assertTrue(files.contains(baz2)); + assertThat(files.size()).isEqualTo(1); + assertThat(files.contains(baz2)).isTrue(); baz2.delete(); @@ -203,7 +197,7 @@ public class WatchServiceDirectoryScannerTests { scanner.listFiles(folder.getRoot()); } - assertTrue(removeFileLatch.await(10, TimeUnit.SECONDS)); + assertThat(removeFileLatch.await(10, TimeUnit.SECONDS)).isTrue(); File baz3 = File.createTempFile("baz3", ".txt", baz); @@ -213,10 +207,10 @@ public class WatchServiceDirectoryScannerTests { Thread.sleep(100); } - assertNotNull(fileMessage); - assertEquals(baz3, fileMessage.getPayload()); - assertThat(fileMessage.getHeaders().get(FileHeaders.RELATIVE_PATH, String.class), - startsWith(TestUtils.applySystemFileSeparator("foo/baz/"))); + assertThat(fileMessage).isNotNull(); + assertThat(fileMessage.getPayload()).isEqualTo(baz3); + assertThat(fileMessage.getHeaders().get(FileHeaders.RELATIVE_PATH, String.class)) + .startsWith(TestUtils.applySystemFileSeparator("foo/baz/")); fileReadingMessageSource.stop(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java index 62ff792a25..02f3184b89 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -71,10 +70,9 @@ public class AutoCreateDirectoryIntegrationTests { DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); FileReadingMessageSource source = (FileReadingMessageSource) adapterAccessor.getPropertyValue("source"); - assertEquals(Boolean.TRUE, - new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")); + assertThat(new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")).isEqualTo(Boolean.TRUE); source.start(); - assertTrue(new File(BASE_PATH + File.separator + "defaultInbound").exists()); + assertThat(new File(BASE_PATH + File.separator + "defaultInbound").exists()).isTrue(); } @Test @@ -83,9 +81,8 @@ public class AutoCreateDirectoryIntegrationTests { DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); FileReadingMessageSource source = (FileReadingMessageSource) adapterAccessor.getPropertyValue("source"); - assertTrue(new File(BASE_PATH + File.separator + "customInbound").exists()); - assertEquals(Boolean.FALSE, - new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")); + assertThat(new File(BASE_PATH + File.separator + "customInbound").exists()).isTrue(); + assertThat(new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")).isEqualTo(Boolean.FALSE); } @Test @@ -94,9 +91,8 @@ public class AutoCreateDirectoryIntegrationTests { DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); FileWritingMessageHandler handler = (FileWritingMessageHandler) adapterAccessor.getPropertyValue("handler"); - assertEquals(Boolean.TRUE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); - assertTrue(new File(BASE_PATH + File.separator + "defaultOutbound").exists()); + assertThat(new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")).isEqualTo(Boolean.TRUE); + assertThat(new File(BASE_PATH + File.separator + "defaultOutbound").exists()).isTrue(); } @Test @@ -105,9 +101,8 @@ public class AutoCreateDirectoryIntegrationTests { DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); FileWritingMessageHandler handler = (FileWritingMessageHandler) adapterAccessor.getPropertyValue("handler"); - assertTrue(new File(BASE_PATH + File.separator + "customOutbound").exists()); - assertEquals(Boolean.FALSE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); + assertThat(new File(BASE_PATH + File.separator + "customOutbound").exists()).isTrue(); + assertThat(new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")).isEqualTo(Boolean.FALSE); } @Test @@ -116,9 +111,8 @@ public class AutoCreateDirectoryIntegrationTests { DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(gateway); FileWritingMessageHandler handler = (FileWritingMessageHandler) gatewayAccessor.getPropertyValue("handler"); - assertEquals(Boolean.TRUE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); - assertTrue(new File(BASE_PATH + File.separator + "defaultOutboundGateway").exists()); + assertThat(new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")).isEqualTo(Boolean.TRUE); + assertThat(new File(BASE_PATH + File.separator + "defaultOutboundGateway").exists()).isTrue(); } @Test @@ -127,9 +121,8 @@ public class AutoCreateDirectoryIntegrationTests { DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(gateway); FileWritingMessageHandler handler = (FileWritingMessageHandler) gatewayAccessor.getPropertyValue("handler"); - assertTrue(new File(BASE_PATH + File.separator + "customOutboundGateway").exists()); - assertEquals(Boolean.FALSE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); + assertThat(new File(BASE_PATH + File.separator + "customOutboundGateway").exists()).isTrue(); + assertThat(new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")).isEqualTo(Boolean.FALSE); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/ChainElementsTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/ChainElementsTests.java index 8d3eb19bf2..c793726def 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/ChainElementsTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/ChainElementsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.util.Properties; @@ -55,8 +54,9 @@ public class ChainElementsTests { "inside a ) endpoint element: 'int-file:outbound-gateway' " + "with id='myFileOutboundGateway'."; final String actualMessage = e.getMessage(); - assertTrue("Error message did not start with '" + expectedMessage + - "' but instead returned: '" + actualMessage + "'", actualMessage.startsWith(expectedMessage)); + assertThat(actualMessage.startsWith(expectedMessage)) + .as("Error message did not start with '" + expectedMessage + + "' but instead returned: '" + actualMessage + "'").isTrue(); } } @@ -67,8 +67,9 @@ public class ChainElementsTests { fail("Expected a XmlBeanDefinitionStoreException to be thrown."); } catch (XmlBeanDefinitionStoreException e) { - assertEquals("cvc-complex-type.3.2.2: Attribute 'input-channel' is not" + - " allowed to appear in element 'int-file:outbound-gateway'.", e.getCause().getMessage()); + assertThat(e.getCause().getMessage()).isEqualTo("cvc-complex-type.3.2.2: Attribute 'input-channel' is " + + "not" + + " allowed to appear in element 'int-file:outbound-gateway'."); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/DefaultConfigurationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/DefaultConfigurationTests.java index 3372bcd044..07ea914a57 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/DefaultConfigurationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/DefaultConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -53,31 +51,31 @@ public class DefaultConfigurationTests { @Test public void verifyErrorChannel() { Object errorChannel = context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME); - assertNotNull(errorChannel); - assertEquals(PublishSubscribeChannel.class, errorChannel.getClass()); + assertThat(errorChannel).isNotNull(); + assertThat(errorChannel.getClass()).isEqualTo(PublishSubscribeChannel.class); } @Test public void verifyNullChannel() { Object nullChannel = context.getBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME); - assertNotNull(nullChannel); - assertEquals(NullChannel.class, nullChannel.getClass()); + assertThat(nullChannel).isNotNull(); + assertThat(nullChannel.getClass()).isEqualTo(NullChannel.class); } @Test public void verifyTaskScheduler() { Object taskScheduler = context.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME); - assertEquals(ThreadPoolTaskScheduler.class, taskScheduler.getClass()); + assertThat(taskScheduler.getClass()).isEqualTo(ThreadPoolTaskScheduler.class); ErrorHandler errorHandler = TestUtils.getPropertyValue(taskScheduler, "errorHandler", ErrorHandler.class); - assertEquals(MessagePublishingErrorHandler.class, errorHandler.getClass()); + assertThat(errorHandler.getClass()).isEqualTo(MessagePublishingErrorHandler.class); MessageChannel defaultErrorChannel = TestUtils.getPropertyValue(errorHandler, "messagingTemplate.defaultDestination", MessageChannel.class); - assertNull(defaultErrorChannel); + assertThat(defaultErrorChannel).isNull(); errorHandler.handleError(new Throwable()); defaultErrorChannel = TestUtils.getPropertyValue(errorHandler, "messagingTemplate.defaultDestination", MessageChannel.class); - assertNotNull(defaultErrorChannel); - assertEquals(context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME), defaultErrorChannel); + assertThat(defaultErrorChannel).isNotNull(); + assertThat(defaultErrorChannel).isEqualTo(context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME)); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterParserTests.java index f9f5d976ef..3e051b9a32 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,15 +16,7 @@ package org.springframework.integration.file.config; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.isOneOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Comparator; @@ -85,25 +77,26 @@ public class FileInboundChannelAdapterParserTests { } @Test - public void channelName() throws Exception { + public void channelName() { AbstractMessageChannel channel = context.getBean("inputDirPoller", AbstractMessageChannel.class); - assertEquals("Channel should be available under specified id", "inputDirPoller", channel.getComponentName()); + assertThat(channel.getComponentName()).as("Channel should be available under specified id") + .isEqualTo("inputDirPoller"); } @Test - public void justFilter() throws Exception { + public void justFilter() { Iterator filterIterator = TestUtils .getPropertyValue(this.inboundWithJustFilterSource, "scanner.filter.fileFilters", Set.class).iterator(); - assertThat(filterIterator.next(), instanceOf(IgnoreHiddenFileListFilter.class)); - assertSame(this.filter, filterIterator.next()); + assertThat(filterIterator.next()).isInstanceOf(IgnoreHiddenFileListFilter.class); + assertThat(filterIterator.next()).isSameAs(this.filter); } @Test public void inputDirectory() { File expected = new File(System.getProperty("java.io.tmpdir")); File actual = (File) this.accessor.getPropertyValue("directory"); - assertEquals("'directory' should be set", expected, actual); - assertThat(this.accessor.getPropertyValue("scanEachPoll"), is(Boolean.TRUE)); + assertThat(actual).as("'directory' should be set").isEqualTo(expected); + assertThat(this.accessor.getPropertyValue("scanEachPoll")).isEqualTo(Boolean.TRUE); } @Test @@ -111,26 +104,27 @@ public class FileInboundChannelAdapterParserTests { DefaultDirectoryScanner scanner = (DefaultDirectoryScanner) accessor.getPropertyValue("scanner"); DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(scanner); Object filter = scannerAccessor.getPropertyValue("filter"); - assertTrue("'filter' should be set and be of instance AcceptOnceFileListFilter but got " - + filter.getClass().getSimpleName(), filter instanceof AcceptOnceFileListFilter); + assertThat(filter instanceof AcceptOnceFileListFilter) + .as("'filter' should be set and be of instance AcceptOnceFileListFilter but got " + + filter.getClass().getSimpleName()).isTrue(); - assertThat(scanner.getClass().getName(), - containsString("FileReadingMessageSource$WatchServiceDirectoryScanner")); + assertThat(scanner.getClass().getName()).contains("FileReadingMessageSource$WatchServiceDirectoryScanner"); FileReadingMessageSource.WatchEventType[] watchEvents = (FileReadingMessageSource.WatchEventType[]) this.accessor.getPropertyValue("watchEvents"); - assertEquals(2, watchEvents.length); + assertThat(watchEvents.length).isEqualTo(2); for (FileReadingMessageSource.WatchEventType watchEvent : watchEvents) { - assertNotEquals(FileReadingMessageSource.WatchEventType.CREATE, watchEvent); - assertThat(watchEvent, isOneOf(FileReadingMessageSource.WatchEventType.MODIFY, - FileReadingMessageSource.WatchEventType.DELETE)); + assertThat(watchEvent).isNotEqualTo(FileReadingMessageSource.WatchEventType.CREATE); + assertThat(watchEvent) + .isIn(FileReadingMessageSource.WatchEventType.MODIFY, + FileReadingMessageSource.WatchEventType.DELETE); } } @Test - public void comparator() throws Exception { + public void comparator() { Object priorityQueue = accessor.getPropertyValue("toBeReceived"); - assertEquals(PriorityBlockingQueue.class, priorityQueue.getClass()); + assertThat(priorityQueue).isInstanceOf(PriorityBlockingQueue.class); Object expected = context.getBean("testComparator"); DirectFieldAccessor queueAccessor = new DirectFieldAccessor(priorityQueue); Object innerQueue = queueAccessor.getPropertyValue("q"); @@ -142,7 +136,7 @@ public class FileInboundChannelAdapterParserTests { // probably running under JDK 7 actual = queueAccessor.getPropertyValue("comparator"); } - assertSame("comparator reference not set, ", expected, actual); + assertThat(actual).as("comparator reference not set, ").isSameAs(expected); } static class TestComparator implements Comparator { @@ -151,5 +145,7 @@ public class FileInboundChannelAdapterParserTests { public int compare(File f1, File f2) { return 0; } + } + } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithClasspathInPropertiesTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithClasspathInPropertiesTests.java index 54267ea0d1..c8338db243 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithClasspathInPropertiesTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithClasspathInPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.file.config; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Iterator; @@ -67,21 +64,21 @@ public class FileInboundChannelAdapterWithClasspathInPropertiesTests { public void inputDirectory() throws Exception { File expected = new ClassPathResource("").getFile(); File actual = (File) accessor.getPropertyValue("directory"); - assertEquals("'directory' should be set", expected, actual); + assertThat(actual).as("'directory' should be set").isEqualTo(expected); FileListFilter fileListFilter = TestUtils.getPropertyValue(this.source, "scanner.filter", FileListFilter.class); - assertThat(fileListFilter, instanceOf(CompositeFileListFilter.class)); + assertThat(fileListFilter).isInstanceOf(CompositeFileListFilter.class); Set> fileFilters = TestUtils.getPropertyValue(fileListFilter, "fileFilters", Set.class); - assertEquals(2, fileFilters.size()); + assertThat(fileFilters.size()).isEqualTo(2); Iterator> iterator = fileFilters.iterator(); iterator.next(); FileListFilter expressionFilter = iterator.next(); - assertThat(expressionFilter, instanceOf(ExpressionFileListFilter.class)); - assertEquals("true", - TestUtils.getPropertyValue(expressionFilter, "expression.expression", String.class)); - assertSame(this.beanFactory, TestUtils.getPropertyValue(expressionFilter, "beanFactory")); + assertThat(expressionFilter).isInstanceOf(ExpressionFileListFilter.class); + assertThat(TestUtils.getPropertyValue(expressionFilter, "expression.expression", String.class)) + .isEqualTo("true"); + assertThat(TestUtils.getPropertyValue(expressionFilter, "beanFactory")).isSameAs(this.beanFactory); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java index 9c14b9382d..f16c099617 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Set; @@ -68,26 +65,26 @@ public class FileInboundChannelAdapterWithPatternParserTests { @Test public void channelName() { AbstractMessageChannel channel = context.getBean("adapterWithPattern", AbstractMessageChannel.class); - assertEquals("adapterWithPattern", channel.getComponentName()); + assertThat(channel.getComponentName()).isEqualTo("adapterWithPattern"); } @Test public void autoStartupDisabled() { - assertFalse(this.endpoint.isRunning()); - assertEquals(Boolean.FALSE, new DirectFieldAccessor(endpoint).getPropertyValue("autoStartup")); + assertThat(this.endpoint.isRunning()).isFalse(); + assertThat(new DirectFieldAccessor(endpoint).getPropertyValue("autoStartup")).isEqualTo(Boolean.FALSE); } @Test public void inputDirectory() { File expected = new File(System.getProperty("java.io.tmpdir")); File actual = (File) accessor.getPropertyValue("directory"); - assertEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Test public void compositeFilterType() { DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); - assertTrue(scannerAccessor.getPropertyValue("filter") instanceof CompositeFileListFilter); + assertThat(scannerAccessor.getPropertyValue("filter") instanceof CompositeFileListFilter).isTrue(); } @Test @@ -96,7 +93,7 @@ public class FileInboundChannelAdapterWithPatternParserTests { DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); Set> filters = (Set>) new DirectFieldAccessor( scannerAccessor.getPropertyValue("filter")).getPropertyValue("fileFilters"); - assertEquals(2, filters.size()); + assertThat(filters.size()).isEqualTo(2); } @Test @@ -111,7 +108,7 @@ public class FileInboundChannelAdapterWithPatternParserTests { hasAcceptOnceFilter = true; } } - assertTrue("expected AcceptOnceFileListFilter", hasAcceptOnceFilter); + assertThat(hasAcceptOnceFilter).as("expected AcceptOnceFileListFilter").isTrue(); } @Test @@ -126,8 +123,8 @@ public class FileInboundChannelAdapterWithPatternParserTests { pattern = (String) new DirectFieldAccessor(filter).getPropertyValue("path"); } } - assertNotNull("expected SimplePatternFileListFilterTest", pattern); - assertEquals("*.txt", pattern.toString()); + assertThat(pattern).as("expected SimplePatternFileListFilterTest").isNotNull(); + assertThat(pattern.toString()).isEqualTo("*.txt"); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPreventDuplicatesFlagTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPreventDuplicatesFlagTests.java index e0b65da0cc..d34b7f89fa 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPreventDuplicatesFlagTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPreventDuplicatesFlagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,14 +16,7 @@ package org.springframework.integration.file.config; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Collection; @@ -64,91 +57,91 @@ public class FileInboundChannelAdapterWithPreventDuplicatesFlagTests { @Test public void filterAndNull() { FileListFilter filter = this.extractFilter("filterAndNull"); - assertFalse(filter instanceof CompositeFileListFilter); - assertSame(testFilter, filter); + assertThat(filter instanceof CompositeFileListFilter).isFalse(); + assertThat(filter).isSameAs(testFilter); } @Test public void filterAndTrue() { FileListFilter filter = this.extractFilter("filterAndTrue"); - assertTrue(filter instanceof CompositeFileListFilter); + assertThat(filter instanceof CompositeFileListFilter).isTrue(); Collection filters = (Collection) new DirectFieldAccessor(filter).getPropertyValue("fileFilters"); - assertTrue(filters.iterator().next() instanceof AcceptOnceFileListFilter); - assertTrue(filters.contains(testFilter)); + assertThat(filters.iterator().next() instanceof AcceptOnceFileListFilter).isTrue(); + assertThat(filters.contains(testFilter)).isTrue(); } @Test public void filterAndFalse() throws Exception { FileListFilter filter = this.extractFilter("filterAndFalse"); - assertFalse(filter instanceof CompositeFileListFilter); - assertSame(testFilter, filter); + assertThat(filter instanceof CompositeFileListFilter).isFalse(); + assertThat(filter).isSameAs(testFilter); } @Test @SuppressWarnings("unchecked") public void patternAndNull() throws Exception { FileListFilter filter = this.extractFilter("patternAndNull"); - assertTrue(filter instanceof CompositeFileListFilter); + assertThat(filter instanceof CompositeFileListFilter).isTrue(); Collection> filters = (Collection>) new DirectFieldAccessor(filter).getPropertyValue("fileFilters"); Iterator> iterator = filters.iterator(); - assertTrue(iterator.next() instanceof AcceptOnceFileListFilter); - assertThat(iterator.next(), is(instanceOf(SimplePatternFileListFilter.class))); + assertThat(iterator.next() instanceof AcceptOnceFileListFilter).isTrue(); + assertThat(iterator.next()).isInstanceOf(SimplePatternFileListFilter.class); } @Test @SuppressWarnings("unchecked") public void patternAndTrue() throws Exception { FileListFilter filter = this.extractFilter("patternAndTrue"); - assertTrue(filter instanceof CompositeFileListFilter); + assertThat(filter instanceof CompositeFileListFilter).isTrue(); Collection> filters = (Collection>) new DirectFieldAccessor(filter).getPropertyValue("fileFilters"); Iterator> iterator = filters.iterator(); - assertTrue(iterator.next() instanceof AcceptOnceFileListFilter); - assertThat(iterator.next(), is(instanceOf(SimplePatternFileListFilter.class))); + assertThat(iterator.next() instanceof AcceptOnceFileListFilter).isTrue(); + assertThat(iterator.next()).isInstanceOf(SimplePatternFileListFilter.class); } @Test public void patternAndFalse() throws Exception { FileListFilter filter = this.extractFilter("patternAndFalse"); - assertFalse(filter instanceof CompositeFileListFilter); - assertThat(filter, is(instanceOf(SimplePatternFileListFilter.class))); + assertThat(filter instanceof CompositeFileListFilter).isFalse(); + assertThat(filter).isInstanceOf(SimplePatternFileListFilter.class); } @Test public void defaultAndNull() throws Exception { FileListFilter filter = this.extractFilter("defaultAndNull"); - assertNotNull(filter); - assertFalse(filter instanceof CompositeFileListFilter); - assertTrue(filter instanceof AcceptOnceFileListFilter); + assertThat(filter).isNotNull(); + assertThat(filter instanceof CompositeFileListFilter).isFalse(); + assertThat(filter instanceof AcceptOnceFileListFilter).isTrue(); File testFile = new File("test"); File[] files = new File[] { testFile, testFile, testFile }; List result = filter.filterFiles(files); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); } @Test public void defaultAndTrue() throws Exception { FileListFilter filter = this.extractFilter("defaultAndTrue"); - assertFalse(filter instanceof CompositeFileListFilter); - assertTrue(filter instanceof AcceptOnceFileListFilter); + assertThat(filter instanceof CompositeFileListFilter).isFalse(); + assertThat(filter instanceof AcceptOnceFileListFilter).isTrue(); File testFile = new File("test"); File[] files = new File[] { testFile, testFile, testFile }; List result = filter.filterFiles(files); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); } @Test public void defaultAndFalse() throws Exception { FileListFilter filter = this.extractFilter("defaultAndFalse"); - assertNotNull(filter); - assertFalse(filter instanceof CompositeFileListFilter); - assertFalse(filter instanceof AcceptOnceFileListFilter); + assertThat(filter).isNotNull(); + assertThat(filter instanceof CompositeFileListFilter).isFalse(); + assertThat(filter instanceof AcceptOnceFileListFilter).isFalse(); File testFile = new File("test"); File[] files = new File[] { testFile, testFile, testFile }; List result = filter.filterFiles(files); - assertEquals(3, result.size()); + assertThat(result.size()).isEqualTo(3); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithQueueSizeTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithQueueSizeTests.java index e9e60b403a..2623ec495c 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithQueueSizeTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithQueueSizeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.List; @@ -88,15 +88,15 @@ public class FileInboundChannelAdapterWithQueueSizeTests { HeadDirectoryScanner scanner1 = TestUtils.getPropertyValue(source1, "scanner", HeadDirectoryScanner.class); HeadDirectoryScanner scanner2 = TestUtils.getPropertyValue(source2, "scanner", HeadDirectoryScanner.class); List files = scanner1.listFiles(new File(PATHNAME)); - assertEquals(2, files.size()); + assertThat(files.size()).isEqualTo(2); files = scanner2.listFiles(new File(PATHNAME)); - assertEquals(2, files.size()); + assertThat(files.size()).isEqualTo(2); files.get(0).delete(); files.get(1).delete(); files = scanner1.listFiles(new File(PATHNAME)); - assertEquals(1, files.size()); + assertThat(files.size()).isEqualTo(1); files = scanner2.listFiles(new File(PATHNAME)); - assertEquals(1, files.size()); + assertThat(files.size()).isEqualTo(1); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithRegexPatternParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithRegexPatternParserTests.java index 24e1688815..2e8db65c73 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithRegexPatternParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithRegexPatternParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.file.config; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Set; import java.util.regex.Pattern; @@ -60,7 +56,7 @@ public class FileInboundChannelAdapterWithRegexPatternParserTests { public void regexFilter() { DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); Object extractedFilter = scannerAccessor.getPropertyValue("filter"); - assertThat(extractedFilter, is(instanceOf(CompositeFileListFilter.class))); + assertThat(extractedFilter).isInstanceOf(CompositeFileListFilter.class); Set> filters = (Set>) new DirectFieldAccessor( extractedFilter).getPropertyValue("fileFilters"); Pattern pattern = null; @@ -69,8 +65,8 @@ public class FileInboundChannelAdapterWithRegexPatternParserTests { pattern = (Pattern) new DirectFieldAccessor(filter).getPropertyValue("pattern"); } } - assertNotNull("expected PatternMatchingFileListFilter", pattern); - assertEquals("^.*\\.txt$", pattern.pattern()); + assertThat(pattern).as("expected PatternMatchingFileListFilter").isNotNull(); + assertThat(pattern.pattern()).isEqualTo("^.*\\.txt$"); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileListFilterFactoryBeanTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileListFilterFactoryBeanTests.java index be9019d38c..51412e9f48 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileListFilterFactoryBeanTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileListFilterFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.file.config; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.Collection; @@ -60,8 +55,8 @@ public class FileListFilterFactoryBeanTests { TestFilter testFilter = new TestFilter(); factory.setFilter(testFilter); FileListFilter result = factory.getObject(); - assertFalse(result instanceof CompositeFileListFilter); - assertSame(testFilter, result); + assertThat(result instanceof CompositeFileListFilter).isFalse(); + assertThat(result).isSameAs(testFilter); } @Test @@ -72,10 +67,10 @@ public class FileListFilterFactoryBeanTests { factory.setFilter(testFilter); factory.setPreventDuplicates(Boolean.TRUE); FileListFilter result = factory.getObject(); - assertTrue(result instanceof CompositeFileListFilter); + assertThat(result instanceof CompositeFileListFilter).isTrue(); Collection filters = (Collection) new DirectFieldAccessor(result).getPropertyValue("fileFilters"); - assertTrue(filters.iterator().next() instanceof AcceptOnceFileListFilter); - assertTrue(filters.contains(testFilter)); + assertThat(filters.iterator().next() instanceof AcceptOnceFileListFilter).isTrue(); + assertThat(filters.contains(testFilter)).isTrue(); } @Test @@ -86,8 +81,8 @@ public class FileListFilterFactoryBeanTests { factory.setFilter(testFilter); factory.setPreventDuplicates(Boolean.FALSE); FileListFilter result = factory.getObject(); - assertFalse(result instanceof CompositeFileListFilter); - assertSame(testFilter, result); + assertThat(result instanceof CompositeFileListFilter).isFalse(); + assertThat(result).isSameAs(testFilter); } @Test @@ -97,12 +92,12 @@ public class FileListFilterFactoryBeanTests { factory.setIgnoreHidden(false); factory.setFilenamePattern("foo"); FileListFilter result = factory.getObject(); - assertTrue(result instanceof CompositeFileListFilter); + assertThat(result instanceof CompositeFileListFilter).isTrue(); Collection> filters = (Collection>) new DirectFieldAccessor(result).getPropertyValue("fileFilters"); Iterator> iterator = filters.iterator(); - assertTrue(iterator.next() instanceof AcceptOnceFileListFilter); - assertThat(iterator.next(), is(instanceOf(SimplePatternFileListFilter.class))); + assertThat(iterator.next() instanceof AcceptOnceFileListFilter).isTrue(); + assertThat(iterator.next()).isInstanceOf(SimplePatternFileListFilter.class); } @Test @@ -113,14 +108,14 @@ public class FileListFilterFactoryBeanTests { factory.setFilenamePattern(("foo")); factory.setPreventDuplicates(Boolean.TRUE); FileListFilter result = factory.getObject(); - assertTrue(result instanceof CompositeFileListFilter); + assertThat(result instanceof CompositeFileListFilter).isTrue(); Collection> filters = (Collection>) new DirectFieldAccessor(result).getPropertyValue("fileFilters"); Iterator> iterator = filters.iterator(); - assertTrue(iterator.next() instanceof AcceptOnceFileListFilter); + assertThat(iterator.next() instanceof AcceptOnceFileListFilter).isTrue(); FileListFilter patternFilter = iterator.next(); - assertThat(patternFilter, is(instanceOf(SimplePatternFileListFilter.class))); - assertFalse(TestUtils.getPropertyValue(patternFilter, "alwaysAcceptDirectories", Boolean.class)); + assertThat(patternFilter).isInstanceOf(SimplePatternFileListFilter.class); + assertThat(TestUtils.getPropertyValue(patternFilter, "alwaysAcceptDirectories", Boolean.class)).isFalse(); } @Test @@ -131,9 +126,9 @@ public class FileListFilterFactoryBeanTests { factory.setAlwaysAcceptDirectories(true); factory.setPreventDuplicates(Boolean.FALSE); FileListFilter result = factory.getObject(); - assertFalse(result instanceof CompositeFileListFilter); - assertThat(result, is(instanceOf(SimplePatternFileListFilter.class))); - assertTrue(TestUtils.getPropertyValue(result, "alwaysAcceptDirectories", Boolean.class)); + assertThat(result instanceof CompositeFileListFilter).isFalse(); + assertThat(result).isInstanceOf(SimplePatternFileListFilter.class); + assertThat(TestUtils.getPropertyValue(result, "alwaysAcceptDirectories", Boolean.class)).isTrue(); } private static class TestFilter extends AbstractFileListFilter { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java index 8068a1f23c..81ac5d6b4a 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.file.config; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.BufferedWriter; import java.io.File; @@ -58,12 +54,12 @@ public class FileMessageHistoryTests { PollableChannel outChannel = context.getBean("outChannel", PollableChannel.class); Message message = outChannel.receive(10000); - assertThat(message, is(notNullValue())); + assertThat(message).isNotNull(); MessageHistory history = MessageHistory.read(message); - assertThat(history, is(notNullValue())); + assertThat(history).isNotNull(); Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "fileAdapter", 0); - assertNotNull(componentHistoryRecord); - assertEquals("file:inbound-channel-adapter", componentHistoryRecord.get("type")); + assertThat(componentHistoryRecord).isNotNull(); + assertThat(componentHistoryRecord.get("type")).isEqualTo("file:inbound-channel-adapter"); context.close(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundAdaptersWithClasspathInPropertiesTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundAdaptersWithClasspathInPropertiesTests.java index 75b109cdda..a4df77345d 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundAdaptersWithClasspathInPropertiesTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundAdaptersWithClasspathInPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -61,7 +61,7 @@ public class FileOutboundAdaptersWithClasspathInPropertiesTests { Expression destinationDirectoryExpression = (Expression) accessor.getPropertyValue("destinationDirectoryExpression"); File actual = new File(destinationDirectoryExpression.getExpressionString()); - assertEquals("'destinationDirectory' should be set", expected, actual); + assertThat(actual).as("'destinationDirectory' should be set").isEqualTo(expected); } @Test @@ -73,7 +73,7 @@ public class FileOutboundAdaptersWithClasspathInPropertiesTests { Expression destinationDirectoryExpression = (Expression) accessor.getPropertyValue("destinationDirectoryExpression"); File actual = new File(destinationDirectoryExpression.getExpressionString()); - assertEquals("'destinationDirectory' should be set", expected, actual); + assertThat(actual).as("'destinationDirectory' should be set").isEqualTo(expected); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserTests.java index d2a8c7b7d5..0a0b5fd0ed 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,14 +16,8 @@ package org.springframework.integration.file.config; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.File; import java.lang.reflect.Method; @@ -32,7 +26,6 @@ import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -134,20 +127,20 @@ public class FileOutboundChannelAdapterParserTests { Expression destinationDirectoryExpression = (Expression) handlerAccessor.getPropertyValue("destinationDirectoryExpression"); File actual = new File(destinationDirectoryExpression.getExpressionString()); - assertEquals(".foo", TestUtils.getPropertyValue(handler, "temporaryFileSuffix", String.class)); - assertThat(actual, is(expected)); + assertThat(TestUtils.getPropertyValue(handler, "temporaryFileSuffix", String.class)).isEqualTo(".foo"); + assertThat(actual).isEqualTo(expected); DefaultFileNameGenerator fileNameGenerator = (DefaultFileNameGenerator) handlerAccessor.getPropertyValue("fileNameGenerator"); - assertNotNull(fileNameGenerator); + assertThat(fileNameGenerator).isNotNull(); Expression expression = TestUtils.getPropertyValue(fileNameGenerator, "expression", Expression.class); - assertNotNull(expression); - assertEquals("'foo.txt'", expression.getExpressionString()); - assertEquals(Boolean.FALSE, handlerAccessor.getPropertyValue("deleteSourceFiles")); - assertEquals(Boolean.TRUE, handlerAccessor.getPropertyValue("flushWhenIdle")); + assertThat(expression).isNotNull(); + assertThat(expression.getExpressionString()).isEqualTo("'foo.txt'"); + assertThat(handlerAccessor.getPropertyValue("deleteSourceFiles")).isEqualTo(Boolean.FALSE); + assertThat(handlerAccessor.getPropertyValue("flushWhenIdle")).isEqualTo(Boolean.TRUE); if (FileUtils.IS_POSIX) { - assertThat(TestUtils.getPropertyValue(handler, "permissions", Set.class).size(), equalTo(9)); + assertThat(TestUtils.getPropertyValue(handler, "permissions", Set.class).size()).isEqualTo(9); } - assertEquals(Boolean.TRUE, handlerAccessor.getPropertyValue("preserveTimestamp")); + assertThat(handlerAccessor.getPropertyValue("preserveTimestamp")).isEqualTo(Boolean.TRUE); } @Test @@ -162,10 +155,10 @@ public class FileOutboundChannelAdapterParserTests { (Expression) handlerAccessor.getPropertyValue("destinationDirectoryExpression"); File actual = new File(destinationDirectoryExpression.getExpressionString()); - assertEquals(expected, actual); - assertTrue(handlerAccessor.getPropertyValue("fileNameGenerator") instanceof CustomFileNameGenerator); - assertEquals(".writing", handlerAccessor.getPropertyValue("temporaryFileSuffix")); - assertEquals(Boolean.FALSE, handlerAccessor.getPropertyValue("flushWhenIdle")); + assertThat(actual).isEqualTo(expected); + assertThat(handlerAccessor.getPropertyValue("fileNameGenerator") instanceof CustomFileNameGenerator).isTrue(); + assertThat(handlerAccessor.getPropertyValue("temporaryFileSuffix")).isEqualTo(".writing"); + assertThat(handlerAccessor.getPropertyValue("flushWhenIdle")).isEqualTo(Boolean.FALSE); } @Test @@ -174,7 +167,7 @@ public class FileOutboundChannelAdapterParserTests { FileWritingMessageHandler handler = (FileWritingMessageHandler) adapterAccessor.getPropertyValue("handler"); DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(handler); - assertEquals(Boolean.TRUE, handlerAccessor.getPropertyValue("deleteSourceFiles")); + assertThat(handlerAccessor.getPropertyValue("deleteSourceFiles")).isEqualTo(Boolean.TRUE); } @Test @@ -183,7 +176,7 @@ public class FileOutboundChannelAdapterParserTests { FileWritingMessageHandler handler = (FileWritingMessageHandler) adapterAccessor.getPropertyValue("handler"); DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(handler); - assertEquals(555, handlerAccessor.getPropertyValue("order")); + assertThat(handlerAccessor.getPropertyValue("order")).isEqualTo(555); } @Test @@ -192,16 +185,16 @@ public class FileOutboundChannelAdapterParserTests { FileWritingMessageHandler handler = (FileWritingMessageHandler) adapterAccessor.getPropertyValue("handler"); DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(handler); - assertEquals(4096, handlerAccessor.getPropertyValue("bufferSize")); - assertEquals(12345L, handlerAccessor.getPropertyValue("flushInterval")); - assertEquals(FileExistsMode.APPEND_NO_FLUSH, handlerAccessor.getPropertyValue("fileExistsMode")); - assertSame(this.predicate, handlerAccessor.getPropertyValue("flushPredicate")); + assertThat(handlerAccessor.getPropertyValue("bufferSize")).isEqualTo(4096); + assertThat(handlerAccessor.getPropertyValue("flushInterval")).isEqualTo(12345L); + assertThat(handlerAccessor.getPropertyValue("fileExistsMode")).isEqualTo(FileExistsMode.APPEND_NO_FLUSH); + assertThat(handlerAccessor.getPropertyValue("flushPredicate")).isSameAs(this.predicate); } @Test public void adapterWithAutoStartupFalse() { DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapterWithOrder); - assertEquals(Boolean.FALSE, adapterAccessor.getPropertyValue("autoStartup")); + assertThat(adapterAccessor.getPropertyValue("autoStartup")).isEqualTo(Boolean.FALSE); } @Test @@ -210,7 +203,7 @@ public class FileOutboundChannelAdapterParserTests { FileWritingMessageHandler handler = (FileWritingMessageHandler) adapterAccessor.getPropertyValue("handler"); DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(handler); - assertEquals(Charset.forName("UTF-8"), handlerAccessor.getPropertyValue("charset")); + assertThat(handlerAccessor.getPropertyValue("charset")).isEqualTo(Charset.forName("UTF-8")); } @Test @@ -220,12 +213,12 @@ public class FileOutboundChannelAdapterParserTests { TestUtils.getPropertyValue(adapterWithDirectoryExpression, "handler", FileWritingMessageHandler.class); Method m = ReflectionUtils.findMethod(FileWritingMessageHandler.class, "getTemporaryFileSuffix"); ReflectionUtils.makeAccessible(m); - assertEquals(".writing", ReflectionUtils.invokeMethod(m, handler)); + assertThat(ReflectionUtils.invokeMethod(m, handler)).isEqualTo(".writing"); String expectedExpressionString = "'foo/bar'"; String actualExpressionString = TestUtils.getPropertyValue(handler, "destinationDirectoryExpression", Expression.class) .getExpressionString(); - assertEquals(expectedExpressionString, actualExpressionString); + assertThat(actualExpressionString).isEqualTo(expectedExpressionString); } @@ -244,14 +237,15 @@ public class FileOutboundChannelAdapterParserTests { usageChannel.send(new GenericMessage<>(new File("test/input.txt"))); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); - assertEquals(4, adviceCalled); + assertThat(actualFileContent).isEqualTo(expectedFileContent); + assertThat(adviceCalled).isEqualTo(4); testFile.delete(); } @Test public void adapterUsageWithAppendAndAppendNewLineTrue() throws Exception { - assertEquals(Boolean.TRUE, TestUtils.getPropertyValue(this.adapterWithAppendNewLine, "handler.appendNewLine")); + assertThat(TestUtils.getPropertyValue(this.adapterWithAppendNewLine, "handler.appendNewLine")) + .isEqualTo(Boolean.TRUE); String newLine = System.getProperty("line.separator"); String expectedFileContent = "Initial File Content:" + newLine + "String content:" + newLine + "byte[] content:" + newLine + "File content" + newLine; @@ -266,7 +260,7 @@ public class FileOutboundChannelAdapterParserTests { adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<>(new File("test/input.txt"))); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); testFile.delete(); } @@ -284,7 +278,7 @@ public class FileOutboundChannelAdapterParserTests { adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<>(new File("test/input.txt"))); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); testFile.delete(); } @@ -302,12 +296,12 @@ public class FileOutboundChannelAdapterParserTests { usageChannelWithFailMode.send(new GenericMessage<>("String content:")); } catch (MessagingException e) { - assertThat(e.getMessage(), containsString("The destination file already exists at")); + assertThat(e.getMessage()).contains("The destination file already exists at"); testFile.delete(); return; } - Assert.fail("Was expecting an Exception to be thrown."); + fail("Was expecting an Exception to be thrown."); } @Test @@ -325,7 +319,7 @@ public class FileOutboundChannelAdapterParserTests { usageChannelWithIgnoreMode.send(new GenericMessage<>("String content:")); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); testFile.delete(); } @@ -352,7 +346,7 @@ public class FileOutboundChannelAdapterParserTests { usageChannelConcurrent.send(new GenericMessage<>(bString)); } - assertTrue(this.fileWriteLatch.await(10, TimeUnit.SECONDS)); + assertThat(this.fileWriteLatch.await(10, TimeUnit.SECONDS)).isTrue(); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); int beginningIndex = 0; @@ -367,7 +361,7 @@ public class FileOutboundChannelAdapterParserTests { char[] characters = substring.toCharArray(); char c = characters[0]; for (char character : characters) { - assertEquals(c, character); + assertThat(character).isEqualTo(c); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserWithErrorsTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserWithErrorsTests.java index 136ce1902f..fcaeab3709 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserWithErrorsTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundChannelAdapterParserWithErrorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import org.junit.Test; @@ -40,11 +40,11 @@ public class FileOutboundChannelAdapterParserWithErrorsTests { getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertEquals("Configuration problem: Either directory or " + + assertThat(e.getMessage()).isEqualTo("Configuration problem: Either directory or " + "directory-expression must be provided but not both\nOffending " + "resource: class path " + - "resource [org/springframework/integration/file/config/FileOutboundChannelAdapterParserWithErrorsTests-context.xml]", - e.getMessage()); + "resource [org/springframework/integration/file/config" + + "/FileOutboundChannelAdapterParserWithErrorsTests-context.xml]"); return; } @@ -60,10 +60,9 @@ public class FileOutboundChannelAdapterParserWithErrorsTests { getClass()).close(); } catch (BeanDefinitionParsingException e) { - assertEquals("Configuration problem: directory or directory-expression " + + assertThat(e.getMessage()).isEqualTo("Configuration problem: directory or directory-expression " + "is required\nOffending resource: class path resource " + - "[org/springframework/integration/file/config/FileOutboundChannelAdapterParserWithErrors2Tests-context.xml]", - e.getMessage()); + "[org/springframework/integration/file/config/FileOutboundChannelAdapterParserWithErrors2Tests-context.xml]"); return; } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java index 22aa15b476..c4c8873408 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileOutboundGatewayParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,8 @@ package org.springframework.integration.file.config; -import static org.hamcrest.Matchers.startsWith; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.File; @@ -93,19 +88,19 @@ public class FileOutboundGatewayParserTests { DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(ordered); FileWritingMessageHandler handler = (FileWritingMessageHandler) gatewayAccessor.getPropertyValue("handler"); - assertEquals(Boolean.FALSE, gatewayAccessor.getPropertyValue("autoStartup")); + assertThat(gatewayAccessor.getPropertyValue("autoStartup")).isEqualTo(Boolean.FALSE); DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(handler); - assertEquals(777, handlerAccessor.getPropertyValue("order")); - assertEquals(Boolean.TRUE, handlerAccessor.getPropertyValue("requiresReply")); + assertThat(handlerAccessor.getPropertyValue("order")).isEqualTo(777); + assertThat(handlerAccessor.getPropertyValue("requiresReply")).isEqualTo(Boolean.TRUE); DefaultFileNameGenerator fileNameGenerator = (DefaultFileNameGenerator) handlerAccessor.getPropertyValue("fileNameGenerator"); - assertNotNull(fileNameGenerator); + assertThat(fileNameGenerator).isNotNull(); Expression expression = TestUtils.getPropertyValue(fileNameGenerator, "expression", Expression.class); - assertNotNull(expression); - assertEquals("'foo.txt'", expression.getExpressionString()); + assertThat(expression).isNotNull(); + assertThat(expression.getExpressionString()).isEqualTo("'foo.txt'"); Long sendTimeout = TestUtils.getPropertyValue(handler, "messagingTemplate.sendTimeout", Long.class); - assertEquals(Long.valueOf(777), sendTimeout); + assertThat(sendTimeout).isEqualTo(Long.valueOf(777)); } @@ -113,11 +108,10 @@ public class FileOutboundGatewayParserTests { public void testOutboundGatewayWithDirectoryExpression() { FileWritingMessageHandler handler = TestUtils.getPropertyValue(gatewayWithDirectoryExpression, "handler", FileWritingMessageHandler.class); - assertEquals("'build/foo'", - TestUtils.getPropertyValue(handler, "destinationDirectoryExpression", Expression.class) - .getExpressionString()); + assertThat(TestUtils.getPropertyValue(handler, "destinationDirectoryExpression", Expression.class) + .getExpressionString()).isEqualTo("'build/foo'"); handler.handleMessage(new GenericMessage<>("foo")); - assertEquals(1, adviceCalled); + assertThat(adviceCalled).isEqualTo(1); } /** @@ -146,13 +140,13 @@ public class FileOutboundGatewayParserTests { Message replyMessage = messagingTemplate.sendAndReceive(new GenericMessage<>("String content:")); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); - assertTrue(replyMessage.getPayload() instanceof File); + assertThat(replyMessage.getPayload() instanceof File).isTrue(); File replyPayload = (File) replyMessage.getPayload(); - assertEquals(expectedFileContent, new String(FileCopyUtils.copyToByteArray(replyPayload))); + assertThat(new String(FileCopyUtils.copyToByteArray(replyPayload))).isEqualTo(expectedFileContent); } @@ -180,7 +174,7 @@ public class FileOutboundGatewayParserTests { messagingTemplate.sendAndReceive(new GenericMessage<>("Initial File Content:")); final String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); try { @@ -188,7 +182,7 @@ public class FileOutboundGatewayParserTests { } catch (MessageHandlingException e) { - assertThat(e.getMessage(), startsWith("The destination file already exists at '")); + assertThat(e.getMessage()).startsWith("The destination file already exists at '"); return; } @@ -221,7 +215,7 @@ public class FileOutboundGatewayParserTests { messagingTemplate.sendAndReceive(new GenericMessage<>("Initial File Content:")); final String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); try { @@ -229,7 +223,7 @@ public class FileOutboundGatewayParserTests { } catch (MessageHandlingException e) { - assertThat(e.getMessage(), startsWith("The destination file already exists at '")); + assertThat(e.getMessage()).startsWith("The destination file already exists at '"); return; } @@ -265,12 +259,12 @@ public class FileOutboundGatewayParserTests { Message m = messagingTemplate.sendAndReceive(new GenericMessage<>("String content:")); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); - assertTrue(m.getPayload() instanceof File); + assertThat(m.getPayload() instanceof File).isTrue(); File replyPayload = (File) m.getPayload(); - assertEquals(expectedFileContent, new String(FileCopyUtils.copyToByteArray(replyPayload))); + assertThat(new String(FileCopyUtils.copyToByteArray(replyPayload))).isEqualTo(expectedFileContent); } @@ -287,7 +281,8 @@ public class FileOutboundGatewayParserTests { @Test public void gatewayWithReplaceMode() throws Exception { - assertFalse(TestUtils.getPropertyValue(this.gatewayWithReplaceModeHandler, "requiresReply", Boolean.class)); + assertThat(TestUtils.getPropertyValue(this.gatewayWithReplaceModeHandler, "requiresReply", Boolean.class)) + .isFalse(); final MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultDestination(this.gatewayWithReplaceModeChannel); @@ -304,12 +299,12 @@ public class FileOutboundGatewayParserTests { Message m = messagingTemplate.sendAndReceive(new GenericMessage<>("String content:")); String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile)); - assertEquals(expectedFileContent, actualFileContent); + assertThat(actualFileContent).isEqualTo(expectedFileContent); - assertTrue(m.getPayload() instanceof File); + assertThat(m.getPayload() instanceof File).isTrue(); File replyPayload = (File) m.getPayload(); - assertEquals(expectedFileContent, new String(FileCopyUtils.copyToByteArray(replyPayload))); + assertThat(new String(FileCopyUtils.copyToByteArray(replyPayload))).isEqualTo(expectedFileContent); } @@ -320,7 +315,8 @@ public class FileOutboundGatewayParserTests { */ @Test public void gatewayWithAppendNewLine() { - assertEquals(Boolean.TRUE, TestUtils.getPropertyValue(this.gatewayWithAppendNewLine, "handler.appendNewLine")); + assertThat(TestUtils.getPropertyValue(this.gatewayWithAppendNewLine, "handler.appendNewLine")) + .isEqualTo(Boolean.TRUE); } public static class FooAdvice extends AbstractRequestHandlerAdvice { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileSplitterParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileSplitterParserTests.java index bd58927461..6dcde89006 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileSplitterParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileSplitterParserTests.java @@ -16,9 +16,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.Charset; @@ -60,19 +58,19 @@ public class FileSplitterParserTests { @Test public void testComplete() { - assertFalse(TestUtils.getPropertyValue(this.splitter, "returnIterator", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(this.splitter, "markers", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(this.splitter, "markersJson", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(this.splitter, "requiresReply", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(this.splitter, "applySequence", Boolean.class)); - assertEquals(Charset.forName("UTF-8"), TestUtils.getPropertyValue(this.splitter, "charset")); - assertEquals(5L, TestUtils.getPropertyValue(this.splitter, "messagingTemplate.sendTimeout")); - assertEquals(this.out, TestUtils.getPropertyValue(this.splitter, "outputChannel")); - assertEquals(2, TestUtils.getPropertyValue(this.splitter, "order")); - assertEquals("foo", TestUtils.getPropertyValue(this.splitter, "firstLineHeaderName")); - assertEquals(this.in, TestUtils.getPropertyValue(this.fullBoat, "inputChannel")); - assertFalse(TestUtils.getPropertyValue(this.fullBoat, "autoStartup", Boolean.class)); - assertEquals(1, TestUtils.getPropertyValue(this.fullBoat, "phase")); + assertThat(TestUtils.getPropertyValue(this.splitter, "returnIterator", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(this.splitter, "markers", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(this.splitter, "markersJson", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(this.splitter, "requiresReply", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(this.splitter, "applySequence", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(this.splitter, "charset")).isEqualTo(Charset.forName("UTF-8")); + assertThat(TestUtils.getPropertyValue(this.splitter, "messagingTemplate.sendTimeout")).isEqualTo(5L); + assertThat(TestUtils.getPropertyValue(this.splitter, "outputChannel")).isEqualTo(this.out); + assertThat(TestUtils.getPropertyValue(this.splitter, "order")).isEqualTo(2); + assertThat(TestUtils.getPropertyValue(this.splitter, "firstLineHeaderName")).isEqualTo("foo"); + assertThat(TestUtils.getPropertyValue(this.fullBoat, "inputChannel")).isEqualTo(this.in); + assertThat(TestUtils.getPropertyValue(this.fullBoat, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(this.fullBoat, "phase")).isEqualTo(1); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterParserTests.java index e566bebf1a..804b02edf2 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import java.io.File; @@ -79,60 +76,60 @@ public class FileTailInboundChannelAdapterParserTests { public void testDefault() { String fileName = TestUtils.getPropertyValue(defaultAdapter, "file", File.class).getAbsolutePath(); String normalizedName = getNormalizedPath(fileName); - assertEquals("/tmp/baz", normalizedName); - assertEquals("tail -F -n 0 " + fileName, TestUtils.getPropertyValue(defaultAdapter, "command")); - assertSame(exec, TestUtils.getPropertyValue(defaultAdapter, "taskExecutor")); - assertTrue(TestUtils.getPropertyValue(defaultAdapter, "autoStartup", Boolean.class)); - assertTrue(TestUtils.getPropertyValue(defaultAdapter, "enableStatusReader", Boolean.class)); - assertEquals(123, TestUtils.getPropertyValue(defaultAdapter, "phase")); - assertSame(this.tailErrorChannel, TestUtils.getPropertyValue(defaultAdapter, "errorChannel")); + assertThat(normalizedName).isEqualTo("/tmp/baz"); + assertThat(TestUtils.getPropertyValue(defaultAdapter, "command")).isEqualTo("tail -F -n 0 " + fileName); + assertThat(TestUtils.getPropertyValue(defaultAdapter, "taskExecutor")).isSameAs(exec); + assertThat(TestUtils.getPropertyValue(defaultAdapter, "autoStartup", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(defaultAdapter, "enableStatusReader", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(defaultAdapter, "phase")).isEqualTo(123); + assertThat(TestUtils.getPropertyValue(defaultAdapter, "errorChannel")).isSameAs(this.tailErrorChannel); this.defaultAdapter.stop(); this.defaultAdapter.setOptions("-F -n 6"); this.defaultAdapter.start(); - assertEquals("tail -F -n 6 " + fileName, TestUtils.getPropertyValue(defaultAdapter, "command")); + assertThat(TestUtils.getPropertyValue(defaultAdapter, "command")).isEqualTo("tail -F -n 6 " + fileName); } @Test public void testNative() { String fileName = TestUtils.getPropertyValue(nativeAdapter, "file", File.class).getAbsolutePath(); String normalizedName = getNormalizedPath(fileName); - assertEquals("/tmp/foo", normalizedName); - assertEquals("tail -F -n 6 " + fileName, TestUtils.getPropertyValue(nativeAdapter, "command")); - assertSame(exec, TestUtils.getPropertyValue(nativeAdapter, "taskExecutor")); - assertSame(sched, TestUtils.getPropertyValue(nativeAdapter, "taskScheduler")); - assertTrue(TestUtils.getPropertyValue(nativeAdapter, "autoStartup", Boolean.class)); - assertFalse(TestUtils.getPropertyValue(nativeAdapter, "enableStatusReader", Boolean.class)); - assertEquals(123, TestUtils.getPropertyValue(nativeAdapter, "phase")); - assertEquals(456L, TestUtils.getPropertyValue(nativeAdapter, "tailAttemptsDelay")); + assertThat(normalizedName).isEqualTo("/tmp/foo"); + assertThat(TestUtils.getPropertyValue(nativeAdapter, "command")).isEqualTo("tail -F -n 6 " + fileName); + assertThat(TestUtils.getPropertyValue(nativeAdapter, "taskExecutor")).isSameAs(exec); + assertThat(TestUtils.getPropertyValue(nativeAdapter, "taskScheduler")).isSameAs(sched); + assertThat(TestUtils.getPropertyValue(nativeAdapter, "autoStartup", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(nativeAdapter, "enableStatusReader", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(nativeAdapter, "phase")).isEqualTo(123); + assertThat(TestUtils.getPropertyValue(nativeAdapter, "tailAttemptsDelay")).isEqualTo(456L); } @Test public void testApacheDefault() { String fileName = TestUtils.getPropertyValue(apacheDefault, "file", File.class).getAbsolutePath(); String normalizedName = getNormalizedPath(fileName); - assertEquals("/tmp/bar", normalizedName); - assertSame(exec, TestUtils.getPropertyValue(apacheDefault, "taskExecutor")); - assertEquals(2000L, TestUtils.getPropertyValue(apacheDefault, "pollingDelay")); - assertEquals(10000L, TestUtils.getPropertyValue(apacheDefault, "tailAttemptsDelay")); - assertEquals(10000L, TestUtils.getPropertyValue(apacheDefault, "idleEventInterval")); - assertFalse(TestUtils.getPropertyValue(apacheDefault, "autoStartup", Boolean.class)); - assertEquals(123, TestUtils.getPropertyValue(apacheDefault, "phase")); - assertEquals(Boolean.TRUE, TestUtils.getPropertyValue(apacheDefault, "end")); - assertEquals(Boolean.FALSE, TestUtils.getPropertyValue(apacheDefault, "reopen")); + assertThat(normalizedName).isEqualTo("/tmp/bar"); + assertThat(TestUtils.getPropertyValue(apacheDefault, "taskExecutor")).isSameAs(exec); + assertThat(TestUtils.getPropertyValue(apacheDefault, "pollingDelay")).isEqualTo(2000L); + assertThat(TestUtils.getPropertyValue(apacheDefault, "tailAttemptsDelay")).isEqualTo(10000L); + assertThat(TestUtils.getPropertyValue(apacheDefault, "idleEventInterval")).isEqualTo(10000L); + assertThat(TestUtils.getPropertyValue(apacheDefault, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(apacheDefault, "phase")).isEqualTo(123); + assertThat(TestUtils.getPropertyValue(apacheDefault, "end")).isEqualTo(Boolean.TRUE); + assertThat(TestUtils.getPropertyValue(apacheDefault, "reopen")).isEqualTo(Boolean.FALSE); } @Test public void testApacheEndReopen() { String fileName = TestUtils.getPropertyValue(apacheEndReopen, "file", File.class).getAbsolutePath(); String normalizedName = getNormalizedPath(fileName); - assertEquals("/tmp/qux", normalizedName); - assertSame(exec, TestUtils.getPropertyValue(apacheEndReopen, "taskExecutor")); - assertEquals(2000L, TestUtils.getPropertyValue(apacheEndReopen, "pollingDelay")); - assertEquals(10000L, TestUtils.getPropertyValue(apacheEndReopen, "tailAttemptsDelay")); - assertFalse(TestUtils.getPropertyValue(apacheEndReopen, "autoStartup", Boolean.class)); - assertEquals(123, TestUtils.getPropertyValue(apacheEndReopen, "phase")); - assertEquals(Boolean.FALSE, TestUtils.getPropertyValue(apacheEndReopen, "end")); - assertEquals(Boolean.TRUE, TestUtils.getPropertyValue(apacheEndReopen, "reopen")); + assertThat(normalizedName).isEqualTo("/tmp/qux"); + assertThat(TestUtils.getPropertyValue(apacheEndReopen, "taskExecutor")).isSameAs(exec); + assertThat(TestUtils.getPropertyValue(apacheEndReopen, "pollingDelay")).isEqualTo(2000L); + assertThat(TestUtils.getPropertyValue(apacheEndReopen, "tailAttemptsDelay")).isEqualTo(10000L); + assertThat(TestUtils.getPropertyValue(apacheEndReopen, "autoStartup", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(apacheEndReopen, "phase")).isEqualTo(123); + assertThat(TestUtils.getPropertyValue(apacheEndReopen, "end")).isEqualTo(Boolean.FALSE); + assertThat(TestUtils.getPropertyValue(apacheEndReopen, "reopen")).isEqualTo(Boolean.TRUE); } /** diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java index addd4c2e8f..489c9086a0 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -54,7 +54,7 @@ public class FileToStringTransformerParserTests { FileToStringTransformer transformer = (FileToStringTransformer) handlerAccessor.getPropertyValue("transformer"); DirectFieldAccessor transformerAccessor = new DirectFieldAccessor(transformer); - assertEquals(Boolean.TRUE, transformerAccessor.getPropertyValue("deleteFiles")); + assertThat(transformerAccessor.getPropertyValue("deleteFiles")).isEqualTo(Boolean.TRUE); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/InboundAdapterWithLockersTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/InboundAdapterWithLockersTests.java index 44c8b55a84..dcd47cf2b6 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/InboundAdapterWithLockersTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/InboundAdapterWithLockersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -42,13 +41,13 @@ public class InboundAdapterWithLockersTests { @Test public void testAdaptersWithLockers() { - assertEquals(context.getBean("locker"), - TestUtils.getPropertyValue(context.getBean("inputWithLockerA"), "source.scanner.locker")); - assertEquals(context.getBean("locker"), - TestUtils.getPropertyValue(context.getBean("inputWithLockerB"), "source.scanner.locker")); - assertTrue(TestUtils.getPropertyValue(context.getBean("inputWithLockerC"), "source.scanner.locker") - instanceof NioFileLocker); - assertTrue(TestUtils.getPropertyValue(context.getBean("inputWithLockerD"), "source.scanner.locker") - instanceof NioFileLocker); + assertThat(TestUtils.getPropertyValue(context.getBean("inputWithLockerA"), "source.scanner.locker")) + .isEqualTo(context.getBean("locker")); + assertThat(TestUtils.getPropertyValue(context.getBean("inputWithLockerB"), "source.scanner.locker")) + .isEqualTo(context.getBean("locker")); + assertThat(TestUtils.getPropertyValue(context.getBean("inputWithLockerC"), "source.scanner.locker") + instanceof NioFileLocker).isTrue(); + assertThat(TestUtils.getPropertyValue(context.getBean("inputWithLockerD"), "source.scanner.locker") + instanceof NioFileLocker).isTrue(); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/dsl/FileTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/dsl/FileTests.java index a86e2e6d11..0da1850a4e 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/dsl/FileTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/dsl/FileTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,8 @@ package org.springframework.integration.file.dsl; -import static org.hamcrest.Matchers.endsWith; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.File; import java.io.FileOutputStream; @@ -157,8 +149,8 @@ public class FileTests { fail("NullPointerException expected"); } catch (Exception e) { - assertThat(e, instanceOf(MessageHandlingException.class)); - assertThat(e.getCause(), instanceOf(NullPointerException.class)); + assertThat(e).isInstanceOf(MessageHandlingException.class); + assertThat(e.getCause()).isInstanceOf(NullPointerException.class); } DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); fileNameGenerator.setBeanFactory(this.beanFactory); @@ -170,15 +162,15 @@ public class FileTests { } } DirectFieldAccessor dfa = new DirectFieldAccessor(targetFileWritingMessageHandler); - assertEquals(Boolean.FALSE, dfa.getPropertyValue("flushWhenIdle")); - assertEquals(60000L, dfa.getPropertyValue("flushInterval")); + assertThat(dfa.getPropertyValue("flushWhenIdle")).isEqualTo(Boolean.FALSE); + assertThat(dfa.getPropertyValue("flushInterval")).isEqualTo(60000L); dfa.setPropertyValue("fileNameGenerator", fileNameGenerator); this.fileFlow1Input.send(message); - assertTrue(new File(tmpDir.getRoot(), "foo").exists()); + assertThat(new File(tmpDir.getRoot(), "foo").exists()).isTrue(); this.fileTriggerFlowInput.send(new GenericMessage<>("trigger")); - assertTrue(this.flushPredicateCalled.await(10, TimeUnit.SECONDS)); + assertThat(this.flushPredicateCalled.await(10, TimeUnit.SECONDS)).isTrue(); } @Test @@ -190,10 +182,10 @@ public class FileTests { this.tailer.start(); for (int i = 0; i < 50; i++) { Message message = this.tailChannel.receive(5000); - assertNotNull(message); - assertEquals("hello " + i, message.getPayload()); + assertThat(message).isNotNull(); + assertThat(message.getPayload()).isEqualTo("hello " + i); } - assertNull(this.tailChannel.receive(1)); + assertThat(this.tailChannel.receive(1)).isNull(); this.controlBus.send("@tailer.stop()"); file.close(); @@ -218,18 +210,18 @@ public class FileTests { } Message message = fileReadingResultChannel.receive(60000); - assertNotNull(message); + assertThat(message).isNotNull(); Object payload = message.getPayload(); - assertThat(payload, instanceOf(List.class)); + assertThat(payload).isInstanceOf(List.class); @SuppressWarnings("unchecked") List result = (List) payload; - assertEquals(25, result.size()); - result.forEach(s -> assertTrue(evens.contains(Integer.parseInt(s)))); + assertThat(result.size()).isEqualTo(25); + result.forEach(s -> assertThat(evens.contains(Integer.parseInt(s))).isTrue()); new File(tmpDir.getRoot(), "a.sitest").createNewFile(); Message receive = this.filePollingErrorChannel.receive(60000); - assertNotNull(receive); - assertThat(receive, instanceOf(ErrorMessage.class)); + assertThat(receive).isNotNull(); + assertThat(receive).isInstanceOf(ErrorMessage.class); } @Test @@ -237,15 +229,15 @@ public class FileTests { String payload = "Spring Integration"; this.fileWritingInput.send(new GenericMessage<>(payload)); Message receive = this.fileWritingResultChannel.receive(1000); - assertNotNull(receive); - assertThat(receive.getPayload(), instanceOf(File.class)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isInstanceOf(File.class); File resultFile = (File) receive.getPayload(); - assertThat(resultFile.getAbsolutePath(), - endsWith(TestUtils.applySystemFileSeparator("fileWritingFlow/foo.write"))); + assertThat(resultFile.getAbsolutePath()) + .endsWith(TestUtils.applySystemFileSeparator("fileWritingFlow/foo.write")); String fileContent = FileCopyUtils.copyToString(new FileReader(resultFile)); - assertEquals(payload, fileContent); + assertThat(fileContent).isEqualTo(payload); if (FileUtils.IS_POSIX) { - assertThat(java.nio.file.Files.getPosixFilePermissions(resultFile.toPath()).size(), equalTo(9)); + assertThat(java.nio.file.Files.getPosixFilePermissions(resultFile.toPath()).size()).isEqualTo(9); } } @@ -261,19 +253,19 @@ public class FileTests { file.close(); Message receive = this.fileSplittingResultChannel.receive(10000); - assertNotNull(receive); - assertThat(receive.getPayload(), instanceOf(FileSplitter.FileMarker.class)); // FileMarker.Mark.START - assertEquals(0, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); // FileMarker.Mark.START + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(0); receive = this.fileSplittingResultChannel.receive(10000); - assertNotNull(receive); //HelloWorld + assertThat(receive).isNotNull(); //HelloWorld receive = this.fileSplittingResultChannel.receive(10000); - assertNotNull(receive); //äöüß + assertThat(receive).isNotNull(); //äöüß receive = this.fileSplittingResultChannel.receive(10000); - assertNotNull(receive); - assertThat(receive.getPayload(), instanceOf(FileSplitter.FileMarker.class)); // FileMarker.Mark.END - assertNull(this.fileSplittingResultChannel.receive(1)); + assertThat(receive).isNotNull(); + assertThat(receive.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); // FileMarker.Mark.END + assertThat(this.fileSplittingResultChannel.receive(1)).isNull(); - assertEquals(StandardCharsets.US_ASCII, TestUtils.getPropertyValue(this.fileSplitter, "charset")); + assertThat(TestUtils.getPropertyValue(this.fileSplitter, "charset")).isEqualTo(StandardCharsets.US_ASCII); } @Autowired @@ -301,13 +293,13 @@ public class FileTests { Set payloads = new TreeSet<>(); Message receive = this.dynamicAdaptersResult.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); payloads.add((String) receive.getPayload()); receive = this.dynamicAdaptersResult.receive(10000); - assertNotNull(receive); + assertThat(receive).isNotNull(); payloads.add((String) receive.getPayload()); - assertArrayEquals(new String[] { "bar", "foo" }, payloads.toArray()); + assertThat(payloads.toArray()).isEqualTo(new String[] { "bar", "foo" }); } @MessagingGateway(defaultRequestChannel = "controlBus.input") diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AbstractMarkerFilePresentFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AbstractMarkerFilePresentFileListFilterTests.java index 85a230d36a..138a736efc 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AbstractMarkerFilePresentFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AbstractMarkerFilePresentFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.file.filters; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.List; @@ -38,8 +37,8 @@ public class AbstractMarkerFilePresentFileListFilterTests { StringMarkerFilePresentFileListFilter filter = new StringMarkerFilePresentFileListFilter( new StringSimplePatternFilter("*.txt")); List filtered = filter.filterFiles(new String[] { "foo.txt", "foo.txt.complete", "bar.txt" }); - assertThat(filtered.size(), equalTo(1)); - assertThat(filtered.get(0), equalTo("foo.txt")); + assertThat(filtered.size()).isEqualTo(1); + assertThat(filtered.get(0)).isEqualTo("foo.txt"); } @Test @@ -47,8 +46,8 @@ public class AbstractMarkerFilePresentFileListFilterTests { StringMarkerFilePresentFileListFilter filter = new StringMarkerFilePresentFileListFilter( new StringSimplePatternFilter("*.txt"), ".done"); List filtered = filter.filterFiles(new String[] { "foo.txt", "foo.txt.done", "bar.txt", "baz.txt" }); - assertThat(filtered.size(), equalTo(1)); - assertThat(filtered.get(0), equalTo("foo.txt")); + assertThat(filtered.size()).isEqualTo(1); + assertThat(filtered.get(0)).isEqualTo("foo.txt"); } @Test @@ -56,10 +55,10 @@ public class AbstractMarkerFilePresentFileListFilterTests { StringMarkerFilePresentFileListFilter filter = new StringMarkerFilePresentFileListFilter( new StringSimplePatternFilter("*.txt"), s -> "allFilesDone"); List filtered = filter.filterFiles(new String[] { "foo.txt", "bar.txt" }); - assertThat(filtered.size(), equalTo(0)); + assertThat(filtered.size()).isEqualTo(0); filtered = filter.filterFiles(new String[] { "foo.txt", "bar.txt", "allFilesDone" }); - assertThat(filtered.get(0), equalTo("foo.txt")); - assertThat(filtered.get(1), equalTo("bar.txt")); + assertThat(filtered.get(0)).isEqualTo("foo.txt"); + assertThat(filtered.get(1)).isEqualTo("bar.txt"); } @Test @@ -72,9 +71,9 @@ public class AbstractMarkerFilePresentFileListFilterTests { StringMarkerFilePresentFileListFilter filter = new StringMarkerFilePresentFileListFilter(map); List filtered = filter .filterFiles(new String[] { "foo.txt", "foo.txt.done", "bar.xml", "bar.xml.complete", "baz.txt" }); - assertThat(filtered.size(), equalTo(2)); - assertThat(filtered.get(0), equalTo("foo.txt")); - assertThat(filtered.get(1), equalTo("bar.xml")); + assertThat(filtered.size()).isEqualTo(2); + assertThat(filtered.get(0)).isEqualTo("foo.txt"); + assertThat(filtered.get(1)).isEqualTo("bar.xml"); } private static class StringSimplePatternFilter extends AbstractSimplePatternFileListFilter { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AcceptOnceFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AcceptOnceFileListFilterTests.java index 5105d96cb1..46f984ff2d 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AcceptOnceFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/AcceptOnceFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2019 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,12 +16,7 @@ package org.springframework.integration.file.filters; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.util.Arrays; import java.util.Collections; @@ -36,6 +31,8 @@ import org.springframework.util.StopWatch; /** * @author Gary Russell + * @author Artem Bilan + * * @since 4.0.4 * */ @@ -46,58 +43,57 @@ public class AcceptOnceFileListFilterTests { public void testPerformance_INT3572() { StopWatch watch = new StopWatch(); watch.start(); - AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter(); + AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter<>(); for (int i = 0; i < 100000; i++) { filter.accept("" + i); } watch.stop(); - assertTrue(watch.getTotalTimeMillis() < 5000); + assertThat(watch.getTotalTimeMillis()).isLessThan(5000); } @Test @SuppressWarnings("unchecked") public void testCapacity() { - AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter(2); - assertTrue(filter.accept("foo")); - assertTrue(filter.accept("bar")); - assertFalse(filter.accept("foo")); - assertTrue(filter.accept("baz")); - assertTrue(filter.accept("foo")); + AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter<>(2); + assertThat(filter.accept("foo")).isTrue(); + assertThat(filter.accept("bar")).isTrue(); + assertThat(filter.accept("foo")).isFalse(); + assertThat(filter.accept("baz")).isTrue(); + assertThat(filter.accept("foo")).isTrue(); Queue seen = TestUtils.getPropertyValue(filter, "seen", Queue.class); - assertEquals(2, seen.size()); + assertThat(seen.size()).isEqualTo(2); Set seenSet = TestUtils.getPropertyValue(filter, "seenSet", Set.class); - assertEquals(2, seenSet.size()); - assertThat(seen, contains("baz", "foo")); - assertThat(seenSet, containsInAnyOrder("foo", "baz")); + assertThat(seenSet.size()).isEqualTo(2); + assertThat(seen).containsExactly("baz", "foo"); + assertThat(seenSet).contains("foo", "baz"); } @Test public void testRollback() { - AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter(); + AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter<>(); doTestRollback(filter); } @Test public void testRollbackComposite() { - AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter(); - CompositeFileListFilter composite = new CompositeFileListFilter( - Collections.singletonList(filter)); + AcceptOnceFileListFilter filter = new AcceptOnceFileListFilter<>(); + CompositeFileListFilter composite = new CompositeFileListFilter<>(Collections.singletonList(filter)); doTestRollback(composite); } protected void doTestRollback(ReversibleFileListFilter filter) { - String[] files = new String[] {"foo", "bar", "baz"}; + String[] files = new String[] { "foo", "bar", "baz" }; List passed = filter.filterFiles(files); - assertTrue(Arrays.equals(files, passed.toArray())); + assertThat(Arrays.equals(files, passed.toArray())).isTrue(); List now = filter.filterFiles(files); - assertEquals(0, now.size()); + assertThat(now.size()).isEqualTo(0); filter.rollback(passed.get(1), passed); now = filter.filterFiles(files); - assertEquals(2, now.size()); - assertEquals("bar", now.get(0)); - assertEquals("baz", now.get(1)); + assertThat(now.size()).isEqualTo(2); + assertThat(now.get(0)).isEqualTo("bar"); + assertThat(now.get(1)).isEqualTo("baz"); now = filter.filterFiles(files); - assertEquals(0, now.size()); + assertThat(now.size()).isEqualTo(0); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/ChainFileListFilterIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/ChainFileListFilterIntegrationTests.java index 1a7a28a97b..0957ad5e8f 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/ChainFileListFilterIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/ChainFileListFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.file.filters; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; @@ -44,7 +44,7 @@ public class ChainFileListFilterIntegrationTests { try (ChainFileListFilter chain = new ChainFileListFilter<>()) { chain.addFilter(new LastModifiedFileListFilter()); List result = chain.filterFiles(noFiles); - assertEquals(0, result.size()); + assertThat(result.size()).isEqualTo(0); } } @@ -53,7 +53,7 @@ public class ChainFileListFilterIntegrationTests { try (ChainFileListFilter chain = new ChainFileListFilter<>()) { chain.addFilter(new SimplePatternFileListFilter(PATTERN_ANY_TEXT_FILES)); List result = chain.filterFiles(oneFile); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); } } @@ -62,7 +62,7 @@ public class ChainFileListFilterIntegrationTests { try (ChainFileListFilter chain = new ChainFileListFilter<>()) { chain.addFilter(new LastModifiedFileListFilter()); List result = chain.filterFiles(oneFile); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); } } @@ -72,7 +72,7 @@ public class ChainFileListFilterIntegrationTests { chain.addFilter(new SimplePatternFileListFilter(PATTERN_ANY_TEXT_FILES)); chain.addFilter(new LastModifiedFileListFilter()); List result = chain.filterFiles(oneFile); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); } } @@ -82,7 +82,7 @@ public class ChainFileListFilterIntegrationTests { chain.addFilter(new LastModifiedFileListFilter()); chain.addFilter(new SimplePatternFileListFilter(PATTERN_ANY_TEXT_FILES)); List result = chain.filterFiles(oneFile); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); } } @@ -91,7 +91,7 @@ public class ChainFileListFilterIntegrationTests { public void initializeFilterByConstructor() throws IOException { try (ChainFileListFilter chain = new ChainFileListFilter<>(Arrays.asList(new SimplePatternFileListFilter(PATTERN_ANY_TEXT_FILES)))) { List result = chain.filterFiles(oneFile); - assertEquals(1, result.size()); + assertThat(result.size()).isEqualTo(1); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/CompositeFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/CompositeFileListFilterTests.java index 4e6dd01188..7e61be2119 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/CompositeFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/CompositeFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,15 +16,12 @@ package org.springframework.integration.file.filters; -import static org.hamcrest.Matchers.arrayWithSize; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.mockito.hamcrest.MockitoHamcrest.argThat; import java.io.File; import java.util.ArrayList; @@ -51,13 +48,13 @@ public class CompositeFileListFilterTests { @Test public void forwardedToFilters() throws Exception { - CompositeFileListFilter compositeFileFilter = new CompositeFileListFilter(); + CompositeFileListFilter compositeFileFilter = new CompositeFileListFilter<>(); compositeFileFilter.addFilter(fileFilterMock1); compositeFileFilter.addFilter(fileFilterMock2); List returnedFiles = Collections.singletonList(fileMock); when(fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(returnedFiles); when(fileFilterMock2.filterFiles(isA(File[].class))).thenReturn(returnedFiles); - assertEquals(returnedFiles, compositeFileFilter.filterFiles(new File[] { fileMock })); + assertThat(compositeFileFilter.filterFiles(new File[] { fileMock })).isEqualTo(returnedFiles); verify(fileFilterMock1).filterFiles(isA(File[].class)); verify(fileFilterMock2).filterFiles(isA(File[].class)); compositeFileFilter.close(); @@ -65,13 +62,13 @@ public class CompositeFileListFilterTests { @Test public void forwardedToAddedFilters() throws Exception { - CompositeFileListFilter compositeFileFilter = new CompositeFileListFilter(); + CompositeFileListFilter compositeFileFilter = new CompositeFileListFilter<>(); compositeFileFilter.addFilter(fileFilterMock1); compositeFileFilter.addFilter(fileFilterMock2); List returnedFiles = Collections.singletonList(fileMock); when(fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(returnedFiles); when(fileFilterMock2.filterFiles(isA(File[].class))).thenReturn(returnedFiles); - assertEquals(returnedFiles, compositeFileFilter.filterFiles(new File[] { fileMock })); + assertThat(compositeFileFilter.filterFiles(new File[] { fileMock })).isEqualTo(returnedFiles); verify(fileFilterMock1).filterFiles(isA(File[].class)); verify(fileFilterMock2).filterFiles(isA(File[].class)); compositeFileFilter.close(); @@ -79,13 +76,13 @@ public class CompositeFileListFilterTests { @Test public void negative() throws Exception { - CompositeFileListFilter compositeFileFilter = new CompositeFileListFilter(); + CompositeFileListFilter compositeFileFilter = new CompositeFileListFilter<>(); compositeFileFilter.addFilter(fileFilterMock1); compositeFileFilter.addFilter(fileFilterMock2); - when(fileFilterMock2.filterFiles(isA(File[].class))).thenReturn(new ArrayList()); - when(fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(new ArrayList()); - assertTrue(compositeFileFilter.filterFiles(new File[] { fileMock }).isEmpty()); + when(fileFilterMock2.filterFiles(isA(File[].class))).thenReturn(new ArrayList<>()); + when(fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(new ArrayList<>()); + assertThat(compositeFileFilter.filterFiles(new File[] { fileMock }).isEmpty()).isTrue(); compositeFileFilter.close(); } @@ -96,9 +93,9 @@ public class CompositeFileListFilterTests { compositeFileFilter.addFilter(this.fileFilterMock2); List noFiles = new ArrayList<>(); when(this.fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(noFiles); - assertEquals(noFiles, compositeFileFilter.filterFiles(new File[] { this.fileMock })); + assertThat(compositeFileFilter.filterFiles(new File[] { this.fileMock })).isEqualTo(noFiles); - verify(fileFilterMock1).filterFiles(argThat(arrayWithSize(1))); + verify(fileFilterMock1).filterFiles(isA(File[].class)); verify(fileFilterMock2, never()).filterFiles(isA(File[].class)); compositeFileFilter.close(); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/FileSystemMarkerFilePresentFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/FileSystemMarkerFilePresentFileListFilterTests.java index 804566154a..2a7780af06 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/FileSystemMarkerFilePresentFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/FileSystemMarkerFilePresentFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 the original author or authors. + * Copyright 2017-2019 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,7 @@ package org.springframework.integration.file.filters; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.List; @@ -42,12 +41,12 @@ public class FileSystemMarkerFilePresentFileListFilterTests { new SimplePatternFileListFilter("*.txt")); File foo = this.folder.newFile("foo.txt"); foo.createNewFile(); - assertThat(filter.filterFiles(new File[] { foo }).size(), equalTo(0)); + assertThat(filter.filterFiles(new File[] { foo }).size()).isEqualTo(0); File complete = this.folder.newFile("foo.txt.complete"); complete.createNewFile(); List filtered = filter.filterFiles(new File[] { foo, complete }); - assertThat(filtered.size(), equalTo(1)); - assertThat(filtered.get(0).getName(), equalTo("foo.txt")); + assertThat(filtered.size()).isEqualTo(1); + assertThat(filtered.get(0).getName()).isEqualTo("foo.txt"); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/LastModifiedFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/LastModifiedFileListFilterTests.java index a94a76507d..e91f99f568 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/LastModifiedFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/LastModifiedFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 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,7 @@ package org.springframework.integration.file.filters; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileOutputStream; @@ -45,10 +45,10 @@ public class LastModifiedFileListFilterTests { FileOutputStream fileOutputStream = new FileOutputStream(foo); fileOutputStream.write("x".getBytes()); fileOutputStream.close(); - assertEquals(0, filter.filterFiles(new File[] { foo }).size()); + assertThat(filter.filterFiles(new File[] { foo }).size()).isEqualTo(0); // Make a file as of yesterday's foo.setLastModified(System.currentTimeMillis() - 1000 * 60 * 60 * 24); - assertEquals(1, filter.filterFiles(new File[] { foo }).size()); + assertThat(filter.filterFiles(new File[] { foo }).size()).isEqualTo(1); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterExternalStoreTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterExternalStoreTests.java index 2b37cf07ee..b9e445ef04 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterExternalStoreTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterExternalStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2018 the original author or authors. + * Copyright 2014-2019 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,7 @@ package org.springframework.integration.file.filters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.util.List; @@ -96,8 +95,8 @@ public class PersistentAcceptOnceFileListFilterExternalStoreTests extends RedisA List> metaData = new JdbcTemplate(dataSource) .queryForList("SELECT * FROM INT_METADATA_STORE"); - assertEquals(1, metaData.size()); - assertEquals("43", metaData.get(0).get("METADATA_VALUE")); + assertThat(metaData.size()).isEqualTo(1); + assertThat(metaData.get(0).get("METADATA_VALUE")).isEqualTo("43"); } finally { dataSource.shutdown(); @@ -128,26 +127,26 @@ public class PersistentAcceptOnceFileListFilterExternalStoreTests extends RedisA final FileSystemPersistentAcceptOnceFileListFilter filter = new FileSystemPersistentAcceptOnceFileListFilter(store, "foo:"); final File file = File.createTempFile("foo", ".txt"); - assertEquals(1, filter.filterFiles(new File[] { file }).size()); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(1); String ts = store.get("foo:" + file.getAbsolutePath()); - assertEquals(String.valueOf(file.lastModified()), ts); - assertEquals(0, filter.filterFiles(new File[] { file }).size()); + assertThat(ts).isEqualTo(String.valueOf(file.lastModified())); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(0); file.setLastModified(file.lastModified() + 5000L); - assertEquals(1, filter.filterFiles(new File[] { file }).size()); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(1); ts = store.get("foo:" + file.getAbsolutePath()); - assertEquals(String.valueOf(file.lastModified()), ts); - assertEquals(0, filter.filterFiles(new File[] { file }).size()); + assertThat(ts).isEqualTo(String.valueOf(file.lastModified())); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(0); suspend.set(true); file.setLastModified(file.lastModified() + 5000L); Future result = Executors.newSingleThreadExecutor() .submit(() -> filter.filterFiles(new File[] { file }).size()); - assertTrue(latch2.await(10, TimeUnit.SECONDS)); + assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); store.put("foo:" + file.getAbsolutePath(), "43"); latch1.countDown(); Integer theResult = result.get(10, TimeUnit.SECONDS); - assertEquals(Integer.valueOf(0), theResult); // lost the race, key changed + assertThat(theResult).isEqualTo(Integer.valueOf(0)); // lost the race, key changed file.delete(); filter.close(); diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterTests.java index 83bc9e5caf..e1538b68e0 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/PersistentAcceptOnceFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 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,7 @@ package org.springframework.integration.file.filters; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.Closeable; import java.io.File; @@ -71,15 +69,15 @@ public class PersistentAcceptOnceFileListFilterTests extends AcceptOnceFileListF final FileSystemPersistentAcceptOnceFileListFilter filter = new FileSystemPersistentAcceptOnceFileListFilter(store, "foo:"); final File file = File.createTempFile("foo", ".txt"); - assertEquals(1, filter.filterFiles(new File[] {file}).size()); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(1); String ts = store.get("foo:" + file.getAbsolutePath()); - assertEquals(String.valueOf(file.lastModified()), ts); - assertEquals(0, filter.filterFiles(new File[] {file}).size()); + assertThat(ts).isEqualTo(String.valueOf(file.lastModified())); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(0); file.setLastModified(file.lastModified() + 5000L); - assertEquals(1, filter.filterFiles(new File[] {file}).size()); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(1); ts = store.get("foo:" + file.getAbsolutePath()); - assertEquals(String.valueOf(file.lastModified()), ts); - assertEquals(0, filter.filterFiles(new File[] {file}).size()); + assertThat(ts).isEqualTo(String.valueOf(file.lastModified())); + assertThat(filter.filterFiles(new File[] { file }).size()).isEqualTo(0); suspend.set(true); file.setLastModified(file.lastModified() + 5000L); @@ -91,11 +89,11 @@ public class PersistentAcceptOnceFileListFilterTests extends AcceptOnceFileListF return filter.filterFiles(new File[] {file}).size(); } }); - assertTrue(latch2.await(10, TimeUnit.SECONDS)); + assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); store.put("foo:" + file.getAbsolutePath(), "43"); latch1.countDown(); Integer theResult = result.get(10, TimeUnit.SECONDS); - assertEquals(Integer.valueOf(0), theResult); // lost the race, key changed + assertThat(theResult).isEqualTo(Integer.valueOf(0)); // lost the race, key changed file.delete(); filter.close(); @@ -126,21 +124,21 @@ public class PersistentAcceptOnceFileListFilterTests extends AcceptOnceFileListF new SimpleMetadataStore(), "rollback:"); File[] files = new File[] {new File("foo"), new File("bar"), new File("baz")}; List passed = filter.filterFiles(files); - assertEquals(0, passed.size()); + assertThat(passed.size()).isEqualTo(0); for (File file : files) { file.createNewFile(); } passed = filter.filterFiles(files); - assertTrue(Arrays.equals(files, passed.toArray())); + assertThat(Arrays.equals(files, passed.toArray())).isTrue(); List now = filter.filterFiles(files); - assertEquals(0, now.size()); + assertThat(now.size()).isEqualTo(0); filter.rollback(passed.get(1), passed); now = filter.filterFiles(files); - assertEquals(2, now.size()); - assertEquals("bar", now.get(0).getName()); - assertEquals("baz", now.get(1).getName()); + assertThat(now.size()).isEqualTo(2); + assertThat(now.get(0).getName()).isEqualTo("bar"); + assertThat(now.get(1).getName()).isEqualTo("baz"); now = filter.filterFiles(files); - assertEquals(0, now.size()); + assertThat(now.size()).isEqualTo(0); filter.close(); for (File file : files) { file.delete(); @@ -180,30 +178,30 @@ public class PersistentAcceptOnceFileListFilterTests extends AcceptOnceFileListF final File file = File.createTempFile("foo", ".txt"); File[] files = new File[] { file }; List passed = filter.filterFiles(files); - assertTrue(Arrays.equals(files, passed.toArray())); + assertThat(Arrays.equals(files, passed.toArray())).isTrue(); filter.rollback(passed.get(0), passed); - assertEquals(0, flushes.get()); + assertThat(flushes.get()).isEqualTo(0); filter.setFlushOnUpdate(true); passed = filter.filterFiles(files); - assertTrue(Arrays.equals(files, passed.toArray())); - assertEquals(1, flushes.get()); + assertThat(Arrays.equals(files, passed.toArray())).isTrue(); + assertThat(flushes.get()).isEqualTo(1); filter.rollback(passed.get(0), passed); - assertEquals(2, flushes.get()); + assertThat(flushes.get()).isEqualTo(2); passed = filter.filterFiles(files); - assertTrue(Arrays.equals(files, passed.toArray())); - assertEquals(3, flushes.get()); + assertThat(Arrays.equals(files, passed.toArray())).isTrue(); + assertThat(flushes.get()).isEqualTo(3); passed = filter.filterFiles(files); - assertEquals(0, passed.size()); - assertEquals(3, flushes.get()); - assertFalse(replaced.get()); + assertThat(passed.size()).isEqualTo(0); + assertThat(flushes.get()).isEqualTo(3); + assertThat(replaced.get()).isFalse(); store.put(prefix + file.getAbsolutePath(), "1"); passed = filter.filterFiles(files); - assertTrue(Arrays.equals(files, passed.toArray())); - assertEquals(4, flushes.get()); - assertTrue(replaced.get()); + assertThat(Arrays.equals(files, passed.toArray())).isTrue(); + assertThat(flushes.get()).isEqualTo(4); + assertThat(replaced.get()).isTrue(); file.delete(); filter.close(); - assertEquals(5, flushes.get()); + assertThat(flushes.get()).isEqualTo(5); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/SimplePatternFileListFilterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/SimplePatternFileListFilterTests.java index dc609752b3..c208d3e444 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/filters/SimplePatternFileListFilterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/filters/SimplePatternFileListFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.filters; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -32,17 +31,17 @@ public class SimplePatternFileListFilterTests { @Test public void shouldMatchExactly() { - assertThat(new SimplePatternFileListFilter("bar").accept(new File("bar")), is(true)); + assertThat(new SimplePatternFileListFilter("bar").accept(new File("bar"))).isTrue(); } @Test public void shouldMatchQuestionMark() { - assertThat(new SimplePatternFileListFilter("*bar").accept(new File("bar")), is(true)); + assertThat(new SimplePatternFileListFilter("*bar").accept(new File("bar"))).isTrue(); } @Test public void shouldMatchWildcard() { - assertThat(new SimplePatternFileListFilter("ba?").accept(new File("bar")), is(true)); + assertThat(new SimplePatternFileListFilter("ba?").accept(new File("bar"))).isTrue(); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingNamespaceTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingNamespaceTests.java index c9583d8679..c0e173a067 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingNamespaceTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingNamespaceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.locking; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -68,8 +66,8 @@ public class FileLockingNamespaceTests { @Test public void shouldSetCustomLockerProperly() { - assertThat(extractFromScanner("locker", customLockingSource), is(instanceOf(StubLocker.class))); - assertThat(extractFromScanner("filter", customLockingSource), is(instanceOf(CompositeFileListFilter.class))); + assertThat(extractFromScanner("locker", customLockingSource)).isInstanceOf(StubLocker.class); + assertThat(extractFromScanner("filter", customLockingSource)).isInstanceOf(CompositeFileListFilter.class); } private Object extractFromScanner(String propertyName, FileReadingMessageSource source) { @@ -78,8 +76,8 @@ public class FileLockingNamespaceTests { @Test public void shouldSetNioLockerProperly() { - assertThat(extractFromScanner("locker", nioLockingSource), is(instanceOf(NioFileLocker.class))); - assertThat(extractFromScanner("filter", nioLockingSource), is(instanceOf(CompositeFileListFilter.class))); + assertThat(extractFromScanner("locker", nioLockingSource)).isInstanceOf(NioFileLocker.class); + assertThat(extractFromScanner("filter", nioLockingSource)).isInstanceOf(CompositeFileListFilter.class); } public static class StubLocker extends AbstractFileLockerFilter { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests.java index c838bc8208..af9647b598 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/FileLockingWithMultipleSourcesIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.locking; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.springframework.integration.test.matcher.PayloadMatcher.hasPayload; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; @@ -31,6 +29,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.file.FileReadingMessageSource; +import org.springframework.messaging.Message; import org.springframework.test.context.ContextConfiguration; /** @@ -72,8 +71,11 @@ public class FileLockingWithMultipleSourcesIntegrationTests { public void filePickedUpOnceWithDistinctFilters() throws IOException { File testFile = new File(workdir, "test"); testFile.createNewFile(); - assertThat(fileSource1.receive(), hasPayload(testFile)); - assertThat(fileSource2.receive(), nullValue()); + assertThat(this.fileSource1.receive()) + .isNotNull() + .extracting(Message::getPayload) + .isEqualTo(testFile); + assertThat(this.fileSource2.receive()).isNull(); FileChannelCache.closeChannelFor(testFile); } @@ -81,8 +83,14 @@ public class FileLockingWithMultipleSourcesIntegrationTests { public void filePickedUpTwiceWithSharedFilter() throws Exception { File testFile = new File(workdir, "test"); testFile.createNewFile(); - assertThat(fileSource1.receive(), hasPayload(testFile)); - assertThat(fileSource3.receive(), hasPayload(testFile)); + assertThat(this.fileSource1.receive()) + .isNotNull() + .extracting(Message::getPayload) + .isEqualTo(testFile); + assertThat(this.fileSource3.receive()) + .isNotNull() + .extracting(Message::getPayload) + .isEqualTo(testFile); FileChannelCache.closeChannelFor(testFile); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java index 3aa230cd64..9ecaab197e 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.locking; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.IOException; @@ -52,9 +51,9 @@ public class NioFileLockerTests { NioFileLocker filter = new NioFileLocker(); File testFile = new File(workdir, "test0"); testFile.createNewFile(); - assertThat(filter.filterFiles(workdir.listFiles()).get(0), is(testFile)); + assertThat(filter.filterFiles(workdir.listFiles()).get(0)).isEqualTo(testFile); filter.lock(testFile); - assertThat(filter.filterFiles(workdir.listFiles()).get(0), is(testFile)); + assertThat(filter.filterFiles(workdir.listFiles()).get(0)).isEqualTo(testFile); } @Test @@ -63,9 +62,9 @@ public class NioFileLockerTests { FileListFilter filter2 = new NioFileLocker(); File testFile = new File(workdir, "test1"); testFile.createNewFile(); - assertThat(filter1.filterFiles(workdir.listFiles()).get(0), is(testFile)); + assertThat(filter1.filterFiles(workdir.listFiles()).get(0)).isEqualTo(testFile); filter1.lock(testFile); - assertThat(filter2.filterFiles(workdir.listFiles()), is((List) new ArrayList())); + assertThat(filter2.filterFiles(workdir.listFiles())).isEqualTo((List) new ArrayList()); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java index eb29120c10..7783eecbb0 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/RemoteFileTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2016 the original author or authors. + * Copyright 2015-2019 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,10 @@ package org.springframework.integration.file.remote; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -26,12 +28,10 @@ import static org.mockito.Mockito.when; import java.io.File; import java.io.InputStream; -import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; -import org.mockito.Mockito; import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.common.LiteralExpression; @@ -43,6 +43,8 @@ import org.springframework.messaging.support.GenericMessage; /** * @author Gary Russell + * @author Artem Bilan + * * @since 4.1.7 * */ @@ -61,7 +63,7 @@ public class RemoteFileTemplateTests { @Before public void setUp() throws Exception { SessionFactory sessionFactory = mock(SessionFactory.class); - this.template = new RemoteFileTemplate(sessionFactory); + this.template = new RemoteFileTemplate<>(sessionFactory); this.template.setRemoteDirectoryExpression(new LiteralExpression("/foo")); this.template.setBeanFactory(mock(BeanFactory.class)); this.template.afterPropertiesSet(); @@ -72,49 +74,49 @@ public class RemoteFileTemplateTests { @Test public void testReplace() throws Exception { - this.template.send(new GenericMessage(this.file), FileExistsMode.REPLACE); - verify(this.session).write(Mockito.any(InputStream.class), Mockito.anyString()); + this.template.send(new GenericMessage<>(this.file), FileExistsMode.REPLACE); + verify(this.session).write(any(InputStream.class), anyString()); } @Test public void testAppend() throws Exception { this.template.setUseTemporaryFileName(false); - this.template.send(new GenericMessage(this.file), FileExistsMode.APPEND); - verify(this.session).append(Mockito.any(InputStream.class), Mockito.anyString()); + this.template.send(new GenericMessage<>(this.file), FileExistsMode.APPEND); + verify(this.session).append(any(InputStream.class), anyString()); } @Test public void testFailExists() throws Exception { - when(session.exists(Mockito.anyString())).thenReturn(true); + when(session.exists(anyString())).thenReturn(true); try { - this.template.send(new GenericMessage(this.file), FileExistsMode.FAIL); + this.template.send(new GenericMessage<>(this.file), FileExistsMode.FAIL); fail("Expected exception"); } catch (MessagingException e) { - assertThat(e.getMessage(), Matchers.containsString("The destination file already exists")); + assertThat(e.getMessage()).contains("The destination file already exists"); } - verify(this.session, never()).write(Mockito.any(InputStream.class), Mockito.anyString()); + verify(this.session, never()).write(any(InputStream.class), anyString()); } @Test public void testIgnoreExists() throws Exception { - when(session.exists(Mockito.anyString())).thenReturn(true); - this.template.send(new GenericMessage(this.file), FileExistsMode.IGNORE); - verify(this.session, never()).write(Mockito.any(InputStream.class), Mockito.anyString()); + when(session.exists(anyString())).thenReturn(true); + this.template.send(new GenericMessage<>(this.file), FileExistsMode.IGNORE); + verify(this.session, never()).write(any(InputStream.class), anyString()); } @Test public void testFailNotExists() throws Exception { - when(session.exists(Mockito.anyString())).thenReturn(false); - this.template.send(new GenericMessage(this.file), FileExistsMode.FAIL); - verify(this.session).write(Mockito.any(InputStream.class), Mockito.anyString()); + when(session.exists(anyString())).thenReturn(false); + this.template.send(new GenericMessage<>(this.file), FileExistsMode.FAIL); + verify(this.session).write(any(InputStream.class), anyString()); } @Test public void testIgnoreNotExists() throws Exception { - when(session.exists(Mockito.anyString())).thenReturn(false); - this.template.send(new GenericMessage(this.file), FileExistsMode.IGNORE); - verify(this.session).write(Mockito.any(InputStream.class), Mockito.anyString()); + when(session.exists(anyString())).thenReturn(false); + this.template.send(new GenericMessage<>(this.file), FileExistsMode.IGNORE); + verify(this.session).write(any(InputStream.class), anyString()); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java index 44c7013c8d..30ad18b833 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/StreamingInboundTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 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,10 +16,8 @@ package org.springframework.integration.file.remote; -import static org.hamcrest.CoreMatchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willReturn; import static org.mockito.BDDMockito.willThrow; @@ -35,9 +33,7 @@ import java.util.Collection; import java.util.Comparator; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; @@ -54,14 +50,13 @@ import org.springframework.messaging.MessagingException; /** * @author Gary Russell + * @author Artem Bilan + * * @since 4.3 * */ public class StreamingInboundTests { - @Rule - public ExpectedException exception = ExpectedException.none(); - private final StreamTransformer transformer = new StreamTransformer(); @SuppressWarnings("unchecked") @@ -73,33 +68,33 @@ public class StreamingInboundTests { streamer.setRemoteDirectory("/foo"); streamer.afterPropertiesSet(); Message received = (Message) this.transformer.transform(streamer.receive()); - assertEquals("foo\nbar", new String(received.getPayload())); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("foo", received.getHeaders().get(FileHeaders.REMOTE_FILE)); + assertThat(received.getPayload()).isEqualTo("foo\nbar".getBytes()); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); String fileInfo = (String) received.getHeaders().get(FileHeaders.REMOTE_FILE_INFO); - assertThat(fileInfo, containsString("remoteDirectory\":\"/foo")); - assertThat(fileInfo, containsString("permissions\":\"-rw-rw-rw")); - assertThat(fileInfo, containsString("size\":42")); - assertThat(fileInfo, containsString("directory\":false")); - assertThat(fileInfo, containsString("filename\":\"foo")); - assertThat(fileInfo, containsString("modified\":42000")); - assertThat(fileInfo, containsString("link\":false")); + assertThat(fileInfo).contains("remoteDirectory\":\"/foo"); + assertThat(fileInfo).contains("permissions\":\"-rw-rw-rw"); + assertThat(fileInfo).contains("size\":42"); + assertThat(fileInfo).contains("directory\":false"); + assertThat(fileInfo).contains("filename\":\"foo"); + assertThat(fileInfo).contains("modified\":42000"); + assertThat(fileInfo).contains("link\":false"); // close after list, transform verify(StaticMessageHeaderAccessor.getCloseableResource(received), times(2)).close(); received = (Message) this.transformer.transform(streamer.receive()); - assertEquals("baz\nqux", new String(received.getPayload())); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("bar", received.getHeaders().get(FileHeaders.REMOTE_FILE)); + assertThat(received.getPayload()).isEqualTo("baz\nqux".getBytes()); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("bar"); fileInfo = (String) received.getHeaders().get(FileHeaders.REMOTE_FILE_INFO); - assertThat(fileInfo, containsString("remoteDirectory\":\"/foo")); - assertThat(fileInfo, containsString("permissions\":\"-rw-rw-rw")); - assertThat(fileInfo, containsString("size\":42")); - assertThat(fileInfo, containsString("directory\":false")); - assertThat(fileInfo, containsString("filename\":\"bar")); - assertThat(fileInfo, containsString("modified\":42000")); - assertThat(fileInfo, containsString("link\":false")); + assertThat(fileInfo).contains("remoteDirectory\":\"/foo"); + assertThat(fileInfo).contains("permissions\":\"-rw-rw-rw"); + assertThat(fileInfo).contains("size\":42"); + assertThat(fileInfo).contains("directory\":false"); + assertThat(fileInfo).contains("filename\":\"bar"); + assertThat(fileInfo).contains("modified\":42000"); + assertThat(fileInfo).contains("link\":false"); // close after transform verify(StaticMessageHeaderAccessor.getCloseableResource(received), times(3)).close(); @@ -118,17 +113,17 @@ public class StreamingInboundTests { streamer.setFilter(new AcceptOnceFileListFilter<>()); streamer.afterPropertiesSet(); Message received = (Message) this.transformer.transform(streamer.receive()); - assertEquals("foo\nbar", new String(received.getPayload())); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("foo", received.getHeaders().get(FileHeaders.REMOTE_FILE)); + assertThat(received.getPayload()).isEqualTo("foo\nbar".getBytes()); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); // close after list, transform verify(StaticMessageHeaderAccessor.getCloseableResource(received), times(2)).close(); received = (Message) this.transformer.transform(streamer.receive()); - assertEquals("baz\nqux", new String(received.getPayload())); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("bar", received.getHeaders().get(FileHeaders.REMOTE_FILE)); + assertThat(received.getPayload()).isEqualTo("baz\nqux".getBytes()); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("bar"); // close after list, transform verify(new IntegrationMessageHeaderAccessor(received).getCloseableResource(), times(4)).close(); @@ -138,13 +133,13 @@ public class StreamingInboundTests { @Test public void testExceptionOnFetch() throws Exception { - exception.expect(MessagingException.class); StringSessionFactory sessionFactory = new StringSessionFactory(); Streamer streamer = new Streamer(new StringRemoteFileTemplate(sessionFactory), null); streamer.setBeanFactory(mock(BeanFactory.class)); streamer.setRemoteDirectory("/bad"); streamer.afterPropertiesSet(); - streamer.receive(); + assertThatThrownBy(streamer::receive) + .isInstanceOf(MessagingException.class); } @SuppressWarnings("unchecked") @@ -161,30 +156,30 @@ public class StreamingInboundTests { splitter.afterPropertiesSet(); Message receivedStream = streamer.receive(); splitter.handleMessage(receivedStream); - Message received = (Message) out.receive(0); - assertEquals("foo", received.getPayload()); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("foo", received.getHeaders().get(FileHeaders.REMOTE_FILE)); + Message received = out.receive(0); + assertThat(received.getPayload()).isEqualTo("foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); received = (Message) out.receive(0); - assertEquals("bar", received.getPayload()); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("foo", received.getHeaders().get(FileHeaders.REMOTE_FILE)); - assertNull(out.receive(0)); + assertThat(received.getPayload()).isEqualTo("bar"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); + assertThat(out.receive(0)).isNull(); // close by list, splitter verify(new IntegrationMessageHeaderAccessor(receivedStream).getCloseableResource(), times(3)).close(); receivedStream = streamer.receive(); splitter.handleMessage(receivedStream); - received = (Message) out.receive(0); - assertEquals("baz", received.getPayload()); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("bar", received.getHeaders().get(FileHeaders.REMOTE_FILE)); - received = (Message) out.receive(0); - assertEquals("qux", received.getPayload()); - assertEquals("/foo", received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("bar", received.getHeaders().get(FileHeaders.REMOTE_FILE)); - assertNull(out.receive(0)); + received = out.receive(0); + assertThat(received.getPayload()).isEqualTo("baz"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("bar"); + received = out.receive(0); + assertThat(received.getPayload()).isEqualTo("qux"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("/foo"); + assertThat(received.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("bar"); + assertThat(out.receive(0)).isNull(); // close by splitter verify(new IntegrationMessageHeaderAccessor(receivedStream).getCloseableResource(), times(5)).close(); @@ -203,7 +198,7 @@ public class StreamingInboundTests { @Override protected List> asFileInfoList(Collection files) { - List> infos = new ArrayList>(); + List> infos = new ArrayList<>(); for (String file : files) { infos.add(new StringFileInfo(file)); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java index 46c980bf57..43ef874727 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,18 +16,8 @@ package org.springframework.integration.file.remote.gateway; -import static org.hamcrest.Matchers.anyOf; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -92,14 +82,14 @@ public class RemoteFileOutboundGatewayTests { @Test(expected = IllegalArgumentException.class) - public void testBad() throws Exception { + public void testBad() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "bad", "payload"); gw.afterPropertiesSet(); } @Test - public void testBadFilterGet() throws Exception { + public void testBadFilterGet() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setFilter(new TestPatternFilter("")); @@ -108,12 +98,12 @@ public class RemoteFileOutboundGatewayTests { fail("Exception expected"); } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Filters are not supported")); + assertThat(e.getMessage().startsWith("Filters are not supported")).isTrue(); } } @Test - public void testBadFilterRm() throws Exception { + public void testBadFilterRm() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "rm", "payload"); gw.setFilter(new TestPatternFilter("")); @@ -122,7 +112,7 @@ public class RemoteFileOutboundGatewayTests { fail("Exception expected"); } catch (IllegalArgumentException e) { - assertTrue(e.getMessage().startsWith("Filters are not supported")); + assertThat(e.getMessage().startsWith("Filters are not supported")).isTrue(); } } @@ -138,15 +128,14 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); - assertEquals(2, out.getPayload().size()); - assertSame(files[1], out.getPayload().get(0)); // sort by default - assertSame(files[0], out.getPayload().get(1)); - assertEquals("testremote/x/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); + assertThat(out.getPayload().size()).isEqualTo(2); + assertThat(out.getPayload().get(0)).isSameAs(files[1]); // sort by default + assertThat(out.getPayload().get(1)).isSameAs(files[0]); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } @Test - public void testMGetWild() throws Exception { + public void testMGetWild() { testMGetWildGuts("f1", "f2"); } @@ -156,7 +145,7 @@ public class RemoteFileOutboundGatewayTests { * @throws Exception */ @Test - public void testMGetWildFullPath() throws Exception { + public void testMGetWildFullPath() { testMGetWildGuts("testremote/f1", "testremote/f2"); } @@ -175,34 +164,34 @@ public class RemoteFileOutboundGatewayTests { public void read(String source, OutputStream outputStream) throws IOException { if (n++ == 0) { - assertEquals("testremote/f1", source); + assertThat(source).isEqualTo("testremote/f1"); } else { - assertEquals("testremote/f2", source); + assertThat(source).isEqualTo("testremote/f2"); } outputStream.write("testData".getBytes()); } @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry(path1.replaceFirst("testremote/", ""), 123, false, false, 1234, "-r--r--r--"), - new TestLsEntry(path2.replaceFirst("testremote/", ""), 123, false, false, 1234, "-r--r--r--") }; + new TestLsEntry(path2.replaceFirst("testremote/", ""), 123, false, false, 1234, + "-r--r--r--") }; } }); @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote/*")); - assertEquals(2, out.getPayload().size()); - assertEquals("f1", out.getPayload().get(0).getName()); - assertEquals("f2", out.getPayload().get(1).getName()); - assertEquals("testremote/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); + assertThat(out.getPayload().size()).isEqualTo(2); + assertThat(out.getPayload().get(0).getName()).isEqualTo("f1"); + assertThat(out.getPayload().get(1).getName()).isEqualTo("f2"); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/"); } @Test - public void testMGetSingle() throws Exception { + public void testMGetSingle() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mget", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); @@ -217,7 +206,7 @@ public class RemoteFileOutboundGatewayTests { } @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 123, false, false, 1234, "-r--r--r--") }; } @@ -225,14 +214,13 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote/f1")); - assertEquals(1, out.getPayload().size()); - assertEquals("f1", out.getPayload().get(0).getName()); - assertEquals("testremote/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); + assertThat(out.getPayload().size()).isEqualTo(1); + assertThat(out.getPayload().get(0).getName()).isEqualTo("f1"); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/"); } @Test(expected = MessagingException.class) - public void testMGetEmpty() throws Exception { + public void testMGetEmpty() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mget", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); @@ -249,7 +237,7 @@ public class RemoteFileOutboundGatewayTests { } }); - gw.handleRequestMessage(new GenericMessage("testremote/*")); + gw.handleRequestMessage(new GenericMessage<>("testremote/*")); } @Test @@ -258,10 +246,10 @@ public class RemoteFileOutboundGatewayTests { TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "mv", "payload"); gw.afterPropertiesSet(); Session session = mock(Session.class); - final AtomicReference args = new AtomicReference(); + final AtomicReference args = new AtomicReference<>(); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); - args.set((String) arguments[0] + (String) arguments[1]); + args.set((String) arguments[0] + arguments[1]); return null; }).when(session).rename(anyString(), anyString()); when(sessionFactory.getSession()).thenReturn(session); @@ -269,9 +257,9 @@ public class RemoteFileOutboundGatewayTests { .setHeader(FileHeaders.RENAME_TO, "bar") .build(); MessageBuilder out = (MessageBuilder) gw.handleRequestMessage(requestMessage); - assertEquals("foo", out.getHeaders().get(FileHeaders.REMOTE_FILE)); - assertEquals("foobar", args.get()); - assertEquals(Boolean.TRUE, out.getPayload()); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); + assertThat(args.get()).isEqualTo("foobar"); + assertThat(out.getPayload()).isEqualTo(Boolean.TRUE); } @Test @@ -281,7 +269,7 @@ public class RemoteFileOutboundGatewayTests { gw.setRenameExpression(PARSER.parseExpression("payload.substring(1)")); gw.afterPropertiesSet(); Session session = mock(Session.class); - final AtomicReference args = new AtomicReference(); + final AtomicReference args = new AtomicReference<>(); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); args.set((String) arguments[0] + arguments[1]); @@ -289,10 +277,10 @@ public class RemoteFileOutboundGatewayTests { }).when(session).rename(anyString(), anyString()); when(sessionFactory.getSession()).thenReturn(session); MessageBuilder out = (MessageBuilder) gw.handleRequestMessage(new GenericMessage<>("foo")); - assertEquals("oo", out.getHeaders().get(FileHeaders.RENAME_TO)); - assertEquals("foo", out.getHeaders().get(FileHeaders.REMOTE_FILE)); - assertEquals("foooo", args.get()); - assertEquals(Boolean.TRUE, out.getPayload()); + assertThat(out.getHeaders().get(FileHeaders.RENAME_TO)).isEqualTo("oo"); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); + assertThat(args.get()).isEqualTo("foooo"); + assertThat(out.getPayload()).isEqualTo(Boolean.TRUE); } @Test @@ -302,13 +290,13 @@ public class RemoteFileOutboundGatewayTests { gw.setRenameExpression(PARSER.parseExpression("'foo/bar/baz'")); gw.afterPropertiesSet(); Session session = mock(Session.class); - final AtomicReference args = new AtomicReference(); + final AtomicReference args = new AtomicReference<>(); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); - args.set((String) arguments[0] + (String) arguments[1]); + args.set((String) arguments[0] + arguments[1]); return null; }).when(session).rename(anyString(), anyString()); - final List madeDirs = new ArrayList(); + final List madeDirs = new ArrayList<>(); doAnswer(invocation -> { madeDirs.add(invocation.getArgument(0)); return null; @@ -318,12 +306,12 @@ public class RemoteFileOutboundGatewayTests { .setHeader(FileHeaders.RENAME_TO, "bar") .build(); MessageBuilder out = (MessageBuilder) gw.handleRequestMessage(requestMessage); - assertEquals("foo", out.getHeaders().get(FileHeaders.REMOTE_FILE)); - assertEquals("foofoo/bar/baz", args.get()); - assertEquals(Boolean.TRUE, out.getPayload()); - assertEquals(2, madeDirs.size()); - assertEquals("foo", madeDirs.get(0)); - assertEquals("foo/bar", madeDirs.get(1)); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("foo"); + assertThat(args.get()).isEqualTo("foofoo/bar/baz"); + assertThat(out.getPayload()).isEqualTo(Boolean.TRUE); + assertThat(madeDirs.size()).isEqualTo(2); + assertThat(madeDirs.get(0)).isEqualTo("foo"); + assertThat(madeDirs.get(1)).isEqualTo("foo/bar"); } public TestLsEntry[] fileList() { @@ -350,11 +338,10 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); - assertEquals(2, out.getPayload().size()); - assertSame(files[0], out.getPayload().get(0)); - assertSame(files[1], out.getPayload().get(1)); - assertEquals("testremote/x/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); + assertThat(out.getPayload().size()).isEqualTo(2); + assertThat(out.getPayload().get(0)).isSameAs(files[0]); + assertThat(out.getPayload().get(1)).isSameAs(files[1]); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } public TestLsEntry[] level1List() { @@ -395,13 +382,12 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); - assertEquals(4, out.getPayload().size()); - assertEquals("f1", out.getPayload().get(0).getFilename()); - assertEquals("d1/d2/f4", out.getPayload().get(1).getFilename()); - assertEquals("d1/f3", out.getPayload().get(2).getFilename()); - assertEquals("f2", out.getPayload().get(3).getFilename()); - assertEquals("testremote/x/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); + assertThat(out.getPayload().size()).isEqualTo(4); + assertThat(out.getPayload().get(0).getFilename()).isEqualTo("f1"); + assertThat(out.getPayload().get(1).getFilename()).isEqualTo("d1/d2/f4"); + assertThat(out.getPayload().get(2).getFilename()).isEqualTo("d1/f3"); + assertThat(out.getPayload().get(3).getFilename()).isEqualTo("f2"); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } @Test @@ -421,14 +407,13 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote/x")); - assertEquals(5, out.getPayload().size()); - assertEquals("f1", out.getPayload().get(0).getFilename()); - assertEquals("d1", out.getPayload().get(1).getFilename()); - assertEquals("d1/d2", out.getPayload().get(2).getFilename()); - assertEquals("d1/f3", out.getPayload().get(3).getFilename()); - assertEquals("f2", out.getPayload().get(4).getFilename()); - assertEquals("testremote/x/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); + assertThat(out.getPayload().size()).isEqualTo(5); + assertThat(out.getPayload().get(0).getFilename()).isEqualTo("f1"); + assertThat(out.getPayload().get(1).getFilename()).isEqualTo("d1"); + assertThat(out.getPayload().get(2).getFilename()).isEqualTo("d1/d2"); + assertThat(out.getPayload().get(3).getFilename()).isEqualTo("d1/f3"); + assertThat(out.getPayload().get(4).getFilename()).isEqualTo("f2"); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); } @Test @@ -443,7 +428,7 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote")); - assertEquals(0, out.getPayload().size()); + assertThat(out.getPayload().size()).isEqualTo(0); } @Test @@ -459,9 +444,9 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote")); - assertEquals(2, out.getPayload().size()); - assertEquals("f1", out.getPayload().get(0)); - assertEquals("f2", out.getPayload().get(1)); + assertThat(out.getPayload().size()).isEqualTo(2); + assertThat(out.getPayload().get(0)).isEqualTo("f1"); + assertThat(out.getPayload().get(1)).isEqualTo("f2"); } @Test @@ -477,9 +462,9 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote")); - assertEquals(2, out.getPayload().size()); - assertEquals("f2", out.getPayload().get(0)); - assertEquals("f1", out.getPayload().get(1)); + assertThat(out.getPayload().size()).isEqualTo(2); + assertThat(out.getPayload().get(0)).isEqualTo("f2"); + assertThat(out.getPayload().get(1)).isEqualTo("f1"); } @Test @@ -495,10 +480,10 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote")); - assertEquals(3, out.getPayload().size()); - assertEquals("f1", out.getPayload().get(0)); - assertEquals("f2", out.getPayload().get(1)); - assertEquals("f3", out.getPayload().get(2)); + assertThat(out.getPayload().size()).isEqualTo(3); + assertThat(out.getPayload().get(0)).isEqualTo("f1"); + assertThat(out.getPayload().get(1)).isEqualTo("f2"); + assertThat(out.getPayload().get(2)).isEqualTo("f3"); } @Test @@ -514,11 +499,11 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote")); - assertEquals(4, out.getPayload().size()); - assertEquals("f1", out.getPayload().get(0)); - assertEquals("f2", out.getPayload().get(1)); - assertEquals("f3", out.getPayload().get(2)); - assertEquals("f4", out.getPayload().get(3)); + assertThat(out.getPayload().size()).isEqualTo(4); + assertThat(out.getPayload().get(0)).isEqualTo("f1"); + assertThat(out.getPayload().get(1)).isEqualTo("f2"); + assertThat(out.getPayload().get(2)).isEqualTo("f3"); + assertThat(out.getPayload().get(3)).isEqualTo("f4"); } @Test @@ -534,13 +519,13 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote")); - assertEquals(6, out.getPayload().size()); - assertEquals("f2", out.getPayload().get(0)); - assertEquals("f1", out.getPayload().get(1)); - assertEquals("f3", out.getPayload().get(2)); - assertEquals("f4", out.getPayload().get(3)); - assertEquals(".f5", out.getPayload().get(4)); - assertEquals(".f6", out.getPayload().get(5)); + assertThat(out.getPayload().size()).isEqualTo(6); + assertThat(out.getPayload().get(0)).isEqualTo("f2"); + assertThat(out.getPayload().get(1)).isEqualTo("f1"); + assertThat(out.getPayload().get(2)).isEqualTo("f3"); + assertThat(out.getPayload().get(3)).isEqualTo("f4"); + assertThat(out.getPayload().get(4)).isEqualTo(".f5"); + assertThat(out.getPayload().get(5)).isEqualTo(".f6"); } @Test @@ -557,8 +542,8 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder> out = (MessageBuilder>) gw .handleRequestMessage(new GenericMessage<>("testremote")); - assertEquals(1, out.getPayload().size()); - assertEquals("f4", out.getPayload().get(0)); + assertThat(out.getPayload().size()).isEqualTo(1); + assertThat(out.getPayload().get(0)).isEqualTo("f4"); } @Test @@ -571,7 +556,7 @@ public class RemoteFileOutboundGatewayTests { when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; @@ -587,11 +572,11 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder out = (MessageBuilder) gw.handleRequestMessage(new GenericMessage<>("f1")); File outFile = new File(this.tmpDir + "/f1"); - assertEquals(outFile, out.getPayload()); - assertTrue(outFile.exists()); + assertThat(out.getPayload()).isEqualTo(outFile); + assertThat(outFile.exists()).isTrue(); outFile.delete(); - assertNull(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("f1", out.getHeaders().get(FileHeaders.REMOTE_FILE)); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isNull(); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("f1"); } @SuppressWarnings("unchecked") @@ -608,7 +593,7 @@ public class RemoteFileOutboundGatewayTests { when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; @@ -629,7 +614,7 @@ public class RemoteFileOutboundGatewayTests { fail("Exception expected"); } catch (MessageHandlingException e) { - assertThat(e.getMessage(), containsString("already exists")); + assertThat(e.getMessage()).contains("already exists"); } gw.setFileExistsMode(FileExistsMode.FAIL); @@ -638,22 +623,22 @@ public class RemoteFileOutboundGatewayTests { fail("Exception expected"); } catch (MessageHandlingException e) { - assertThat(e.getMessage(), containsString("already exists")); + assertThat(e.getMessage()).contains("already exists"); } gw.setFileExistsMode(FileExistsMode.IGNORE); out = (MessageBuilder) gw.handleRequestMessage(new GenericMessage<>("f1")); - assertEquals(outFile, out.getPayload()); + assertThat(out.getPayload()).isEqualTo(outFile); assertContents("foo", outFile); gw.setFileExistsMode(FileExistsMode.APPEND); out = (MessageBuilder) gw.handleRequestMessage(new GenericMessage<>("f1")); - assertEquals(outFile, out.getPayload()); + assertThat(out.getPayload()).isEqualTo(outFile); assertContents("footestfile", outFile); gw.setFileExistsMode(FileExistsMode.REPLACE); out = (MessageBuilder) gw.handleRequestMessage(new GenericMessage<>("f1")); - assertEquals(outFile, out.getPayload()); + assertThat(out.getPayload()).isEqualTo(outFile); assertContents("testfile", outFile); outFile.delete(); @@ -661,12 +646,12 @@ public class RemoteFileOutboundGatewayTests { private void assertContents(String expected, File outFile) throws Exception { BufferedReader reader = new BufferedReader(new FileReader(outFile)); - assertEquals(expected, reader.readLine()); + assertThat(reader.readLine()).isEqualTo(expected); reader.close(); } @Test - public void testGetTempFileDelete() throws Exception { + public void testGetTempFileDelete() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); @@ -675,7 +660,7 @@ public class RemoteFileOutboundGatewayTests { when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; @@ -688,22 +673,22 @@ public class RemoteFileOutboundGatewayTests { }); try { - gw.handleRequestMessage(new GenericMessage("f1")); + gw.handleRequestMessage(new GenericMessage<>("f1")); fail("Expected exception"); } catch (MessagingException e) { - assertThat(e.getCause(), instanceOf(RuntimeException.class)); - assertEquals("test remove .writing", e.getCause().getMessage()); + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + assertThat(e.getCause().getMessage()).isEqualTo("test remove .writing"); @SuppressWarnings("unchecked") RemoteFileTemplate template = new RemoteFileTemplate(sessionFactory); File outFile = new File(this.tmpDir + "/f1" + template.getTemporaryFileSuffix()); - assertFalse(outFile.exists()); + assertThat(outFile.exists()).isFalse(); } } @Test - public void testGet_P() throws Exception { + public void testGet_P() { SessionFactory sessionFactory = mock(SessionFactory.class); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(sessionFactory, "get", "payload"); gw.setLocalDirectory(new File(this.tmpDir)); @@ -716,7 +701,7 @@ public class RemoteFileOutboundGatewayTests { when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, modified.getTime(), "-rw-r--r--") }; @@ -732,18 +717,16 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder out = (MessageBuilder) gw.handleRequestMessage(new GenericMessage<>("x/f1")); File outFile = new File(this.tmpDir + "/f1"); - assertEquals(outFile, out.getPayload()); - assertTrue(outFile.exists()); - assertEquals(modified.getTime(), outFile.lastModified()); + assertThat(out.getPayload()).isEqualTo(outFile); + assertThat(outFile.exists()).isTrue(); + assertThat(outFile.lastModified()).isEqualTo(modified.getTime()); outFile.delete(); - assertEquals("x/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("f1", - out.getHeaders().get(FileHeaders.REMOTE_FILE)); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("x/"); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("f1"); } @Test - public void testGet_create_dir() throws Exception { + public void testGet_create_dir() { new File(this.tmpDir + "/x/f1").delete(); new File(this.tmpDir + "/x").delete(); SessionFactory sessionFactory = mock(SessionFactory.class); @@ -753,7 +736,7 @@ public class RemoteFileOutboundGatewayTests { when(sessionFactory.getSession()).thenReturn(new TestSession() { @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; @@ -766,9 +749,9 @@ public class RemoteFileOutboundGatewayTests { } }); - gw.handleRequestMessage(new GenericMessage("f1")); + gw.handleRequestMessage(new GenericMessage<>("f1")); File out = new File(this.tmpDir + "/x/f1"); - assertTrue(out.exists()); + assertThat(out.exists()).isTrue(); out.delete(); } @@ -783,12 +766,10 @@ public class RemoteFileOutboundGatewayTests { @SuppressWarnings("unchecked") MessageBuilder out = (MessageBuilder) gw .handleRequestMessage(new GenericMessage<>("testremote/x/f1")); - assertEquals(Boolean.TRUE, out.getPayload()); + assertThat(out.getPayload()).isEqualTo(Boolean.TRUE); verify(session).remove("testremote/x/f1"); - assertEquals("testremote/x/", - out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)); - assertEquals("f1", - out.getHeaders().get(FileHeaders.REMOTE_FILE)); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_DIRECTORY)).isEqualTo("testremote/x/"); + assertThat(out.getHeaders().get(FileHeaders.REMOTE_FILE)).isEqualTo("f1"); } @Test @@ -809,7 +790,7 @@ public class RemoteFileOutboundGatewayTests { template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload"); - FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sessionFactory); + FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpressionString("'foo/'"); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); @@ -819,10 +800,10 @@ public class RemoteFileOutboundGatewayTests { .setHeader(FileHeaders.FILENAME, "bar.txt") .build(); String path = (String) gw.handleRequestMessage(requestMessage); - assertEquals("foo/bar.txt", path); + assertThat(path).isEqualTo("foo/bar.txt"); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(session).write(any(InputStream.class), captor.capture()); - assertEquals("foo/bar.txt.writing", captor.getValue()); + assertThat(captor.getValue()).isEqualTo("foo/bar.txt.writing"); verify(session).rename("foo/bar.txt.writing", "foo/bar.txt"); } @@ -844,7 +825,7 @@ public class RemoteFileOutboundGatewayTests { template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "put", "payload"); - FileTransferringMessageHandler handler = new FileTransferringMessageHandler(sessionFactory); + FileTransferringMessageHandler handler = new FileTransferringMessageHandler<>(sessionFactory); handler.setRemoteDirectoryExpression(new LiteralExpression("foo/")); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); @@ -856,10 +837,10 @@ public class RemoteFileOutboundGatewayTests { // default (null) == REPLACE String path = (String) gw.handleRequestMessage(requestMessage); - assertEquals("foo/bar.txt", path); + assertThat(path).isEqualTo("foo/bar.txt"); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); verify(session).write(any(InputStream.class), captor.capture()); - assertEquals("foo/bar.txt.writing", captor.getValue()); + assertThat(captor.getValue()).isEqualTo("foo/bar.txt.writing"); verify(session).rename("foo/bar.txt.writing", "foo/bar.txt"); gw.setFileExistsMode(FileExistsMode.FAIL); @@ -868,27 +849,27 @@ public class RemoteFileOutboundGatewayTests { fail("Exception expected"); } catch (Exception e) { - assertThat(e.getMessage(), containsString("The destination file already exists")); + assertThat(e.getMessage()).contains("The destination file already exists"); } gw.setFileExistsMode(FileExistsMode.REPLACE); path = (String) gw.handleRequestMessage(requestMessage); - assertEquals("foo/bar.txt", path); + assertThat(path).isEqualTo("foo/bar.txt"); captor = ArgumentCaptor.forClass(String.class); verify(session, times(2)).write(any(InputStream.class), captor.capture()); - assertEquals("foo/bar.txt.writing", captor.getValue()); + assertThat(captor.getValue()).isEqualTo("foo/bar.txt.writing"); verify(session, times(2)).rename("foo/bar.txt.writing", "foo/bar.txt"); gw.setFileExistsMode(FileExistsMode.APPEND); path = (String) gw.handleRequestMessage(requestMessage); - assertEquals("foo/bar.txt", path); + assertThat(path).isEqualTo("foo/bar.txt"); captor = ArgumentCaptor.forClass(String.class); verify(session).append(any(InputStream.class), captor.capture()); - assertEquals("foo/bar.txt", captor.getValue()); + assertThat(captor.getValue()).isEqualTo("foo/bar.txt"); gw.setFileExistsMode(FileExistsMode.IGNORE); path = (String) gw.handleRequestMessage(requestMessage); - assertEquals("foo/bar.txt", path); + assertThat(path).isEqualTo("foo/bar.txt"); // no more writes/appends verify(session, times(2)).write(any(InputStream.class), anyString()); verify(session, times(1)).append(any(InputStream.class), anyString()); @@ -900,14 +881,14 @@ public class RemoteFileOutboundGatewayTests { SessionFactory sessionFactory = mock(SessionFactory.class); @SuppressWarnings("unchecked") Session session = mock(Session.class); - RemoteFileTemplate template = new RemoteFileTemplate(sessionFactory); + RemoteFileTemplate template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "mput", "payload"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); - final AtomicReference written = new AtomicReference(); + final AtomicReference written = new AtomicReference<>(); doAnswer(invocation -> { written.set(invocation.getArgument(1)); return null; @@ -918,13 +899,10 @@ public class RemoteFileOutboundGatewayTests { .build(); @SuppressWarnings("unchecked") List out = (List) gw.handleRequestMessage(requestMessage); - assertEquals(2, out.size()); - assertThat(out.get(0), - not(equalTo(out.get(1)))); - assertThat(out.get(0), anyOf( - equalTo("foo/baz.txt"), equalTo("foo/qux.txt"))); - assertThat(out.get(1), anyOf( - equalTo("foo/baz.txt"), equalTo("foo/qux.txt"))); + assertThat(out.size()).isEqualTo(2); + assertThat(out.get(0)).isNotEqualTo(out.get(1)); + assertThat(out.get(0)).isIn("foo/baz.txt", "foo/qux.txt"); + assertThat(out.get(1)).isIn("foo/baz.txt", "foo/qux.txt"); } @Test @@ -933,7 +911,7 @@ public class RemoteFileOutboundGatewayTests { SessionFactory sessionFactory = mock(SessionFactory.class); @SuppressWarnings("unchecked") Session session = mock(Session.class); - RemoteFileTemplate template = new RemoteFileTemplate(sessionFactory); + RemoteFileTemplate template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); @@ -941,7 +919,7 @@ public class RemoteFileOutboundGatewayTests { gw.setOptions("-R"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); - final AtomicReference written = new AtomicReference(); + final AtomicReference written = new AtomicReference<>(); doAnswer(invocation -> { written.set(invocation.getArgument(1)); return null; @@ -955,15 +933,11 @@ public class RemoteFileOutboundGatewayTests { .build(); @SuppressWarnings("unchecked") List out = (List) gw.handleRequestMessage(requestMessage); - assertEquals(3, out.size()); - assertThat(out.get(0), - not(equalTo(out.get(1)))); - assertThat(out.get(0), anyOf( - equalTo("foo/baz.txt"), equalTo("foo/qux.txt"), equalTo("foo/" + dir1.getName() + "/" + file3.getName()))); - assertThat(out.get(1), anyOf( - equalTo("foo/baz.txt"), equalTo("foo/qux.txt"), equalTo("foo/" + dir1.getName() + "/" + file3.getName()))); - assertThat(out.get(2), anyOf( - equalTo("foo/baz.txt"), equalTo("foo/qux.txt"), equalTo("foo/" + dir1.getName() + "/" + file3.getName()))); + assertThat(out.size()).isEqualTo(3); + assertThat(out.get(0)).isNotEqualTo(out.get(1)); + assertThat(out.get(0)).isIn("foo/baz.txt", "foo/qux.txt", "foo/" + dir1.getName() + "/" + file3.getName()); + assertThat(out.get(1)).isIn("foo/baz.txt", "foo/qux.txt", "foo/" + dir1.getName() + "/" + file3.getName()); + assertThat(out.get(2)).isIn("foo/baz.txt", "foo/qux.txt", "foo/" + dir1.getName() + "/" + file3.getName()); } @Test @@ -972,14 +946,14 @@ public class RemoteFileOutboundGatewayTests { SessionFactory sessionFactory = mock(SessionFactory.class); @SuppressWarnings("unchecked") Session session = mock(Session.class); - RemoteFileTemplate template = new RemoteFileTemplate(sessionFactory); + RemoteFileTemplate template = new RemoteFileTemplate<>(sessionFactory); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setBeanFactory(mock(BeanFactory.class)); template.afterPropertiesSet(); TestRemoteFileOutboundGateway gw = new TestRemoteFileOutboundGateway(template, "mput", "payload"); gw.afterPropertiesSet(); when(sessionFactory.getSession()).thenReturn(session); - final AtomicReference written = new AtomicReference(); + final AtomicReference written = new AtomicReference<>(); doAnswer(invocation -> { written.set(invocation.getArgument(1)); return null; @@ -991,12 +965,11 @@ public class RemoteFileOutboundGatewayTests { .build(); @SuppressWarnings("unchecked") List out = (List) gw.handleRequestMessage(requestMessage); - assertEquals(2, out.size()); - assertThat(out.get(0), - not(equalTo(out.get(1)))); - assertThat(out.get(0), equalTo("foo/fiz.txt")); - assertThat(out.get(1), equalTo("foo/buz.txt")); - assertThat(written.get(), equalTo("foo/buz.txt.writing")); + assertThat(out.size()).isEqualTo(2); + assertThat(out.get(0)).isNotEqualTo(out.get(1)); + assertThat(out.get(0)).isEqualTo("foo/fiz.txt"); + assertThat(out.get(1)).isEqualTo("foo/buz.txt"); + assertThat(written.get()).isEqualTo("foo/buz.txt.writing"); verify(session).rename("foo/buz.txt.writing", "foo/buz.txt"); } @@ -1006,12 +979,12 @@ public class RemoteFileOutboundGatewayTests { @Override - public boolean remove(String path) throws IOException { + public boolean remove(String path) { return false; } @Override - public TestLsEntry[] list(String path) throws IOException { + public TestLsEntry[] list(String path) { return null; } @@ -1021,28 +994,25 @@ public class RemoteFileOutboundGatewayTests { } @Override - public void write(InputStream inputStream, String destination) - throws IOException { + public void write(InputStream inputStream, String destination) { } @Override - public void append(InputStream inputStream, String destination) - throws IOException { + public void append(InputStream inputStream, String destination) { } @Override - public boolean mkdir(String directory) throws IOException { + public boolean mkdir(String directory) { return true; } @Override - public boolean rmdir(String directory) throws IOException { + public boolean rmdir(String directory) { return true; } @Override - public void rename(String pathFrom, String pathTo) - throws IOException { + public void rename(String pathFrom, String pathTo) { } @Override @@ -1056,22 +1026,22 @@ public class RemoteFileOutboundGatewayTests { } @Override - public boolean exists(String path) throws IOException { + public boolean exists(String path) { return true; } @Override - public String[] listNames(String path) throws IOException { + public String[] listNames(String path) { return null; } @Override - public InputStream readRaw(String source) throws IOException { + public InputStream readRaw(String source) { return null; } @Override - public boolean finalizeRaw() throws IOException { + public boolean finalizeRaw() { return false; } @@ -1127,7 +1097,8 @@ public class RemoteFileOutboundGatewayTests { @Override protected List> asFileInfoList( Collection files) { - return new ArrayList>(files); + + return new ArrayList<>(files); } @Override @@ -1154,6 +1125,7 @@ public class RemoteFileOutboundGatewayTests { TestLsEntry(String filename, long size, boolean dir, boolean link, long modified, String permissions) { + this.filename = filename; this.size = size; this.dir = dir; diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java index 46cfbc191d..a93d4de3c5 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/handler/FileTransferringMessageHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.remote.handler; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -66,7 +64,7 @@ public class FileTransferringMessageHandlerTests { when(sf.getSession()).thenReturn(session); doAnswer(invocation -> { String path = invocation.getArgument(1); - assertFalse(path.startsWith("/")); + assertThat(path.startsWith("/")).isFalse(); return null; }).when(session).rename(Mockito.anyString(), Mockito.anyString()); ExpressionParser parser = new SpelExpressionParser(); @@ -99,8 +97,8 @@ public class FileTransferringMessageHandlerTests { handler.afterPropertiesSet(); handler.handleMessage(new GenericMessage("hello")); verify(session, times(1)).write(Mockito.any(InputStream.class), Mockito.anyString()); - assertEquals("bar", temporaryPath.get().substring(0, 3)); - assertEquals("foo", finalPath.get().substring(0, 3)); + assertThat(temporaryPath.get().substring(0, 3)).isEqualTo("bar"); + assertThat(finalPath.get().substring(0, 3)).isEqualTo("foo"); } @SuppressWarnings("unchecked") @@ -112,7 +110,7 @@ public class FileTransferringMessageHandlerTests { when(sf.getSession()).thenReturn(session); doAnswer(invocation -> { String path = invocation.getArgument(1); - assertFalse(path.startsWith("/")); + assertThat(path.startsWith("/")).isFalse(); return null; }).when(session).rename(Mockito.anyString(), Mockito.anyString()); ExpressionParser parser = new SpelExpressionParser(); @@ -176,16 +174,16 @@ public class FileTransferringMessageHandlerTests { handler.handleMessage(new GenericMessage("hello")); } catch (Exception e) { - assertEquals("test", e.getCause().getCause().getMessage()); + assertThat(e.getCause().getCause().getMessage()).isEqualTo("test"); } } verify(session1, times(1)).write(Mockito.any(InputStream.class), Mockito.anyString()); verify(session2, times(1)).write(Mockito.any(InputStream.class), Mockito.anyString()); verify(session3, times(1)).write(Mockito.any(InputStream.class), Mockito.anyString()); SimplePool pool = TestUtils.getPropertyValue(csf, "pool", SimplePool.class); - assertEquals(1, pool.getAllocatedCount()); - assertEquals(1, pool.getIdleCount()); - assertSame(session3, TestUtils.getPropertyValue(pool, "allocated", Set.class).iterator().next()); + assertThat(pool.getAllocatedCount()).isEqualTo(1); + assertThat(pool.getIdleCount()).isEqualTo(1); + assertThat(TestUtils.getPropertyValue(pool, "allocated", Set.class).iterator().next()).isSameAs(session3); } private Session newSession() throws IOException { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java index 3cce48210d..9a65ddefba 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/CachingSessionFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2018 the original author or authors. + * Copyright 2013-2019 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,8 @@ package org.springframework.integration.file.remote.session; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -54,29 +49,29 @@ public class CachingSessionFactoryTests { CachingSessionFactory cache = new CachingSessionFactory(factory); cache.setTestSession(true); Session sess1 = cache.getSession(); - assertEquals("session:1", TestUtils.getPropertyValue(sess1, "targetSession.id")); + assertThat(TestUtils.getPropertyValue(sess1, "targetSession.id")).isEqualTo("session:1"); Session sess2 = cache.getSession(); - assertEquals("session:2", TestUtils.getPropertyValue(sess2, "targetSession.id")); + assertThat(TestUtils.getPropertyValue(sess2, "targetSession.id")).isEqualTo("session:2"); sess1.close(); // session back to pool; should be open and reused. - assertTrue(sess1.isOpen()); + assertThat(sess1.isOpen()).isTrue(); sess1 = cache.getSession(); - assertEquals("session:1", TestUtils.getPropertyValue(sess1, "targetSession.id")); - assertTrue((TestUtils.getPropertyValue(sess1, "targetSession.testCalled", Boolean.class))); + assertThat(TestUtils.getPropertyValue(sess1, "targetSession.id")).isEqualTo("session:1"); + assertThat((TestUtils.getPropertyValue(sess1, "targetSession.testCalled", Boolean.class))).isTrue(); sess1.close(); - assertTrue(sess1.isOpen()); + assertThat(sess1.isOpen()).isTrue(); // reset the cache; should close idle (sess1); sess2 should closed later cache.resetCache(); - assertFalse(sess1.isOpen()); + assertThat(sess1.isOpen()).isFalse(); sess1 = cache.getSession(); - assertEquals("session:3", TestUtils.getPropertyValue(sess1, "targetSession.id")); + assertThat(TestUtils.getPropertyValue(sess1, "targetSession.id")).isEqualTo("session:3"); sess1.close(); - assertTrue(sess1.isOpen()); + assertThat(sess1.isOpen()).isTrue(); // session from previous epoch is closed on return sess2.close(); - assertFalse(sess2.isOpen()); + assertThat(sess2.isOpen()).isFalse(); cache.resetCache(); - assertFalse(sess1.isOpen()); + assertThat(sess1.isOpen()).isFalse(); } @Test @@ -100,8 +95,8 @@ public class CachingSessionFactoryTests { fail("Expected exception"); } catch (Exception e) { - assertThat(e.getCause(), instanceOf(RuntimeException.class)); - assertThat(e.getCause().getMessage(), equalTo("bar")); + assertThat(e.getCause()).isInstanceOf(RuntimeException.class); + assertThat(e.getCause().getMessage()).isEqualTo("bar"); } verify(session).close(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/DelegatingSessionFactoryTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/DelegatingSessionFactoryTests.java index a77df1bca3..ad96a5bbdc 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/DelegatingSessionFactoryTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/session/DelegatingSessionFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 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,10 +16,7 @@ package org.springframework.integration.file.remote.session; -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.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -81,19 +78,19 @@ public class DelegatingSessionFactoryTests { @Test public void testDelegates() { - assertEquals(foo.mockSession, this.dsf.getSession("foo")); - assertEquals(bar.mockSession, this.dsf.getSession("bar")); - assertEquals(bar.mockSession, this.dsf.getSession("junk")); - assertEquals(bar.mockSession, this.dsf.getSession()); + assertThat(this.dsf.getSession("foo")).isEqualTo(foo.mockSession); + assertThat(this.dsf.getSession("bar")).isEqualTo(bar.mockSession); + assertThat(this.dsf.getSession("junk")).isEqualTo(bar.mockSession); + assertThat(this.dsf.getSession()).isEqualTo(bar.mockSession); this.dsf.setThreadKey("foo"); - assertEquals(foo.mockSession, this.dsf.getSession("foo")); + assertThat(this.dsf.getSession("foo")).isEqualTo(foo.mockSession); this.dsf.clearThreadKey(); TestSessionFactory factory = new TestSessionFactory(); this.sessionFactoryLocator.addSessionFactory("baz", factory); this.dsf.setThreadKey("baz"); - assertEquals(factory.mockSession, this.dsf.getSession("baz")); + assertThat(this.dsf.getSession("baz")).isEqualTo(factory.mockSession); this.dsf.clearThreadKey(); - assertSame(factory, sessionFactoryLocator.removeSessionFactory("baz")); + assertThat(sessionFactoryLocator.removeSessionFactory("baz")).isSameAs(factory); } @Test @@ -102,9 +99,9 @@ public class DelegatingSessionFactoryTests { .willReturn(new String[0]); in.send(new GenericMessage<>("foo")); Message received = out.receive(0); - assertNotNull(received); + assertThat(received).isNotNull(); verify(foo.mockSession).list("foo/"); - assertNull(TestUtils.getPropertyValue(dsf, "threadKey", ThreadLocal.class).get()); + assertThat(TestUtils.getPropertyValue(dsf, "threadKey", ThreadLocal.class).get()).isNull(); } @Configuration diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java index d6fdc1c3dc..1b30742544 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/synchronizer/AbstractRemoteFileSynchronizerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2017 the original author or authors. + * Copyright 2014-2019 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,10 +16,8 @@ package org.springframework.integration.file.remote.synchronizer; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.mock; import java.io.File; @@ -87,16 +85,16 @@ public class AbstractRemoteFileSynchronizerTests { try { sync.synchronizeToLocalDirectory(mock(File.class)); - assertEquals(1, count.get()); + assertThat(count.get()).isEqualTo(1); fail("Expected exception"); } catch (MessagingException e) { - assertThat(e.getCause(), instanceOf(MessagingException.class)); - assertThat(e.getCause().getCause(), instanceOf(IOException.class)); - assertEquals("fail", e.getCause().getCause().getMessage()); + assertThat(e.getCause()).isInstanceOf(MessagingException.class); + assertThat(e.getCause().getCause()).isInstanceOf(IOException.class); + assertThat(e.getCause().getCause().getMessage()).isEqualTo("fail"); } sync.synchronizeToLocalDirectory(mock(File.class)); - assertEquals(3, count.get()); + assertThat(count.get()).isEqualTo(3); sync.close(); } @@ -106,11 +104,11 @@ public class AbstractRemoteFileSynchronizerTests { AbstractInboundFileSynchronizer sync = createLimitingSynchronizer(count); sync.synchronizeToLocalDirectory(mock(File.class), 1); - assertEquals(1, count.get()); + assertThat(count.get()).isEqualTo(1); sync.synchronizeToLocalDirectory(mock(File.class), 1); - assertEquals(2, count.get()); + assertThat(count.get()).isEqualTo(2); sync.synchronizeToLocalDirectory(mock(File.class), 1); - assertEquals(3, count.get()); + assertThat(count.get()).isEqualTo(3); sync.close(); } @@ -123,7 +121,7 @@ public class AbstractRemoteFileSynchronizerTests { source.start(); source.receive(); - assertEquals(1, count.get()); + assertThat(count.get()).isEqualTo(1); sync.synchronizeToLocalDirectory(mock(File.class), 1); source.receive(); sync.synchronizeToLocalDirectory(mock(File.class), 1); @@ -139,7 +137,7 @@ public class AbstractRemoteFileSynchronizerTests { source.afterPropertiesSet(); source.start(); source.receive(); - assertEquals(1, count.get()); + assertThat(count.get()).isEqualTo(1); } @Test @@ -150,7 +148,7 @@ public class AbstractRemoteFileSynchronizerTests { source.afterPropertiesSet(); source.start(); source.receive(); - assertEquals(1, count.get()); + assertThat(count.get()).isEqualTo(1); } @Test(expected = IllegalStateException.class) diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/splitter/FileSplitterTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/splitter/FileSplitterTests.java index 2623d9ae07..b2cc5ec253 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/splitter/FileSplitterTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/splitter/FileSplitterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2018 the original author or authors. + * Copyright 2015-2019 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,8 @@ package org.springframework.integration.file.splitter; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeader; -import static org.springframework.integration.test.matcher.HeaderMatcher.hasHeaderKey; -import static org.springframework.integration.test.matcher.PayloadMatcher.hasPayload; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.File; @@ -88,7 +80,7 @@ public class FileSplitterTests { private static File file; - private static final String SAMPLE_CONTENT = "HelloWorld\näöüß"; + private static final String SAMPLE_CONTENT = "HelloWorld\n????"; @Autowired private MessageChannel input1; @@ -118,80 +110,80 @@ public class FileSplitterTests { public void testFileSplitter() throws Exception { this.input1.send(new GenericMessage(file)); Message receive = this.output.receive(10000); - assertNotNull(receive); //HelloWorld - assertEquals("HelloWorld", receive.getPayload()); - assertEquals(2, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); //HelloWorld + assertThat(receive.getPayload()).isEqualTo("HelloWorld"); + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(2); receive = this.output.receive(10000); - assertNotNull(receive); //äöüß - assertEquals("äöüß", receive.getPayload()); - assertEquals(file, receive.getHeaders().get(FileHeaders.ORIGINAL_FILE)); - assertEquals(file.getName(), receive.getHeaders().get(FileHeaders.FILENAME)); - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); //???? + assertThat(receive.getPayload()).isEqualTo("????"); + assertThat(receive.getHeaders().get(FileHeaders.ORIGINAL_FILE)).isEqualTo(file); + assertThat(receive.getHeaders().get(FileHeaders.FILENAME)).isEqualTo(file.getName()); + assertThat(this.output.receive(1)).isNull(); this.input1.send(new GenericMessage(file.getAbsolutePath())); receive = this.output.receive(10000); - assertNotNull(receive); //HelloWorld - assertEquals(2, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); //HelloWorld + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(2); receive = this.output.receive(10000); - assertNotNull(receive); //äöüß - assertEquals(file, receive.getHeaders().get(FileHeaders.ORIGINAL_FILE)); - assertEquals(file.getName(), receive.getHeaders().get(FileHeaders.FILENAME)); - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); //???? + assertThat(receive.getHeaders().get(FileHeaders.ORIGINAL_FILE)).isEqualTo(file); + assertThat(receive.getHeaders().get(FileHeaders.FILENAME)).isEqualTo(file.getName()); + assertThat(this.output.receive(1)).isNull(); this.input1.send(new GenericMessage(new FileReader(file))); receive = this.output.receive(10000); - assertNotNull(receive); //HelloWorld - assertEquals(2, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); //HelloWorld + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(2); receive = this.output.receive(10000); - assertNotNull(receive); //äöüß - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); //???? + assertThat(this.output.receive(1)).isNull(); this.input2.send(new GenericMessage(file)); receive = this.output.receive(10000); - assertNotNull(receive); //HelloWorld - assertEquals(0, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); //HelloWorld + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(0); receive = this.output.receive(10000); - assertNotNull(receive); //äöüß - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); //???? + assertThat(this.output.receive(1)).isNull(); this.input2.send(new GenericMessage(new ByteArrayInputStream(SAMPLE_CONTENT.getBytes("UTF-8")))); receive = this.output.receive(10000); - assertNotNull(receive); //HelloWorld - assertEquals(0, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); //HelloWorld + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(0); receive = this.output.receive(10000); - assertNotNull(receive); //äöüß - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); //???? + assertThat(this.output.receive(1)).isNull(); try { this.input2.send(new GenericMessage("bar")); fail("FileNotFoundException expected"); } catch (Exception e) { - assertThat(e.getCause(), instanceOf(FileNotFoundException.class)); - assertThat(e.getMessage(), containsString("failed to read file [bar]")); + assertThat(e.getCause()).isInstanceOf(FileNotFoundException.class); + assertThat(e.getMessage()).contains("failed to read file [bar]"); } this.input2.send(new GenericMessage(new Date())); receive = this.output.receive(10000); - assertNotNull(receive); - assertEquals(1, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertThat(receive.getPayload(), instanceOf(Date.class)); - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(1); + assertThat(receive.getPayload()).isInstanceOf(Date.class); + assertThat(this.output.receive(1)).isNull(); this.input3.send(new GenericMessage(file)); receive = this.output.receive(10000); - assertNotNull(receive); //HelloWorld - assertEquals(0, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); //HelloWorld + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(0); receive = this.output.receive(10000); - assertNotNull(receive); //äöüß - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); //???? + assertThat(this.output.receive(1)).isNull(); this.input3.send(new GenericMessage(new ByteArrayInputStream(SAMPLE_CONTENT.getBytes("UTF-8")))); receive = this.output.receive(10000); - assertNotNull(receive); //HelloWorld - assertEquals(0, receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); + assertThat(receive).isNotNull(); //HelloWorld + assertThat(receive.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isEqualTo(0); receive = this.output.receive(10000); - assertNotNull(receive); //äöüß - assertNull(this.output.receive(1)); + assertThat(receive).isNotNull(); //???? + assertThat(this.output.receive(1)).isNull(); } @Test @@ -201,23 +193,23 @@ public class FileSplitterTests { splitter.setOutputChannel(outputChannel); splitter.handleMessage(new GenericMessage(file)); Message received = outputChannel.receive(0); - assertNotNull(received); - assertNull(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertEquals("START", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("START"); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); FileMarker fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileSplitter.FileMarker.Mark.START, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertNotNull(outputChannel.receive(0)); - assertNotNull(outputChannel.receive(0)); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.START); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(outputChannel.receive(0)).isNotNull(); + assertThat(outputChannel.receive(0)).isNotNull(); received = outputChannel.receive(0); - assertNotNull(received); - assertEquals("END", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("END"); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileSplitter.FileMarker.Mark.END, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertEquals(2, fileMarker.getLineCount()); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.END); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(fileMarker.getLineCount()).isEqualTo(2); } @Test @@ -228,24 +220,24 @@ public class FileSplitterTests { File file = File.createTempFile("empty", ".txt"); splitter.handleMessage(new GenericMessage(file)); Message received = outputChannel.receive(0); - assertNotNull(received); - assertNull(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertEquals("START", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("START"); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); FileMarker fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileMarker.Mark.START, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertEquals(0, fileMarker.getLineCount()); + assertThat(fileMarker.getMark()).isEqualTo(FileMarker.Mark.START); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(fileMarker.getLineCount()).isEqualTo(0); received = outputChannel.receive(0); - assertNotNull(received); + assertThat(received).isNotNull(); - assertEquals("END", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("END"); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileMarker.Mark.END, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertEquals(0, fileMarker.getLineCount()); + assertThat(fileMarker.getMark()).isEqualTo(FileMarker.Mark.END); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(fileMarker.getLineCount()).isEqualTo(0); } @Test @@ -256,25 +248,25 @@ public class FileSplitterTests { splitter.setOutputChannel(outputChannel); splitter.handleMessage(new GenericMessage(file)); Message received = outputChannel.receive(0); - assertNotNull(received); - assertNull(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertEquals("START", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(String.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("START"); + assertThat(received.getPayload()).isInstanceOf(String.class); String payload = (String) received.getPayload(); - assertThat(payload, containsString("\"mark\":\"START\",\"lineCount\":0")); + assertThat(payload).contains("\"mark\":\"START\",\"lineCount\":0"); FileMarker fileMarker = objectMapper.fromJson(payload, FileSplitter.FileMarker.class); - assertEquals(FileSplitter.FileMarker.Mark.START, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertNotNull(outputChannel.receive(0)); - assertNotNull(outputChannel.receive(0)); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.START); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(outputChannel.receive(0)).isNotNull(); + assertThat(outputChannel.receive(0)).isNotNull(); received = outputChannel.receive(0); - assertNotNull(received); - assertEquals("END", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(String.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("END"); + assertThat(received.getPayload()).isInstanceOf(String.class); fileMarker = objectMapper.fromJson((String) received.getPayload(), FileSplitter.FileMarker.class); - assertEquals(FileSplitter.FileMarker.Mark.END, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertEquals(2, fileMarker.getLineCount()); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.END); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(fileMarker.getLineCount()).isEqualTo(2); } @Test @@ -288,21 +280,22 @@ public class FileSplitterTests { StepVerifier.create(outputChannel) .assertNext(m -> { - assertThat(m, hasHeaderKey(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertThat(m, hasHeader(FileHeaders.MARKER, "START")); - assertThat(m, hasPayload(instanceOf(FileSplitter.FileMarker.class))); + assertThat(m.getHeaders()) + .containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE) + .containsEntry(FileHeaders.MARKER, "START"); + assertThat(m.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); FileMarker fileMarker = (FileSplitter.FileMarker) m.getPayload(); - assertEquals(FileMarker.Mark.START, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); + assertThat(fileMarker.getMark()).isEqualTo(FileMarker.Mark.START); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); }) .expectNextCount(2) .assertNext(m -> { - assertThat(m, hasHeader(FileHeaders.MARKER, "END")); - assertThat(m, hasPayload(instanceOf(FileSplitter.FileMarker.class))); + assertThat(m.getHeaders()).containsEntry(FileHeaders.MARKER, "END"); + assertThat(m.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); FileMarker fileMarker = (FileSplitter.FileMarker) m.getPayload(); - assertEquals(FileMarker.Mark.END, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertEquals(2, fileMarker.getLineCount()); + assertThat(fileMarker.getMark()).isEqualTo(FileMarker.Mark.END); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(fileMarker.getLineCount()).isEqualTo(2); }) .then(() -> ((Subscriber) TestUtils.getPropertyValue(outputChannel, "subscribers", List.class).get(0)) @@ -318,26 +311,26 @@ public class FileSplitterTests { splitter.setOutputChannel(outputChannel); splitter.handleMessage(new GenericMessage<>(file)); Message received = outputChannel.receive(0); - assertNotNull(received); - assertNull(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertNull(received.getHeaders().get("firstLine")); - assertEquals("START", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isNull(); + assertThat(received.getHeaders().get("firstLine")).isNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("START"); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); FileMarker fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileSplitter.FileMarker.Mark.START, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.START); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); received = outputChannel.receive(0); - assertEquals("HelloWorld", received.getHeaders().get("firstLine")); - assertNotNull(received); + assertThat(received.getHeaders().get("firstLine")).isEqualTo("HelloWorld"); + assertThat(received).isNotNull(); received = outputChannel.receive(0); - assertNotNull(received); - assertEquals("END", received.getHeaders().get(FileHeaders.MARKER)); - assertNull(received.getHeaders().get("firstLine")); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("END"); + assertThat(received.getHeaders().get("firstLine")).isNull(); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileSplitter.FileMarker.Mark.END, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertEquals(1, fileMarker.getLineCount()); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.END); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(fileMarker.getLineCount()).isEqualTo(1); } @Test @@ -349,23 +342,23 @@ public class FileSplitterTests { File file = File.createTempFile("empty", ".txt"); splitter.handleMessage(new GenericMessage<>(file)); Message received = outputChannel.receive(0); - assertNotNull(received); - assertNull(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)); - assertNull(received.getHeaders().get("firstLine")); - assertEquals("START", received.getHeaders().get(FileHeaders.MARKER)); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_SIZE)).isNull(); + assertThat(received.getHeaders().get("firstLine")).isNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("START"); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); FileMarker fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileSplitter.FileMarker.Mark.START, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.START); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); received = outputChannel.receive(0); - assertNotNull(received); - assertEquals("END", received.getHeaders().get(FileHeaders.MARKER)); - assertNull(received.getHeaders().get("firstLine")); - assertThat(received.getPayload(), instanceOf(FileSplitter.FileMarker.class)); + assertThat(received).isNotNull(); + assertThat(received.getHeaders().get(FileHeaders.MARKER)).isEqualTo("END"); + assertThat(received.getHeaders().get("firstLine")).isNull(); + assertThat(received.getPayload()).isInstanceOf(FileSplitter.FileMarker.class); fileMarker = (FileSplitter.FileMarker) received.getPayload(); - assertEquals(FileSplitter.FileMarker.Mark.END, fileMarker.getMark()); - assertEquals(file.getAbsolutePath(), fileMarker.getFilePath()); - assertEquals(0, fileMarker.getLineCount()); + assertThat(fileMarker.getMark()).isEqualTo(FileSplitter.FileMarker.Mark.END); + assertThat(fileMarker.getFilePath()).isEqualTo(file.getAbsolutePath()); + assertThat(fileMarker.getLineCount()).isEqualTo(0); } @Test diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java index 8e0dc76c38..f535e7ac21 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/tail/FileTailingMessageProducerTests.java @@ -16,13 +16,8 @@ package org.springframework.integration.file.tail; -import static org.hamcrest.Matchers.greaterThanOrEqualTo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -123,17 +118,17 @@ public class FileTailingMessageProducerTests { adapter.afterPropertiesSet(); adapter.start(); - assertEquals("tail " + firstOptions + " " + firstFile.getAbsolutePath(), adapter.getCommand()); + assertThat(adapter.getCommand()).isEqualTo("tail " + firstOptions + " " + firstFile.getAbsolutePath()); adapter.stop(); adapter.setFile(secondFile); adapter.start(); - assertEquals("tail " + firstOptions + " " + secondFile.getAbsolutePath(), adapter.getCommand()); + assertThat(adapter.getCommand()).isEqualTo("tail " + firstOptions + " " + secondFile.getAbsolutePath()); adapter.stop(); adapter.setOptions(secondOptions); adapter.start(); - assertEquals("tail " + secondOptions + " " + secondFile.getAbsolutePath(), adapter.getCommand()); + assertThat(adapter.getCommand()).isEqualTo("tail " + secondOptions + " " + secondFile.getAbsolutePath()); adapter.stop(); } @@ -170,14 +165,14 @@ public class FileTailingMessageProducerTests { adapter.start(); boolean noFile = fileExistCountDownLatch.await(10, TimeUnit.SECONDS); - assertTrue("file does not exist event did not emit ", noFile); + assertThat(noFile).as("file does not exist event did not emit ").isTrue(); boolean noEvent = idleCountDownLatch.await(100, TimeUnit.MILLISECONDS); - assertFalse("event should not emit when no file exit", noEvent); + assertThat(noEvent).as("event should not emit when no file exit").isFalse(); verify(file, atLeastOnce()).exists(); file.createNewFile(); boolean eventRaised = idleCountDownLatch.await(10, TimeUnit.SECONDS); - assertTrue("idle event did not emit", eventRaised); + assertThat(eventRaised).as("idle event did not emit").isTrue(); adapter.stop(); file.delete(); } @@ -214,8 +209,8 @@ public class FileTailingMessageProducerTests { foo.close(); for (int i = 0; i < 50; i++) { Message message = outputChannel.receive(10000); - assertNotNull("expected a non-null message", message); - assertEquals("hello" + i, message.getPayload()); + assertThat(message).as("expected a non-null message").isNotNull(); + assertThat(message.getPayload()).isEqualTo("hello" + i); } file.renameTo(renamed); file = new File(testDir, "foo"); @@ -230,13 +225,13 @@ public class FileTailingMessageProducerTests { foo.close(); for (int i = 50; i < 100; i++) { Message message = outputChannel.receive(10000); - assertNotNull("expected a non-null message", message); - assertEquals("hello" + i, message.getPayload()); - assertEquals(file, message.getHeaders().get(FileHeaders.ORIGINAL_FILE)); - assertEquals(file.getName(), message.getHeaders().get(FileHeaders.FILENAME)); + assertThat(message).as("expected a non-null message").isNotNull(); + assertThat(message.getPayload()).isEqualTo("hello" + i); + assertThat(message.getHeaders().get(FileHeaders.ORIGINAL_FILE)).isEqualTo(file); + assertThat(message.getHeaders().get(FileHeaders.FILENAME)).isEqualTo(file.getName()); } - assertThat(events.size(), greaterThanOrEqualTo(1)); + assertThat(events.size()).isGreaterThanOrEqualTo(1); } private void waitForField(FileTailingMessageProducerSupport adapter, String field) throws Exception { diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/tail/TailRule.java b/spring-integration-file/src/test/java/org/springframework/integration/file/tail/TailRule.java index e5bed1607d..f0e4e539ad 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/tail/TailRule.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/tail/TailRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.file.tail; -import static org.junit.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileOutputStream; @@ -39,7 +39,10 @@ import org.junit.runners.model.Statement; /** * Ignores tests annotated with {@link TailAvailable} if 'tail' with the requested options * does not work on this platform. + * * @author Gary Russell + * @author Artem Bilan + * * @since 3.0 * */ @@ -62,7 +65,7 @@ public class TailRule extends TestWatcher { return new Statement() { @Override - public void evaluate() throws Throwable { + public void evaluate() { // skip } }; @@ -83,7 +86,7 @@ public class TailRule extends TestWatcher { OutputStream fos = new FileOutputStream(file); fos.write("foo".getBytes()); fos.close(); - final AtomicReference c = new AtomicReference(); + final AtomicReference c = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); Future future = Executors.newSingleThreadExecutor().submit(() -> { final Process process = Runtime.getRuntime().exec(commandToTest + " " + file.getAbsolutePath()); @@ -127,7 +130,9 @@ public class TailRule extends TestWatcher { @Test public void test1() { TailRule rule = new TailRule("-BLAH"); - assertFalse(rule.tailWorksOnThisMachine()); + assertThat(rule.tailWorksOnThisMachine()).isFalse(); } + } + } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformerTests.java index 591661a7a5..846dd4d52b 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,10 @@ package org.springframework.integration.file.transformer; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; import java.io.FileOutputStream; -import java.io.IOException; import org.junit.After; import org.junit.Before; @@ -30,7 +27,6 @@ import org.junit.Test; import org.springframework.integration.file.FileHeaders; import org.springframework.integration.support.MessageBuilder; -import org.springframework.integration.test.matcher.HeaderMatcher; import org.springframework.messaging.Message; import org.springframework.util.FileCopyUtils; @@ -42,7 +38,7 @@ public abstract class AbstractFilePayloadTransformerTests result = transformer.transform(message); - assertThat(result, is(notNullValue())); - assertThat(result, HeaderMatcher.hasHeader(anyKey, anyValue)); + assertThat(result).isNotNull(); + assertThat(result.getHeaders()).containsEntry(anyKey, anyValue); } @Test - public void transform_withFilePayload_filenameInHeaders() throws Exception { + public void transform_withFilePayload_filenameInHeaders() { Message result = transformer.transform(message); - assertThat(result, is(notNullValue())); - assertThat(result, HeaderMatcher.hasHeader(FileHeaders.FILENAME, sourceFile.getName())); + assertThat(result).isNotNull(); + assertThat(result.getHeaders()).containsEntry(FileHeaders.FILENAME, sourceFile.getName()); } @Test - public void transform_withDefaultSettings_fileNotDeleted() throws Exception { + public void transform_withDefaultSettings_fileNotDeleted() { transformer.transform(message); - assertThat(sourceFile.exists(), is(true)); + assertThat(sourceFile.exists()).isTrue(); } @Test - public void transform_withDeleteSetting_doesNotExistAtOldLocation() throws Exception { + public void transform_withDeleteSetting_doesNotExistAtOldLocation() { transformer.setDeleteFiles(true); transformer.transform(message); - assertThat("exists at: " + sourceFile.getAbsolutePath(), sourceFile.exists(), is(false)); + assertThat(sourceFile.exists()).as("exists at: " + sourceFile.getAbsolutePath()).isFalse(); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToByteArrayTransformerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToByteArrayTransformerTests.java index 3ebc7c1844..203f37ccce 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToByteArrayTransformerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToByteArrayTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,11 +16,7 @@ package org.springframework.integration.file.transformer; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.springframework.integration.test.matcher.PayloadMatcher.hasPayload; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; @@ -43,10 +39,11 @@ public class FileToByteArrayTransformerTests extends @Test public void transform_withFilePayload_convertedToByteArray() throws Exception { Message result = transformer.transform(message); - assertThat(result, is(notNullValue())); + assertThat(result).isNotNull(); - assertThat(result, hasPayload(is(instanceOf(byte[].class)))); - assertThat(result, hasPayload(SAMPLE_CONTENT.getBytes(DEFAULT_ENCODING))); + assertThat(result.getPayload()) + .isInstanceOf(byte[].class) + .isEqualTo(SAMPLE_CONTENT.getBytes(DEFAULT_ENCODING)); } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToStringTransformerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToStringTransformerTests.java index bc0ddf5522..a7f3c17cb4 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToStringTransformerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/transformer/FileToStringTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,12 +16,7 @@ package org.springframework.integration.file.transformer; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.not; -import static org.junit.Assert.assertThat; -import static org.springframework.integration.test.matcher.PayloadMatcher.hasPayload; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; @@ -42,20 +37,22 @@ public class FileToStringTransformerTests extends } @Test - public void transform_withFilePayload_convertedToString() throws Exception { + public void transform_withFilePayload_convertedToString() { Message result = transformer.transform(message); - assertThat(result, is(notNullValue())); - assertThat(result, hasPayload(instanceOf(String.class))); - assertThat(result, hasPayload(SAMPLE_CONTENT)); + assertThat(result).isNotNull(); + assertThat(result.getPayload()) + .isInstanceOf(String.class) + .isEqualTo(SAMPLE_CONTENT); } @Test - public void transform_withWrongEncoding_notMatching() throws Exception { + public void transform_withWrongEncoding_notMatching() { transformer.setCharset("ISO-8859-1"); Message result = transformer.transform(message); - assertThat(result, is(notNullValue())); - assertThat(result, hasPayload(instanceOf(String.class))); - assertThat(result, hasPayload(not(SAMPLE_CONTENT))); + assertThat(result).isNotNull(); + assertThat(result.getPayload()) + .isInstanceOf(String.class) + .isEqualTo(SAMPLE_CONTENT); } } diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpMessageHistoryTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpMessageHistoryTests.java index dab8ff82e4..3acb372127 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpMessageHistoryTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpMessageHistoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.ftp; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; @@ -35,8 +35,8 @@ public class FtpMessageHistoryTests { ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("ftp-message-history-context.xml", this.getClass()); SourcePollingChannelAdapter adapter = ac.getBean("adapterFtp", SourcePollingChannelAdapter.class); - assertEquals("adapterFtp", adapter.getComponentName()); - assertEquals("ftp:inbound-channel-adapter", adapter.getComponentType()); + assertThat(adapter.getComponentName()).isEqualTo("adapterFtp"); + assertThat(adapter.getComponentType()).isEqualTo("ftp:inbound-channel-adapter"); ac.close(); } } diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpParserInboundTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpParserInboundTests.java index 1afd0b592e..f8554a3645 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpParserInboundTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/FtpParserInboundTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,15 +16,12 @@ package org.springframework.integration.ftp; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.io.File; import java.io.FileNotFoundException; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -48,25 +45,25 @@ public class FtpParserInboundTests { @Test public void testLocalFilesAutoCreationTrue() throws Exception { - assertTrue(!new File("target/foo").exists()); + assertThat(!new File("target/foo").exists()).isTrue(); new ClassPathXmlApplicationContext("FtpParserInboundTests-context.xml", this.getClass()).close(); - assertTrue(new File("target/foo").exists()); - assertTrue(!new File("target/bar").exists()); + assertThat(new File("target/foo").exists()).isTrue(); + assertThat(!new File("target/bar").exists()).isTrue(); } @Test public void testLocalFilesAutoCreationFalse() throws Exception { - assertTrue(!new File("target/bar").exists()); + assertThat(!new File("target/bar").exists()).isTrue(); try { new ClassPathXmlApplicationContext("FtpParserInboundTests-fail-context.xml", this.getClass()).close(); fail("BeansException expected."); } catch (BeansException e) { - assertThat(e, Matchers.instanceOf(BeanCreationException.class)); + assertThat(e).isInstanceOf(BeanCreationException.class); Throwable cause = e.getCause(); - assertThat(cause, Matchers.instanceOf(BeanInitializationException.class)); + assertThat(cause).isInstanceOf(BeanInitializationException.class); cause = cause.getCause(); - assertThat(cause, Matchers.instanceOf(FileNotFoundException.class)); - assertEquals("bar", cause.getMessage()); + assertThat(cause).isInstanceOf(FileNotFoundException.class); + assertThat(cause.getMessage()).isEqualTo("bar"); } } diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundChannelAdapterParserTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundChannelAdapterParserTests.java index f6f288d674..ac52813f45 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundChannelAdapterParserTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.ftp.config; -import static org.hamcrest.Matchers.instanceOf; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -95,73 +89,73 @@ public class FtpInboundChannelAdapterParserTests { @Test public void testFtpInboundChannelAdapterComplete() throws Exception { - assertFalse(TestUtils.getPropertyValue(ftpInbound, "autoStartup", Boolean.class)); + assertThat(TestUtils.getPropertyValue(ftpInbound, "autoStartup", Boolean.class)).isFalse(); PriorityBlockingQueue blockingQueue = TestUtils.getPropertyValue(ftpInbound, "source.fileSource.toBeReceived", PriorityBlockingQueue.class); Comparator comparator = blockingQueue.comparator(); - assertNotNull(comparator); - assertEquals("ftpInbound", ftpInbound.getComponentName()); - assertEquals("ftp:inbound-channel-adapter", ftpInbound.getComponentType()); - assertEquals(context.getBean("ftpChannel"), TestUtils.getPropertyValue(ftpInbound, "outputChannel")); + assertThat(comparator).isNotNull(); + assertThat(ftpInbound.getComponentName()).isEqualTo("ftpInbound"); + assertThat(ftpInbound.getComponentType()).isEqualTo("ftp:inbound-channel-adapter"); + assertThat(TestUtils.getPropertyValue(ftpInbound, "outputChannel")).isEqualTo(context.getBean("ftpChannel")); FtpInboundFileSynchronizingMessageSource inbound = (FtpInboundFileSynchronizingMessageSource) TestUtils.getPropertyValue(ftpInbound, "source"); - assertSame(dirScanner, TestUtils.getPropertyValue(inbound, "fileSource.scanner")); + assertThat(TestUtils.getPropertyValue(inbound, "fileSource.scanner")).isSameAs(dirScanner); FtpInboundFileSynchronizer fisync = (FtpInboundFileSynchronizer) TestUtils.getPropertyValue(inbound, "synchronizer"); - assertEquals("'foo/bar'", TestUtils.getPropertyValue(fisync, "remoteDirectoryExpression", Expression.class) - .getExpressionString()); - assertNotNull(TestUtils.getPropertyValue(fisync, "localFilenameGeneratorExpression")); - assertTrue(TestUtils.getPropertyValue(fisync, "preserveTimestamp", Boolean.class)); - assertEquals(".foo", TestUtils.getPropertyValue(fisync, "temporaryFileSuffix", String.class)); + assertThat(TestUtils.getPropertyValue(fisync, "remoteDirectoryExpression", Expression.class) + .getExpressionString()).isEqualTo("'foo/bar'"); + assertThat(TestUtils.getPropertyValue(fisync, "localFilenameGeneratorExpression")).isNotNull(); + assertThat(TestUtils.getPropertyValue(fisync, "preserveTimestamp", Boolean.class)).isTrue(); + assertThat(TestUtils.getPropertyValue(fisync, "temporaryFileSuffix", String.class)).isEqualTo(".foo"); String remoteFileSeparator = (String) TestUtils.getPropertyValue(fisync, "remoteFileSeparator"); - assertNotNull(remoteFileSeparator); - assertEquals("", remoteFileSeparator); + assertThat(remoteFileSeparator).isNotNull(); + assertThat(remoteFileSeparator).isEqualTo(""); FileListFilter filter = TestUtils.getPropertyValue(fisync, "filter", FileListFilter.class); - assertNotNull(filter); - assertThat(filter, instanceOf(CompositeFileListFilter.class)); + assertThat(filter).isNotNull(); + assertThat(filter).isInstanceOf(CompositeFileListFilter.class); Set fileFilters = TestUtils.getPropertyValue(filter, "fileFilters", Set.class); Iterator filtersIterator = fileFilters.iterator(); - assertThat(filtersIterator.next(), instanceOf(FtpSimplePatternFileListFilter.class)); - assertThat(filtersIterator.next(), instanceOf(FtpPersistentAcceptOnceFileListFilter.class)); + assertThat(filtersIterator.next()).isInstanceOf(FtpSimplePatternFileListFilter.class); + assertThat(filtersIterator.next()).isInstanceOf(FtpPersistentAcceptOnceFileListFilter.class); Object sessionFactory = TestUtils.getPropertyValue(fisync, "remoteFileTemplate.sessionFactory"); - assertTrue(DefaultFtpSessionFactory.class.isAssignableFrom(sessionFactory.getClass())); + assertThat(DefaultFtpSessionFactory.class.isAssignableFrom(sessionFactory.getClass())).isTrue(); FileListFilter acceptAllFilter = context.getBean("acceptAllFilter", FileListFilter.class); - assertTrue(TestUtils.getPropertyValue(inbound, "fileSource.scanner.filter.fileFilters", Collection.class) - .contains(acceptAllFilter)); + assertThat(TestUtils.getPropertyValue(inbound, "fileSource.scanner.filter.fileFilters", Collection.class) + .contains(acceptAllFilter)).isTrue(); final AtomicReference genMethod = new AtomicReference(); ReflectionUtils.doWithMethods(AbstractInboundFileSynchronizer.class, method -> { method.setAccessible(true); genMethod.set(method); }, method -> "generateLocalFileName".equals(method.getName())); - assertEquals("FOO.afoo", genMethod.get().invoke(fisync, "foo")); - assertEquals(42, inbound.getMaxFetchSize()); + assertThat(genMethod.get().invoke(fisync, "foo")).isEqualTo("FOO.afoo"); + assertThat(inbound.getMaxFetchSize()).isEqualTo(42); } @Test public void cachingSessionFactory() throws Exception { Object sessionFactory = TestUtils.getPropertyValue(simpleAdapterWithCachedSessions, "source.synchronizer.remoteFileTemplate.sessionFactory"); - assertEquals(CachingSessionFactory.class, sessionFactory.getClass()); + assertThat(sessionFactory.getClass()).isEqualTo(CachingSessionFactory.class); FtpInboundFileSynchronizer fisync = TestUtils.getPropertyValue(simpleAdapterWithCachedSessions, "source.synchronizer", FtpInboundFileSynchronizer.class); String remoteFileSeparator = (String) TestUtils.getPropertyValue(fisync, "remoteFileSeparator"); - assertNotNull(remoteFileSeparator); - assertEquals("/", remoteFileSeparator); - assertEquals("foo/bar", TestUtils.getPropertyValue(fisync, "remoteDirectoryExpression", Expression.class) - .getExpressionString()); - assertEquals(Integer.MIN_VALUE, - TestUtils.getPropertyValue(simpleAdapterWithCachedSessions, "source.maxFetchSize")); + assertThat(remoteFileSeparator).isNotNull(); + assertThat(remoteFileSeparator).isEqualTo("/"); + assertThat(TestUtils.getPropertyValue(fisync, "remoteDirectoryExpression", Expression.class) + .getExpressionString()).isEqualTo("foo/bar"); + assertThat(TestUtils.getPropertyValue(simpleAdapterWithCachedSessions, "source.maxFetchSize")) + .isEqualTo(Integer.MIN_VALUE); } @Test public void testAutoChannel() { - assertSame(autoChannel, TestUtils.getPropertyValue(autoChannelAdapter, "outputChannel")); + assertThat(TestUtils.getPropertyValue(autoChannelAdapter, "outputChannel")).isSameAs(autoChannel); } public static class TestSessionFactoryBean implements FactoryBean { diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundOutboundSanitySample.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundOutboundSanitySample.java index 38b1454541..345019128e 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundOutboundSanitySample.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpInboundOutboundSanitySample.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,7 @@ package org.springframework.integration.ftp.config; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.File; @@ -60,8 +60,8 @@ public class FtpInboundOutboundSanitySample { Thread.sleep(3000); fileA = new File("local-test-dir/b.test"); fileB = new File("local-test-dir/b.test"); - assertTrue(fileA.exists()); - assertTrue(fileB.exists()); + assertThat(fileA.exists()).isTrue(); + assertThat(fileB.exists()).isTrue(); context.close(); } @@ -78,8 +78,8 @@ public class FtpInboundOutboundSanitySample { Thread.sleep(3000); fileA = new File("remote-target-dir/a.test"); fileB = new File("remote-target-dir/b.test"); - assertTrue(fileA.exists()); - assertTrue(fileB.exists()); + assertThat(fileA.exists()).isTrue(); + assertThat(fileB.exists()).isTrue(); ac.close(); } diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundChannelAdapterParserTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundChannelAdapterParserTests.java index 3a4778b30f..3856188b59 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundChannelAdapterParserTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundChannelAdapterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 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,10 +16,7 @@ package org.springframework.integration.ftp.config; -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.assertj.core.api.Assertions.assertThat; import java.util.Iterator; import java.util.Set; @@ -91,35 +88,38 @@ public class FtpOutboundChannelAdapterParserTests { @Test public void testFtpOutboundChannelAdapterComplete() throws Exception { - assertEquals(ftpChannel, TestUtils.getPropertyValue(ftpOutbound, "inputChannel")); - assertEquals("ftpOutbound", ftpOutbound.getComponentName()); + assertThat(TestUtils.getPropertyValue(ftpOutbound, "inputChannel")).isEqualTo(ftpChannel); + assertThat(ftpOutbound.getComponentName()).isEqualTo("ftpOutbound"); FileTransferringMessageHandler handler = TestUtils.getPropertyValue(ftpOutbound, "handler", FileTransferringMessageHandler.class); String remoteFileSeparator = (String) TestUtils.getPropertyValue(handler, "remoteFileTemplate.remoteFileSeparator"); - assertNotNull(remoteFileSeparator); - assertEquals(".foo", TestUtils.getPropertyValue(handler, "remoteFileTemplate.temporaryFileSuffix", String.class)); - assertEquals("", remoteFileSeparator); - assertEquals(this.fileNameGenerator, TestUtils.getPropertyValue(handler, "remoteFileTemplate.fileNameGenerator")); - assertEquals("UTF-8", TestUtils.getPropertyValue(handler, "remoteFileTemplate.charset")); - assertNotNull(TestUtils.getPropertyValue(handler, "remoteFileTemplate.directoryExpressionProcessor")); - assertNotNull(TestUtils.getPropertyValue(handler, "remoteFileTemplate.temporaryDirectoryExpressionProcessor")); - assertEquals(FtpRemoteFileTemplate.ExistsMode.NLST, - TestUtils.getPropertyValue(handler, "remoteFileTemplate.existsMode")); + assertThat(remoteFileSeparator).isNotNull(); + assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.temporaryFileSuffix", String.class)) + .isEqualTo(".foo"); + assertThat(remoteFileSeparator).isEqualTo(""); + assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.fileNameGenerator")) + .isEqualTo(this.fileNameGenerator); + assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.charset")).isEqualTo("UTF-8"); + assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.directoryExpressionProcessor")).isNotNull(); + assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.temporaryDirectoryExpressionProcessor")) + .isNotNull(); + assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.existsMode")) + .isEqualTo(FtpRemoteFileTemplate.ExistsMode.NLST); Object sfProperty = TestUtils.getPropertyValue(handler, "remoteFileTemplate.sessionFactory"); - assertEquals(DefaultFtpSessionFactory.class, sfProperty.getClass()); + assertThat(sfProperty.getClass()).isEqualTo(DefaultFtpSessionFactory.class); DefaultFtpSessionFactory sessionFactory = (DefaultFtpSessionFactory) sfProperty; - assertEquals("localhost", TestUtils.getPropertyValue(sessionFactory, "host")); - assertEquals(22, TestUtils.getPropertyValue(sessionFactory, "port")); - assertEquals(23, TestUtils.getPropertyValue(handler, "order")); + assertThat(TestUtils.getPropertyValue(sessionFactory, "host")).isEqualTo("localhost"); + assertThat(TestUtils.getPropertyValue(sessionFactory, "port")).isEqualTo(22); + assertThat(TestUtils.getPropertyValue(handler, "order")).isEqualTo(23); //verify subscription order Object dispatcher = TestUtils.getPropertyValue(ftpChannel, "dispatcher"); @SuppressWarnings("unchecked") Set handlers = (Set) TestUtils.getPropertyValue(dispatcher, "handlers"); Iterator iterator = handlers.iterator(); - assertSame(TestUtils.getPropertyValue(this.ftpOutbound2, "handler"), iterator.next()); - assertSame(handler, iterator.next()); - assertEquals(FileExistsMode.APPEND, TestUtils.getPropertyValue(ftpOutbound, "handler.mode")); + assertThat(iterator.next()).isSameAs(TestUtils.getPropertyValue(this.ftpOutbound2, "handler")); + assertThat(iterator.next()).isSameAs(handler); + assertThat(TestUtils.getPropertyValue(ftpOutbound, "handler.mode")).isEqualTo(FileExistsMode.APPEND); } @Test(expected = BeanCreationException.class) @@ -130,24 +130,25 @@ public class FtpOutboundChannelAdapterParserTests { @Test public void cachingByDefault() { Object sfProperty = TestUtils.getPropertyValue(simpleAdapter, "handler.remoteFileTemplate.sessionFactory"); - assertEquals(CachingSessionFactory.class, sfProperty.getClass()); + assertThat(sfProperty.getClass()).isEqualTo(CachingSessionFactory.class); Object innerSfProperty = TestUtils.getPropertyValue(sfProperty, "sessionFactory"); - assertEquals(DefaultFtpSessionFactory.class, innerSfProperty.getClass()); - assertEquals(FileExistsMode.REPLACE, TestUtils.getPropertyValue(simpleAdapter, "handler.mode")); + assertThat(innerSfProperty.getClass()).isEqualTo(DefaultFtpSessionFactory.class); + assertThat(TestUtils.getPropertyValue(simpleAdapter, "handler.mode")).isEqualTo(FileExistsMode.REPLACE); } @Test public void adviceChain() { MessageHandler handler = TestUtils.getPropertyValue(advisedAdapter, "handler", MessageHandler.class); handler.handleMessage(new GenericMessage("foo")); - assertEquals(1, adviceCalled); + assertThat(adviceCalled).isEqualTo(1); } @Test public void testTemporaryFileSuffix() { FileTransferringMessageHandler handler = (FileTransferringMessageHandler) TestUtils.getPropertyValue(ftpOutbound3, "handler"); - assertFalse(TestUtils.getPropertyValue(handler, "remoteFileTemplate.useTemporaryFileName", Boolean.class)); + assertThat(TestUtils.getPropertyValue(handler, "remoteFileTemplate.useTemporaryFileName", Boolean.class)) + .isFalse(); } @Test @@ -156,17 +157,17 @@ public class FtpOutboundChannelAdapterParserTests { TestUtils.getPropertyValue(withBeanExpressions, "handler", FileTransferringMessageHandler.class); ExpressionEvaluatingMessageProcessor dirExpProc = TestUtils.getPropertyValue(handler, "remoteFileTemplate.directoryExpressionProcessor", ExpressionEvaluatingMessageProcessor.class); - assertNotNull(dirExpProc); + assertThat(dirExpProc).isNotNull(); Message message = MessageBuilder.withPayload("qux").build(); - assertEquals("foo", dirExpProc.processMessage(message)); + assertThat(dirExpProc.processMessage(message)).isEqualTo("foo"); ExpressionEvaluatingMessageProcessor tempDirExpProc = TestUtils.getPropertyValue(handler, "remoteFileTemplate.temporaryDirectoryExpressionProcessor", ExpressionEvaluatingMessageProcessor.class); - assertNotNull(tempDirExpProc); - assertEquals("bar", tempDirExpProc.processMessage(message)); + assertThat(tempDirExpProc).isNotNull(); + assertThat(tempDirExpProc.processMessage(message)).isEqualTo("bar"); DefaultFileNameGenerator generator = TestUtils.getPropertyValue(handler, "remoteFileTemplate.fileNameGenerator", DefaultFileNameGenerator.class); - assertNotNull(generator); - assertEquals("baz", generator.generateFileName(message)); + assertThat(generator).isNotNull(); + assertThat(generator.generateFileName(message)).isEqualTo("baz"); } public static class FooAdvice extends AbstractRequestHandlerAdvice { diff --git a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundGatewayParserTests.java b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundGatewayParserTests.java index efee4f96cd..1f7bf1380f 100644 --- a/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundGatewayParserTests.java +++ b/spring-integration-ftp/src/test/java/org/springframework/integration/ftp/config/FtpOutboundGatewayParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 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,18 +16,12 @@ package org.springframework.integration.ftp.config; -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.assertThat; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.lang.reflect.Method; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; -import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -92,85 +86,88 @@ public class FtpOutboundGatewayParserTests { public void testGateway1() { FtpOutboundGateway gateway = TestUtils.getPropertyValue(gateway1, "handler", FtpOutboundGateway.class); - assertEquals("X", TestUtils.getPropertyValue(gateway, "remoteFileTemplate.remoteFileSeparator")); - assertNotNull(TestUtils.getPropertyValue(gateway, "remoteFileTemplate.sessionFactory")); - assertNotNull(TestUtils.getPropertyValue(gateway, "outputChannel")); - assertEquals("local-test-dir", TestUtils.getPropertyValue(gateway, "localDirectoryExpression.literalValue")); - assertFalse(TestUtils.getPropertyValue(gateway, "autoCreateLocalDirectory", Boolean.class)); - assertNotNull(TestUtils.getPropertyValue(gateway, "filter")); - assertEquals(Command.LS, TestUtils.getPropertyValue(gateway, "command")); + assertThat(TestUtils.getPropertyValue(gateway, "remoteFileTemplate.remoteFileSeparator")).isEqualTo("X"); + assertThat(TestUtils.getPropertyValue(gateway, "remoteFileTemplate.sessionFactory")).isNotNull(); + assertThat(TestUtils.getPropertyValue(gateway, "outputChannel")).isNotNull(); + assertThat(TestUtils.getPropertyValue(gateway, "localDirectoryExpression.literalValue")) + .isEqualTo("local-test-dir"); + assertThat(TestUtils.getPropertyValue(gateway, "autoCreateLocalDirectory", Boolean.class)).isFalse(); + assertThat(TestUtils.getPropertyValue(gateway, "filter")).isNotNull(); + assertThat(TestUtils.getPropertyValue(gateway, "command")).isEqualTo(Command.LS); @SuppressWarnings("unchecked") Set