From 05765d752062f37b202e7dfd20593c995dc47df0 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 4 Mar 2013 19:46:15 -0800 Subject: [PATCH] Replace EasyMock with Mockito Issue: SPR-10126 --- build.gradle | 8 - .../adapter/ThrowsAdviceInterceptorTests.java | 8 +- .../CustomizableTraceInterceptorTests.java | 11 +- .../interceptor/DebugInterceptorTests.java | 13 +- .../PerformanceMonitorInterceptorTests.java | 11 +- .../SimpleTraceInterceptorTests.java | 11 +- .../aop/scope/DefaultScopedObjectTests.java | 6 +- ...elegatingIntroductionInterceptorTests.java | 12 +- .../DefaultListableBeanFactoryTests.java | 26 +- .../config/CustomScopeConfigurerTests.java | 6 +- ...ObjectFactoryCreatingFactoryBeanTests.java | 12 +- .../ServiceLocatorFactoryBeanTests.java | 10 +- .../parsing/FailFastProblemReporterTests.java | 10 +- .../wiring/BeanConfigurerSupportTests.java | 5 +- .../scheduling/quartz/QuartzSupportTests.java | 20 +- .../aop/aspectj/AfterAdviceBindingTests.java | 9 +- .../AfterReturningAdviceBindingTests.java | 10 +- .../AfterThrowingAdviceBindingTests.java | 7 +- .../aop/aspectj/AroundAdviceBindingTests.java | 11 +- .../aop/aspectj/BeforeAdviceBindingTests.java | 9 +- .../MethodLocatingFactoryBeanTests.java | 12 +- .../aop/framework/JdkDynamicProxyTests.java | 8 +- .../ContextBeanFactoryReferenceTests.java | 9 +- .../EnableLoadTimeWeavingTests.java | 10 +- .../event/ApplicationContextEventTests.java | 12 +- .../EventPublicationInterceptorTests.java | 10 +- .../LocalSlsbInvokerInterceptorTests.java | 10 +- ...StatelessSessionProxyFactoryBeanTests.java | 11 +- ...mpleRemoteSlsbInvokerInterceptorTests.java | 9 +- ...StatelessSessionProxyFactoryBeanTests.java | 11 +- .../jndi/JndiObjectFactoryBeanTests.java | 9 +- .../jndi/JndiTemplateTests.java | 10 +- .../scripting/bsh/BshScriptFactoryTests.java | 7 +- .../groovy/GroovyScriptFactoryTests.java | 7 +- .../RefreshableScriptTargetSourceTests.java | 5 +- .../support/ResourceScriptSourceTests.java | 7 +- .../ScriptFactoryPostProcessorTests.java | 4 +- .../util/StreamUtilsTests.java | 12 +- .../xml/AbstractStaxXMLReaderTestCase.java | 10 +- .../util/xml/StaxEventXMLReaderTests.java | 8 +- .../util/xml/StaxStreamXMLReaderTests.java | 13 +- .../jdbc/core/AbstractRowMapperTests.java | 9 +- .../jdbc/core/JdbcTemplateQueryTests.java | 13 +- .../jdbc/core/JdbcTemplateTests.java | 27 +- .../jdbc/core/RowMapperTests.java | 9 +- .../jdbc/core/StatementCreatorUtilsTests.java | 8 +- .../NamedParameterJdbcTemplateTests.java | 7 +- .../namedparam/NamedParameterQueryTests.java | 12 +- .../core/simple/CallMetaDataContextTests.java | 9 +- .../jdbc/core/simple/SimpleJdbcCallTests.java | 15 +- .../core/simple/SimpleJdbcInsertTests.java | 8 +- .../core/simple/SimpleJdbcTemplateTests.java | 14 +- .../simple/TableMetaDataContextTests.java | 9 +- .../JdbcBeanDefinitionReaderTests.java | 10 +- .../core/support/JdbcDaoSupportTests.java | 8 +- .../jdbc/core/support/LobSupportTests.java | 11 +- .../jdbc/core/support/SqlLobValueTests.java | 14 +- .../DataSourceJtaTransactionTests.java | 18 +- .../DataSourceTransactionManagerTests.java | 11 +- .../datasource/DelegatingDataSourceTest.java | 12 +- .../DriverManagerDataSourceTests.java | 8 +- ...UserCredentialsDataSourceAdapterTests.java | 9 +- .../init/DatabasePopulatorTests.java | 9 +- .../BeanFactoryDataSourceLookupTests.java | 11 +- .../jdbc/object/BatchSqlUpdateTests.java | 12 +- .../jdbc/object/GenericSqlQueryTests.java | 10 +- .../object/GenericStoredProcedureTests.java | 10 +- .../jdbc/object/SqlQueryTests.java | 18 +- .../jdbc/object/SqlUpdateTests.java | 10 +- .../jdbc/object/StoredProcedureTests.java | 16 +- .../DataFieldMaxValueIncrementerTests.java | 11 +- .../jdbc/support/DefaultLobHandlerTests.java | 7 +- .../support/NativeJdbcExtractorTests.java | 9 +- .../support/SQLErrorCodesFactoryTests.java | 16 +- .../rowset/ResultSetWrappingRowSetTests.java | 10 +- .../jms/config/JmsNamespaceHandlerTests.java | 11 +- .../JmsTransactionManagerTests.java | 11 +- .../SingleConnectionFactoryTests.java | 11 +- .../jms/core/JmsTemplate102Tests.java | 12 +- .../jms/core/JmsTemplateTests.java | 13 +- .../core/support/JmsGatewaySupportTests.java | 6 +- .../SimpleMessageListenerContainerTests.java | 12 +- .../MessageListenerAdapter102Tests.java | 10 +- .../adapter/MessageListenerAdapterTests.java | 15 +- .../DefaultJmsActivationSpecFactoryTests.java | 5 +- .../jms/remoting/JmsInvokerTests.java | 9 +- .../SimpleMessageConverter102Tests.java | 12 +- .../support/SimpleMessageConverterTests.java | 11 +- .../MappingJackson2MessageConverterTests.java | 10 +- .../MappingJacksonMessageConverterTests.java | 10 +- .../MarshallingMessageConverterTests.java | 10 +- .../DynamicDestinationResolverTests.java | 5 +- .../JmsDestinationAccessorTests.java | 7 +- .../JndiDestinationResolverTests.java | 10 +- .../hibernate3/HibernateInterceptorTests.java | 15 +- .../HibernateJtaTransactionTests.java | 17 +- .../hibernate3/HibernateTemplateTests.java | 17 +- .../LocalSessionFactoryBeanTests.java | 10 +- .../support/HibernateDaoSupportTests.java | 6 +- .../orm/hibernate3/support/LobTypeTests.java | 8 +- .../support/OpenSessionInViewTests.java | 13 +- .../orm/ibatis/SqlMapClientTests.java | 10 +- .../ibatis/support/LobTypeHandlerTests.java | 10 +- .../orm/jdo/JdoInterceptorTests.java | 8 +- .../orm/jdo/JdoTemplateTests.java | 11 +- .../orm/jdo/JdoTransactionManagerTests.java | 5 +- .../LocalPersistenceManagerFactoryTests.java | 8 +- .../orm/jdo/support/JdoDaoSupportTests.java | 6 +- .../OpenPersistenceManagerInViewTests.java | 10 +- ...AbstractEntityManagerFactoryBeanTests.java | 8 +- .../orm/jpa/DefaultJpaDialectTests.java | 8 +- .../EntityManagerFactoryBeanSupportTests.java | 4 +- .../jpa/EntityManagerFactoryUtilsTests.java | 10 +- .../orm/jpa/JpaInterceptorTests.java | 12 +- .../orm/jpa/JpaTemplateTests.java | 11 +- .../orm/jpa/JpaTransactionManagerTests.java | 14 +- ...ontainerEntityManagerFactoryBeanTests.java | 16 +- .../LocalEntityManagerFactoryBeanTests.java | 7 +- .../orm/jpa/support/JpaDaoSupportTests.java | 8 +- .../support/OpenEntityManagerInViewTests.java | 14 +- .../support/PersistenceInjectionTests.java | 12 +- .../SharedEntityManagerFactoryTests.java | 11 +- .../oxm/castor/CastorMarshallerTests.java | 51 +- .../oxm/jaxb/Jaxb2MarshallerTests.java | 66 +- .../oxm/jaxb/Jaxb2UnmarshallerTests.java | 24 +- .../oxm/xstream/XStreamMarshallerTests.java | 51 +- .../web/struts/StrutsSupportTests.java | 32 +- .../web/servlet/DefaultMvcResultTests.java | 47 +- .../mock/web/MockFilterChainTests.java | 28 +- .../jca/cci/CciLocalTransactionTests.java | 103 +-- .../jca/cci/CciTemplateTests.java | 689 ++++++-------- .../jca/cci/EisOperationTests.java | 190 ++-- .../LocalConnectionFactoryBeanTests.java | 32 +- .../JndiJtaTransactionManagerTests.java | 99 +- .../JtaTransactionManagerTests.java | 851 +++++------------- .../AbstractTransactionAspectTests.java | 168 ++-- .../BeanFactoryTransactionTests.java | 25 +- .../WebSphereUowTransactionManagerTests.java | 25 +- ...aTransactionManagerSerializationTests.java | 10 +- .../http/MockHttpOutputMessage.java | 4 +- .../FormHttpMessageConverterTests.java | 5 +- .../MarshallingHttpMessageConverterTests.java | 26 +- .../remoting/jaxrpc/JaxRpcSupportTests.java | 127 +-- .../DefaultResponseErrorHandlerTests.java | 66 +- .../HttpMessageConverterExtractorTests.java | 86 +- .../web/client/RestTemplateTests.java | 600 ++++++------ .../ServletRequestAttributesTests.java | 27 +- .../request/async/DeferredResultTests.java | 37 +- .../StandardServletAsyncWebRequestTests.java | 24 +- .../request/async/WebAsyncManagerTests.java | 203 ++--- .../async/WebAsyncManagerTimeoutTests.java | 59 +- .../filter/CharacterEncodingFilterTests.java | 137 +-- .../ModelAttributeMethodProcessorTests.java | 39 +- .../method/annotation/ModelFactoryTests.java | 29 +- .../WebArgumentResolverAdapterTests.java | 58 +- .../ByteArrayMultipartFileEditorTests.java | 21 +- .../PortletRequestAttributesTests.java | 20 +- .../web/portlet/util/PortletUtilsTests.java | 102 +-- .../view/tiles3/TilesViewResolverTests.java | 24 +- .../servlet/view/tiles3/TilesViewTests.java | 26 +- .../web/servlet/DispatcherServletTests.java | 3 +- .../servlet/HandlerExecutionChainTests.java | 99 +- .../DelegatingWebMvcConfigurationTests.java | 98 +- .../web/servlet/mvc/ControllerTests.java | 47 +- .../HttpEntityMethodProcessorMockTests.java | 84 +- ...equestPartMethodArgumentResolverTests.java | 34 +- ...tResponseBodyMethodProcessorMockTests.java | 91 +- .../form/AbstractHtmlElementTagTests.java | 10 +- .../web/servlet/tags/form/FormTagTests.java | 13 +- .../web/servlet/view/BaseViewTests.java | 45 +- .../ContentNegotiatingViewResolverTests.java | 254 ++---- .../view/InternalResourceViewTests.java | 82 +- .../web/servlet/view/RedirectViewTests.java | 46 +- .../view/freemarker/FreeMarkerViewTests.java | 58 +- .../AbstractJasperReportsViewTests.java | 14 +- .../json/MappingJackson2JsonViewTests.java | 18 +- .../json/MappingJacksonJsonViewTests.java | 18 +- .../view/velocity/VelocityViewTests.java | 88 +- .../view/xml/MarshallingViewTests.java | 33 +- ...ansactionalAnnotationIntegrationTests.java | 17 +- 180 files changed, 2349 insertions(+), 4292 deletions(-) diff --git a/build.gradle b/build.gradle index bf5df93e859c..fac5af1ec003 100644 --- a/build.gradle +++ b/build.gradle @@ -13,7 +13,6 @@ configure(allprojects) { project -> version = qualifyVersionIfNecessary(version) ext.aspectjVersion = "1.7.2" - ext.easymockVersion = "2.5.2" ext.hsqldbVersion = "1.8.0.10" ext.junitVersion = "4.11" ext.slf4jVersion = "1.6.1" @@ -69,13 +68,6 @@ configure(allprojects) { project -> testCompile("junit:junit:${junitVersion}") testCompile("org.hamcrest:hamcrest-all:1.3") testCompile("org.mockito:mockito-core:1.9.5") - if (project.name in ["spring", - "spring-orm-hibernate4", "spring-oxm", "spring-struts", - "spring-test", "spring-test-mvc", "spring-tx", "spring-web", - "spring-webmvc", "spring-webmvc-portlet", "spring-webmvc-tiles3"]) { - testCompile("org.easymock:easymock:${easymockVersion}") - testCompile "org.easymock:easymockclassextension:${easymockVersion}" - } } ext.javadocLinks = [ diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java index e13097c4b68b..f2224a4134d1 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java @@ -16,11 +16,6 @@ package org.springframework.aop.framework.adapter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; @@ -33,6 +28,9 @@ import org.springframework.aop.ThrowsAdvice; import org.springframework.tests.aop.advice.MethodCounter; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java index 0c1c50c9c529..6146571fa6f2 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java @@ -16,18 +16,13 @@ package org.springframework.aop.interceptor; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rob Harrop * @author Rick Evans diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java index d0cee0780eb7..5096fe88dd7a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,13 @@ package org.springframework.aop.interceptor; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the {@link DebugInterceptor} class. * diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java index bf2c45fc2c6e..a08b03064a1e 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/PerformanceMonitorInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,13 @@ package org.springframework.aop.interceptor; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rob Harrop * @author Rick Evans diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java index 96501f2c14f6..5bdeb414dff8 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java @@ -16,18 +16,13 @@ package org.springframework.aop.interceptor; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the {@link SimpleTraceInterceptor} class. * diff --git a/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java b/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java index 9ec42626db35..4e3d3ca61978 100644 --- a/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/scope/DefaultScopedObjectTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,11 @@ package org.springframework.aop.scope; -import static org.mockito.Mockito.mock; - import org.junit.Test; import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the {@link DefaultScopedObject} class. * diff --git a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java index 7a7257ea2f35..cf959b324ca7 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java @@ -16,14 +16,6 @@ package org.springframework.aop.support; -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.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.io.Serializable; import org.aopalliance.intercept.MethodInterceptor; @@ -41,6 +33,10 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Chris Beams diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index 94f6376ce18f..73c2ab592a6c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -16,24 +16,6 @@ package org.springframework.beans.factory; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.containsString; -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.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.mockito.BDDMockito.given; -import static org.mockito.Matchers.isNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - import java.io.Closeable; import java.lang.reflect.Field; import java.net.MalformedURLException; @@ -104,6 +86,10 @@ import org.springframework.util.StopWatch; import org.springframework.util.StringValueResolver; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Tests properties population and autowire behavior. * @@ -2261,8 +2247,8 @@ public void testContainsBeanReturnsTrueEvenForAbstractBeanDefinition() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); bf.registerBeanDefinition("abs", BeanDefinitionBuilder .rootBeanDefinition(TestBean.class).setAbstract(true).getBeanDefinition()); - assertThat(bf.containsBean("abs"), is(true)); - assertThat(bf.containsBean("bogus"), is(false)); + assertThat(bf.containsBean("abs"), equalTo(true)); + assertThat(bf.containsBean("bogus"), equalTo(false)); } @Test diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java index f06388cc8d7c..4c6725e01ecb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java @@ -16,9 +16,6 @@ package org.springframework.beans.factory.config; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - import java.util.HashMap; import java.util.Map; @@ -26,6 +23,9 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for {@link CustomScopeConfigurer}. * diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java index dc56161776db..a41a5c97bb73 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java @@ -16,14 +16,6 @@ package org.springframework.beans.factory.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.springframework.tests.TestResourceUtils.qualifiedResource; - import java.util.Date; import javax.inject.Provider; @@ -38,6 +30,10 @@ import org.springframework.core.io.Resource; import org.springframework.util.SerializationTestUtils; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.tests.TestResourceUtils.*; + /** * @author Colin Sampaleanu * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java index f7ab438e7659..ae7c2b845198 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,6 @@ package org.springframework.beans.factory.config; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; - import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -30,6 +26,10 @@ import org.springframework.core.NestedCheckedException; import org.springframework.core.NestedRuntimeException; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.beans.factory.support.BeanDefinitionBuilder.*; + /** * Unit tests for {@link ServiceLocatorFactoryBean}. * diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java index 622b7fda5d38..af6ec0c484fb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/FailFastProblemReporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,13 @@ package org.springframework.beans.factory.parsing; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.apache.commons.logging.Log; import org.junit.Test; import org.springframework.core.io.DescriptiveResource; +import static org.mockito.Matchers.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java index 625e8c7085e7..7b039cc66083 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java @@ -16,9 +16,6 @@ package org.springframework.beans.factory.wiring; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; import junit.framework.TestCase; import org.springframework.beans.factory.BeanFactory; @@ -26,6 +23,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.tests.sample.beans.TestBean; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java index ca55ed9a0e19..04d7bda02f3f 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java @@ -16,15 +16,6 @@ package org.springframework.scheduling.quartz; -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.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.util.Arrays; import java.util.Date; import java.util.HashMap; @@ -52,19 +43,22 @@ import org.quartz.TriggerListener; import org.quartz.impl.SchedulerRepository; import org.quartz.spi.JobFactory; -import org.springframework.tests.context.TestMethodInvokingTask; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.StaticListableBeanFactory; -import org.springframework.tests.Assume; -import org.springframework.tests.TestGroup; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.core.task.TaskExecutor; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; +import org.springframework.tests.context.TestMethodInvokingTask; +import org.springframework.tests.sample.beans.TestBean; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java index 364d5415920c..b078e3c0048e 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java @@ -16,18 +16,17 @@ package org.springframework.aop.aspectj; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Before; import org.junit.Test; import org.springframework.aop.aspectj.AdviceBindingTestAspect.AdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; +import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import org.springframework.context.support.ClassPathXmlApplicationContext; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * Tests for various parameter binding scenarios with before advice. diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java index c04a54f8e646..3d6f902d3425 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java @@ -16,19 +16,17 @@ package org.springframework.aop.aspectj; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - import org.junit.Before; import org.junit.Test; import org.springframework.aop.aspectj.AfterReturningAdviceBindingTestAspect.AfterReturningAdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; +import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import org.springframework.context.support.ClassPathXmlApplicationContext; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * Tests for various parameter binding scenarios with before advice. diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java index 076050792495..c98aea5211d1 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java @@ -16,14 +16,13 @@ package org.springframework.aop.aspectj; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Before; import org.junit.Test; import org.springframework.aop.aspectj.AfterThrowingAdviceBindingTestAspect.AfterThrowingAdviceBindingCollaborator; -import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.tests.sample.beans.ITestBean; + +import static org.mockito.BDDMockito.*; /** * Tests for various parameter binding scenarios with before advice. diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java index 879e846b2bdc..0d9911560e64 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java @@ -16,20 +16,19 @@ package org.springframework.aop.aspectj; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.aspectj.lang.ProceedingJoinPoint; import org.junit.Before; import org.junit.Test; import org.springframework.aop.aspectj.AroundAdviceBindingTestAspect.AroundAdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * Tests for various parameter binding scenarios with before advice. diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java index 94e6e43f8abc..c313c6f33932 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java @@ -16,18 +16,17 @@ package org.springframework.aop.aspectj; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Before; import org.junit.Test; import org.springframework.aop.aspectj.AdviceBindingTestAspect.AdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; +import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import org.springframework.context.support.ClassPathXmlApplicationContext; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * Tests for various parameter binding scenarios with before advice. diff --git a/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java index 753fb3341a75..7959a45b08a8 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/MethodLocatingFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,15 @@ package org.springframework.aop.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.lang.reflect.Method; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Chris Beams diff --git a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java index 77101f6cc902..562ab9bf3287 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java @@ -16,21 +16,19 @@ package org.springframework.aop.framework; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.io.Serializable; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; - import org.springframework.aop.interceptor.ExposeInvocationInterceptor; import org.springframework.aop.support.AopUtils; import org.springframework.tests.sample.beans.IOther; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @since 13.03.2003 * @author Rod Johnson diff --git a/spring-context/src/test/java/org/springframework/context/access/ContextBeanFactoryReferenceTests.java b/spring-context/src/test/java/org/springframework/context/access/ContextBeanFactoryReferenceTests.java index 33bdac26e819..f9aefe64da1c 100644 --- a/spring-context/src/test/java/org/springframework/context/access/ContextBeanFactoryReferenceTests.java +++ b/spring-context/src/test/java/org/springframework/context/access/ContextBeanFactoryReferenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,12 @@ package org.springframework.context.access; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Test; import org.springframework.context.ConfigurableApplicationContext; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit test for {@link ContextBeanFactoryReference} * diff --git a/spring-context/src/test/java/org/springframework/context/annotation/EnableLoadTimeWeavingTests.java b/spring-context/src/test/java/org/springframework/context/annotation/EnableLoadTimeWeavingTests.java index 9a3ced52d704..a8b40b2ac33f 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/EnableLoadTimeWeavingTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/EnableLoadTimeWeavingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.context.annotation; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - import java.lang.instrument.ClassFileTransformer; import org.junit.Test; @@ -28,6 +23,9 @@ import org.springframework.context.support.GenericXmlApplicationContext; import org.springframework.instrument.classloading.LoadTimeWeaver; +import static org.mockito.Matchers.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for @EnableLoadTimeWeaving * diff --git a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java index d124bac83066..24c1a4da95a2 100644 --- a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java @@ -20,16 +20,8 @@ import java.util.Set; import org.aopalliance.intercept.MethodInvocation; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Test; - import org.springframework.aop.framework.ProxyFactory; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; @@ -39,6 +31,10 @@ import org.springframework.context.BeanThatListens; import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.Ordered; +import org.springframework.tests.sample.beans.TestBean; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * Unit and integration tests for the ApplicationContext event support. diff --git a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java index 1a0e064b757f..128abf301dc6 100644 --- a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java @@ -16,21 +16,21 @@ package org.springframework.context.event; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - import org.junit.Before; import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.BeansException; -import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.MutablePropertyValues; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.TestListener; import org.springframework.context.support.StaticApplicationContext; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * @author Dmitriy Kopylenko diff --git a/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java index b8206b21a28f..a87d56eb9bd7 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/LocalSlsbInvokerInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.ejb.access; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import javax.ejb.CreateException; import javax.ejb.EJBLocalHome; import javax.ejb.EJBLocalObject; @@ -31,6 +26,9 @@ import org.springframework.aop.framework.ProxyFactory; import org.springframework.jndi.JndiTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java index c0a78215bd67..d10dce2a5ac7 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/LocalStatelessSessionProxyFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,6 @@ package org.springframework.ejb.access; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - import java.lang.reflect.Proxy; import javax.ejb.CreateException; @@ -32,6 +26,9 @@ import org.junit.Test; import org.springframework.jndi.JndiTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java index 0c03c57c69db..0191220b1bf3 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java @@ -16,12 +16,6 @@ package org.springframework.ejb.access; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.rmi.ConnectException; import java.rmi.RemoteException; @@ -36,6 +30,9 @@ import org.springframework.jndi.JndiTemplate; import org.springframework.remoting.RemoteAccessException; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java index 8e03115c1f30..68af4a9b06db 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteStatelessSessionProxyFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,6 @@ package org.springframework.ejb.access; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; - import java.lang.reflect.Proxy; import java.rmi.RemoteException; @@ -34,6 +28,9 @@ import org.springframework.jndi.JndiTemplate; import org.springframework.remoting.RemoteAccessException; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java index 4ad2255d2c49..d9d7e60ac6b5 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java @@ -16,12 +16,6 @@ package org.springframework.jndi; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import javax.naming.Context; import javax.naming.NamingException; @@ -31,6 +25,9 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java index 401880247598..ef73a867f189 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,14 @@ package org.springframework.jndi; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import javax.naming.Context; import javax.naming.NameNotFoundException; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java index 05601840108e..93b33b48bc99 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java @@ -16,9 +16,6 @@ package org.springframework.scripting.bsh; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.util.Arrays; import java.util.Collection; @@ -26,7 +23,6 @@ import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.Refreshable; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -38,6 +34,9 @@ import org.springframework.scripting.ScriptSource; import org.springframework.scripting.TestBeanAwareMessenger; import org.springframework.scripting.support.ScriptFactoryPostProcessor; +import org.springframework.tests.sample.beans.TestBean; + +import static org.mockito.BDDMockito.*; /** * @author Rob Harrop diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java index cca1625d3dfe..7ced7671ce37 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java @@ -16,16 +16,16 @@ package org.springframework.scripting.groovy; +import groovy.lang.DelegatingMetaClass; +import groovy.lang.GroovyObject; + import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Map; -import groovy.lang.DelegatingMetaClass; -import groovy.lang.GroovyObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; - import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.Refreshable; import org.springframework.beans.factory.BeanCreationException; @@ -52,7 +52,6 @@ import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; -import static org.mockito.Mockito.mock; /** * @author Rob Harrop diff --git a/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java index 5a5b72715c56..a443bee0bb43 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,12 @@ package org.springframework.scripting.support; -import static org.mockito.Mockito.mock; import junit.framework.TestCase; import org.springframework.beans.factory.BeanFactory; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans */ diff --git a/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java index e1fe7c848e06..08c9353bb923 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.scripting.support; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.io.ByteArrayInputStream; import java.io.IOException; @@ -27,6 +24,8 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java index d561ac7e7eb7..680bbe65d259 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/ScriptFactoryPostProcessorTests.java @@ -16,11 +16,8 @@ package org.springframework.scripting.support; -import static org.mockito.Mockito.mock; - import org.junit.Before; import org.junit.Test; - import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.config.BeanDefinition; @@ -34,6 +31,7 @@ import org.springframework.tests.TestGroup; import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * @author Rick Evans diff --git a/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java b/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java index fe10d2359673..61810c98ec64 100644 --- a/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java @@ -16,14 +16,6 @@ package org.springframework.util; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; @@ -36,6 +28,10 @@ import org.junit.Test; import org.mockito.InOrder; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Tests for {@link StreamUtils}. * diff --git a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java index 0c3b9f0e49de..3ced43ba0ce9 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java +++ b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,6 @@ package org.springframework.util.xml; -import static org.mockito.BDDMockito.willAnswer; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; - import java.io.InputStream; import javax.xml.stream.XMLInputFactory; @@ -44,6 +38,8 @@ import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLReaderFactory; +import static org.mockito.BDDMockito.*; + public abstract class AbstractStaxXMLReaderTestCase { protected static XMLInputFactory inputFactory; diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java index 5a34a003ee25..355cb94438b4 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,9 @@ package org.springframework.util.xml; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.InputStream; import java.io.StringReader; + import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; @@ -29,6 +27,8 @@ import org.xml.sax.InputSource; import org.xml.sax.helpers.AttributesImpl; +import static org.mockito.BDDMockito.*; + public class StaxEventXMLReaderTests extends AbstractStaxXMLReaderTestCase { public static final String CONTENT = ""; diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java index ba84eadd760f..e074085f6d7b 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,23 +18,22 @@ import java.io.InputStream; import java.io.StringReader; + import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; -import static org.junit.Assert.*; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import org.junit.Test; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.BDDMockito.*; + public class StaxStreamXMLReaderTests extends AbstractStaxXMLReaderTestCase { public static final String CONTENT = ""; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java index 98016c611349..e6e2121c8d1c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java @@ -16,12 +16,6 @@ package org.springframework.jdbc.core; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.math.BigDecimal; import java.sql.Connection; import java.sql.ResultSet; @@ -35,6 +29,9 @@ import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Mock object based abstract class for RowMapper tests. * Initializes mock objects and verifies results. diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java index 86518a5f8769..f9963c11233f 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateQueryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,6 @@ package org.springframework.jdbc.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Connection; @@ -43,6 +35,9 @@ import org.junit.rules.ExpectedException; import org.springframework.dao.IncorrectResultSizeDataAccessException; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java index 3c4e1bc73ae6..ffa2d74ddfcf 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/JdbcTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,26 +16,6 @@ package org.springframework.jdbc.core; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.sameInstance; -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.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.springframework.tests.Matchers.exceptionCause; - import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -71,6 +51,11 @@ import org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractorAdapter; import org.springframework.util.LinkedCaseInsensitiveMap; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.tests.Matchers.*; + /** * Mock object based tests for JdbcTemplate. * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java index 60a4b4b3499b..a44686f3a617 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java @@ -16,11 +16,6 @@ package org.springframework.jdbc.core; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -34,9 +29,11 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; +import org.springframework.tests.sample.beans.TestBean; + +import static org.mockito.BDDMockito.*; /** * @author Juergen Hoeller diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java index 00e229ba9dc6..694c3c65fad6 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/StatementCreatorUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,6 @@ package org.springframework.jdbc.core; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; @@ -30,6 +26,8 @@ import org.junit.Before; import org.junit.Test; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 31.08.2004 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java index c17c8bbc02d9..a8c27275e817 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java @@ -27,13 +27,13 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; + import javax.sql.DataSource; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; - import org.springframework.dao.DataAccessException; import org.springframework.jdbc.Customer; import org.springframework.jdbc.core.JdbcOperations; @@ -46,11 +46,6 @@ import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; /** * @author Rick Evans diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java index 80c7a07f2e2f..73e9b46ff59f 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterQueryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,6 @@ package org.springframework.jdbc.core.namedparam; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -42,6 +35,9 @@ import org.junit.Test; import org.springframework.jdbc.core.RowMapper; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thomas Risberg * @author Phillip Webb diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java index 0b09e04dc3f6..22498510c746 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/CallMetaDataContextTests.java @@ -1,11 +1,5 @@ package org.springframework.jdbc.core.simple; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Types; @@ -24,6 +18,9 @@ import org.springframework.jdbc.core.metadata.CallMetaDataContext; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Mock object based tests for CallMetaDataContext. * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java index 9779c29d65da..0559f34b8c84 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcCallTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,6 @@ package org.springframework.jdbc.core.simple; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.springframework.tests.Matchers.exceptionCause; - import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -43,6 +35,11 @@ import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.tests.Matchers.*; + /** * Mock object based tests for SimpleJdbcCall. * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcInsertTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcInsertTests.java index 85b6263e47fa..9d76aeebd49a 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcInsertTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcInsertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,6 @@ package org.springframework.jdbc.core.simple; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -34,6 +30,8 @@ import org.junit.rules.ExpectedException; import org.springframework.dao.InvalidDataAccessApiUsageException; +import static org.mockito.BDDMockito.*; + /** * Mock object based tests for SimpleJdbcInsert. * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplateTests.java index 05f289076ba6..8c5a2024df0e 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/SimpleJdbcTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,6 @@ package org.springframework.jdbc.core.simple; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; @@ -48,6 +39,9 @@ import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; import org.springframework.jdbc.core.namedparam.SqlParameterSource; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Rob Harrop diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java index 34572961a808..968883fd6a28 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java @@ -16,12 +16,6 @@ package org.springframework.jdbc.core.simple; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; @@ -38,6 +32,9 @@ import org.springframework.jdbc.core.metadata.TableMetaDataContext; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Mock object based tests for TableMetaDataContext. * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java index 664c2ff24b14..6e5779c26a40 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcBeanDefinitionReaderTests.java @@ -16,11 +16,6 @@ package org.springframework.jdbc.core.support; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; @@ -28,8 +23,11 @@ import javax.sql.DataSource; import org.junit.Test; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.tests.sample.beans.TestBean; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * @author Rod Johnson diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java index 1aefee1e9464..45e11b3c2522 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/JdbcDaoSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.jdbc.core.support; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - import java.util.ArrayList; import java.util.List; @@ -27,6 +24,9 @@ import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 30.07.2003 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java index feba295516b3..a243d59ba42a 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/LobSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,6 @@ package org.springframework.jdbc.core.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -36,6 +30,9 @@ import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Alef Arendsen */ diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java index 8a7cc6454695..d0003d4f56f4 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/support/SqlLobValueTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,14 +15,6 @@ */ package org.springframework.jdbc.core.support; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; @@ -40,6 +32,10 @@ import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Test cases for the sql lob value: * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java index 3d6d4d4d1770..4563a2b197ec 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceJtaTransactionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,6 @@ package org.springframework.jdbc.datasource; -import static org.junit.Assert.assertFalse; -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.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.SQLException; import java.util.HashMap; @@ -59,6 +46,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 17.10.2005 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java index c02dcbf02de8..3c29aa3ae89c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DataSourceTransactionManagerTests.java @@ -16,14 +16,6 @@ package org.springframework.jdbc.datasource; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; @@ -55,6 +47,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 04.07.2003 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTest.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTest.java index de22e56058e6..05295b56dde3 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTest.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DelegatingDataSourceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,6 @@ package org.springframework.jdbc.datasource; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.sql.Connection; @@ -31,6 +25,10 @@ import org.junit.Before; import org.junit.Test; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Tests for {@link DelegatingDataSource}. * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java index ec33bdeaf1e5..d4c1be90262c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/DriverManagerDataSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,14 @@ package org.springframework.jdbc.datasource; -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; - import java.sql.Connection; import java.util.Properties; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson */ diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java index 221a9e59fbcd..0a9f8b7df18c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/UserCredentialsDataSourceAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,6 @@ package org.springframework.jdbc.datasource; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.sql.Connection; import java.sql.SQLException; @@ -27,6 +23,9 @@ import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 28.05.2004 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java index 2e5c67d0f2b9..64f09cc77cc9 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,6 @@ package org.springframework.jdbc.datasource.init; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.SQLException; @@ -32,6 +28,9 @@ import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Dave Syer * @author Sam Brannen diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java index 1ad38f1457c0..ec2e2b4d0d7b 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/datasource/lookup/BeanFactoryDataSourceLookupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,15 @@ package org.springframework.jdbc.datasource.lookup; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import javax.sql.DataSource; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java index f325d4891f3c..e0352b941c82 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/BatchSqlUpdateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -16,13 +16,6 @@ package org.springframework.jdbc.object; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; @@ -33,6 +26,9 @@ import org.junit.Test; import org.springframework.jdbc.core.SqlParameter; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 22.02.2005 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java index 6f17fc2044ec..b43b68957255 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericSqlQueryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,6 @@ package org.springframework.jdbc.object; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -43,6 +38,9 @@ import org.springframework.jdbc.Customer; import org.springframework.jdbc.datasource.TestDataSourceWrapper; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thomas Risberg */ diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java index 4a5c78738250..c7260f2bd3d7 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/GenericStoredProcedureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.jdbc.object; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Types; @@ -37,6 +32,9 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.TestDataSourceWrapper; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thomas Risberg */ diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java index 10a2248c374a..3dc5c36d89b9 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlQueryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,6 @@ package org.springframework.jdbc.object; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -51,6 +39,10 @@ import org.springframework.jdbc.Customer; import org.springframework.jdbc.core.SqlParameter; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Trevor Cook * @author Thomas Risberg diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java index c57e430f67b2..718f085b29e5 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/SqlUpdateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.jdbc.object; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -42,6 +37,9 @@ import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Trevor Cook * @author Thomas Risberg diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java index 6d2ce8106fe5..d31f74315725 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,6 @@ package org.springframework.jdbc.object; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.startsWith; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - import java.math.BigDecimal; import java.sql.CallableStatement; import java.sql.Connection; @@ -62,6 +51,9 @@ import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thomas Risberg * @author Trevor Cook diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java index 6d23a8e8284e..b1e021d2e3f5 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/DataFieldMaxValueIncrementerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,6 @@ package org.springframework.jdbc.support; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -35,6 +29,9 @@ import org.springframework.jdbc.support.incrementer.OracleSequenceMaxValueIncrementer; import org.springframework.jdbc.support.incrementer.PostgreSQLSequenceMaxValueIncrementer; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 27.02.2004 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/DefaultLobHandlerTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/DefaultLobHandlerTests.java index 14e4d5bf682b..1426ade1044a 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/DefaultLobHandlerTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/DefaultLobHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.jdbc.support; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -33,6 +30,8 @@ import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 17.12.2003 diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/NativeJdbcExtractorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/NativeJdbcExtractorTests.java index f99ae954ddee..d70991e608d1 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/NativeJdbcExtractorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/NativeJdbcExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,6 @@ package org.springframework.jdbc.support; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -32,6 +28,9 @@ import org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor; import org.springframework.jdbc.support.nativejdbc.SimpleNativeJdbcExtractor; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Andre Biryukov * @author Juergen Hoeller diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java index e118d922ff8a..944b77c5dc02 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodesFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,6 @@ package org.springframework.jdbc.support; -import static org.hamcrest.CoreMatchers.equalTo; -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.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; @@ -37,6 +27,10 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Tests for SQLErrorCodes loading. * diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java index 0594fec1cb4a..27e1d96fb773 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/rowset/ResultSetWrappingRowSetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.jdbc.support.rowset; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; @@ -34,6 +29,9 @@ import org.junit.Test; import org.springframework.jdbc.InvalidResultSetAccessException; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thomas Risberg */ diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java index a8c89b525e87..fd7dbf89390b 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java @@ -16,14 +16,6 @@ package org.springframework.jms.config; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.util.HashSet; import java.util.Iterator; import java.util.Map; @@ -53,6 +45,9 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ErrorHandler; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Mark Fisher * @author Juergen Hoeller diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java index cd53ab37a313..77353d24dab2 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java @@ -16,14 +16,6 @@ package org.springframework.jms.connection; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -53,6 +45,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 26.07.2004 diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java index a1a40d51e44b..3f323ec8b151 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java @@ -16,14 +16,6 @@ package org.springframework.jms.connection; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.ExceptionListener; @@ -38,6 +30,9 @@ import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 26.07.2004 diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java index cbf03b7abaf2..6b9e83581ed0 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java @@ -16,15 +16,6 @@ package org.springframework.jms.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; - import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; @@ -67,6 +58,9 @@ import org.springframework.jms.support.destination.JndiDestinationResolver; import org.springframework.jndi.JndiTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the JmsTemplate implemented using JMS 1.0.2. * diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java index 1ac040f3f86d..937220108050 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java @@ -16,16 +16,6 @@ package org.springframework.jms.core; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; - import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; @@ -68,6 +58,9 @@ import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the JmsTemplate implemented using JMS 1.1. * diff --git a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java index 15eefc873f75..570a7abc87a1 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java @@ -15,9 +15,6 @@ */ package org.springframework.jms.core.support; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - import java.util.ArrayList; import java.util.List; @@ -26,6 +23,9 @@ import org.junit.Test; import org.springframework.jms.core.JmsTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Mark Pollack * @since 24.9.2004 diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java index 8dad2a08e037..2dda59ceb137 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java @@ -16,15 +16,6 @@ package org.springframework.jms.listener; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.util.HashSet; import javax.jms.Connection; @@ -43,6 +34,9 @@ import org.springframework.jms.StubQueue; import org.springframework.util.ErrorHandler; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java index 0781e2916d95..1d633b4e5f46 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java @@ -16,13 +16,6 @@ package org.springframework.jms.listener.adapter; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import javax.jms.BytesMessage; @@ -42,6 +35,9 @@ import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.SimpleMessageConverter102; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the {@link MessageListenerAdapter102} class. * diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java index c673f51a4474..3fa9fe313a00 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java @@ -16,18 +16,6 @@ package org.springframework.jms.listener.adapter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.io.Serializable; @@ -50,6 +38,9 @@ import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java index ea98f9020678..1a78ba5f7918 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java @@ -16,9 +16,6 @@ package org.springframework.jms.listener.endpoint; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import javax.jms.Destination; import javax.jms.Session; @@ -28,6 +25,8 @@ import org.springframework.jms.StubQueue; import org.springframework.jms.support.destination.DestinationResolver; +import static org.mockito.BDDMockito.*; + /** * @author Agim Emruli * @author Juergen Hoeller diff --git a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java index 9cdbf3413686..4913da3e9026 100644 --- a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java @@ -16,12 +16,6 @@ package org.springframework.jms.remoting; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import java.io.Serializable; import java.util.Arrays; import java.util.Enumeration; @@ -44,6 +38,9 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller */ diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java index 8ca5ad2e1f1a..153cf0dd7a92 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java @@ -16,12 +16,6 @@ package org.springframework.jms.support; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; - import java.io.ByteArrayInputStream; import java.util.Random; @@ -35,6 +29,10 @@ import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.SimpleMessageConverter102; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the {@link SimpleMessageConverter102} class. * @@ -53,7 +51,7 @@ public void testByteArrayConversion102() throws JMSException { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); given(session.createBytesMessage()).willReturn(message); - given(message.readBytes(any(byte[].class))).willAnswer(new Answer() { + given(message.readBytes((byte[]) anyObject())).willAnswer(new Answer() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { return byteArrayInputStream.read((byte[])invocation.getArguments()[0]); diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java index b903ff368686..3ea917f017c0 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java @@ -16,14 +16,6 @@ package org.springframework.jms.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; @@ -43,6 +35,9 @@ import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the {@link SimpleMessageConverter} class. * diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java index d2054d5bf2ce..bbb59cde21ec 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java @@ -16,13 +16,6 @@ package org.springframework.jms.support.converter; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Date; @@ -38,6 +31,9 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Arjen Poutsma * @author Dave Syer diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java index 0bce702aaad8..190d55cf5e7c 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java @@ -16,13 +16,6 @@ package org.springframework.jms.support.converter; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; @@ -37,6 +30,9 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Arjen Poutsma * @author Dave Syer diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java index 2f6a06199de1..65ed03ab2b25 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java @@ -16,13 +16,6 @@ package org.springframework.jms.support.converter; -import static org.junit.Assert.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; @@ -34,6 +27,9 @@ import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Arjen Poutsma */ diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java index 504e247ee92d..aba6c9dee78f 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java @@ -16,9 +16,6 @@ package org.springframework.jms.support.destination; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Queue; @@ -32,6 +29,8 @@ import org.springframework.jms.StubQueue; import org.springframework.jms.StubTopic; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans */ diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java index 2afd8e6f9c99..dd44cf3994be 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java @@ -16,14 +16,13 @@ package org.springframework.jms.support.destination; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - import javax.jms.ConnectionFactory; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Chris Beams diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java index 548e0334d19e..9d54247d86a5 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java @@ -16,13 +16,6 @@ package org.springframework.jms.support.destination; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import javax.jms.Destination; import javax.jms.Session; import javax.naming.NamingException; @@ -30,6 +23,9 @@ import org.junit.Test; import org.springframework.jms.StubTopic; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Chris Beams diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java index 498005295ea0..16a7ed030cfb 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java @@ -16,18 +16,6 @@ package org.springframework.orm.hibernate3; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.SQLException; import org.aopalliance.intercept.MethodInvocation; @@ -46,6 +34,9 @@ import org.springframework.dao.DataIntegrityViolationException; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java index 6f5ef6d62d2d..ff9c053d8191 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java @@ -16,20 +16,6 @@ package org.springframework.orm.hibernate3; -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.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willDoNothing; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.util.ArrayList; import java.util.List; @@ -62,6 +48,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java index fd1ae832b38f..07fdf5e6b8e8 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java @@ -16,20 +16,6 @@ package org.springframework.orm.hibernate3; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -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.mockito.BDDMockito.given; -import static org.mockito.Matchers.same; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; - import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.SQLException; @@ -79,6 +65,9 @@ import org.springframework.tests.sample.beans.TestBean; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java index 0b61d5916031..91972e57b093 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java @@ -16,13 +16,6 @@ package org.springframework.orm.hibernate3; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -63,6 +56,9 @@ import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java index 8aa465e0e82f..85aa8db363ff 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java @@ -16,9 +16,6 @@ package org.springframework.orm.hibernate3.support; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - import java.util.ArrayList; import java.util.List; @@ -26,6 +23,9 @@ import org.junit.Test; import org.springframework.orm.hibernate3.HibernateTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java index ab82cbcf6382..f8b5d81194b8 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java @@ -16,11 +16,6 @@ package org.springframework.orm.hibernate3.support; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; @@ -48,6 +43,9 @@ import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java index a51fc633e9b0..0777c3ae11c2 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java @@ -16,16 +16,6 @@ package org.springframework.orm.hibernate3.support; -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.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.io.IOException; import java.sql.Connection; import java.util.concurrent.Callable; @@ -64,6 +54,9 @@ import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller diff --git a/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java b/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java index 91a7277e7832..802c0a2fa4c9 100644 --- a/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java @@ -16,13 +16,6 @@ package org.springframework.orm.ibatis; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; @@ -42,6 +35,9 @@ import com.ibatis.sqlmap.client.SqlMapSession; import com.ibatis.sqlmap.client.event.RowHandler; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Alef Arendsen diff --git a/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java b/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java index 948c4e7ec26a..0eb1a5124389 100644 --- a/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java @@ -16,13 +16,6 @@ package org.springframework.orm.ibatis.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; @@ -47,6 +40,9 @@ import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java index 1967c188d53e..0174445df2cf 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java @@ -16,11 +16,6 @@ package org.springframework.orm.jdo; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; @@ -33,6 +28,9 @@ import org.junit.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java index 29c882b2b638..de3c4d05fe32 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java @@ -16,13 +16,6 @@ package org.springframework.orm.jdo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -41,12 +34,14 @@ import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java index 46003776b05a..f5fb828e49d3 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java @@ -23,6 +23,7 @@ import java.sql.Savepoint; import java.util.ArrayList; import java.util.List; + import javax.jdo.Constants; import javax.jdo.JDOFatalDataStoreException; import javax.jdo.PersistenceManager; @@ -37,7 +38,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; - import org.springframework.jdbc.datasource.ConnectionHandle; import org.springframework.jdbc.datasource.ConnectionHolder; import org.springframework.jdbc.datasource.SimpleConnectionHandle; @@ -56,9 +56,6 @@ import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; /** * @author Juergen Hoeller diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java index 4b16a589caf5..8f4c921adfb6 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java @@ -16,11 +16,6 @@ package org.springframework.orm.jdo; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - import java.io.IOException; import java.util.Map; import java.util.Properties; @@ -31,6 +26,9 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java index 529bdcabf1bd..d11d147ab174 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java @@ -16,9 +16,6 @@ package org.springframework.orm.jdo.support; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; - import java.util.ArrayList; import java.util.List; @@ -27,6 +24,9 @@ import org.junit.Test; import org.springframework.orm.jdo.JdoTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java index 2736e3b6da42..a3b75526d168 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java @@ -16,13 +16,6 @@ package org.springframework.orm.jdo.support; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.io.IOException; import javax.jdo.PersistenceManager; @@ -43,6 +36,9 @@ import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Chris Beams diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java index cefae3bdf2ff..353ba458fa98 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java @@ -16,11 +16,6 @@ package org.springframework.orm.jpa; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceException; import javax.persistence.spi.PersistenceUnitInfo; @@ -29,6 +24,9 @@ import org.junit.Before; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Superclass for unit tests for EntityManagerFactory-creating beans. * Note: Subclasses must set expectations on the mock EntityManagerFactory. diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java index 9102cd8645aa..f84155ecc6f8 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java @@ -16,11 +16,6 @@ package org.springframework.orm.jpa; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.OptimisticLockException; @@ -30,6 +25,9 @@ import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.DefaultTransactionDefinition; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Costin Leau * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java index 0f21f02ea853..0380650be6d1 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java @@ -16,10 +16,10 @@ package org.springframework.orm.jpa; -import static org.mockito.Mockito.verify; - import org.junit.Test; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java index 437713666367..7edab0c0ce1e 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java @@ -16,13 +16,6 @@ package org.springframework.orm.jpa; -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.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import javax.persistence.EntityExistsException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -41,6 +34,9 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Costin Leau * @author Rod Johnson diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java index 959fa0efe9b5..6e4eabe20642 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java @@ -16,15 +16,6 @@ package org.springframework.orm.jpa; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; @@ -40,6 +31,9 @@ import org.junit.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Costin Leau * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java index 64828a431907..697cc6389b90 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java @@ -16,14 +16,6 @@ package org.springframework.orm.jpa; -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.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -39,6 +31,9 @@ import org.springframework.dao.DataAccessException; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Costin Leau * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java index a343d215372a..f81d97dc2ea5 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java @@ -16,17 +16,6 @@ package org.springframework.orm.jpa; -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.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -51,6 +40,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Costin Leau * @author Juergen Hoeller diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java index 5f20a375d4be..7ab71bc860a0 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java @@ -16,19 +16,6 @@ package org.springframework.orm.jpa; -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.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import java.util.Map; import java.util.Properties; @@ -51,6 +38,9 @@ import org.springframework.transaction.interceptor.DefaultTransactionAttribute; import org.springframework.util.SerializationTestUtils; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java index de6667f543f1..bbf407b38075 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java @@ -16,10 +16,6 @@ package org.springframework.orm.jpa; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.verify; - import java.util.Map; import java.util.Properties; @@ -30,6 +26,9 @@ import org.junit.After; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java index 4925258a6693..acb86b597a28 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java @@ -16,11 +16,6 @@ package org.springframework.orm.jpa.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - import java.util.ArrayList; import java.util.List; @@ -30,6 +25,9 @@ import org.junit.Test; import org.springframework.orm.jpa.JpaTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Costin Leau * @author Phillip Webb diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java index 8dd05c32b3d0..1859fd3acad3 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java @@ -16,17 +16,6 @@ package org.springframework.orm.jpa.support; -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.mockito.BDDMockito.given; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.io.IOException; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; @@ -56,6 +45,9 @@ import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Costin Leau * @author Juergen Hoeller diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java index f7a26112fc51..9833c7146d7b 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java @@ -16,15 +16,6 @@ package org.springframework.orm.jpa.support; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.withSettings; - import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -57,6 +48,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.SerializationTestUtils; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for persistence context and persistence unit injection. * diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java index 4a783c7d5d59..d185546a802c 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java @@ -16,14 +16,6 @@ package org.springframework.orm.jpa.support; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -32,6 +24,9 @@ import org.springframework.orm.jpa.EntityManagerProxy; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java index 1ffc53630447..8178d7045225 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,6 @@ package org.springframework.oxm.castor; -import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; -import static org.easymock.EasyMock.aryEq; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; - import java.io.StringWriter; import java.util.Arrays; import java.util.HashMap; @@ -39,6 +30,7 @@ import org.custommonkey.xmlunit.XpathEngine; import org.junit.Assert; import org.junit.Test; +import org.mockito.InOrder; import org.springframework.core.io.ClassPathResource; import org.springframework.oxm.AbstractMarshallerTests; import org.springframework.oxm.Marshaller; @@ -47,6 +39,11 @@ import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; +import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.BDDMockito.*; + /** * Tests the {@link CastorMarshaller} class. * @@ -126,26 +123,21 @@ protected Object createFlights() { @Test public void marshalSaxResult() throws Exception { - ContentHandler handlerMock = createMock(ContentHandler.class); - handlerMock.startDocument(); - handlerMock.startPrefixMapping("tns", "http://samples.springframework.org/flight"); - handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("tns:flights"), - isA(Attributes.class)); - handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("tns:flight"), - isA(Attributes.class)); - handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("tns:number"), - isA(Attributes.class)); - handlerMock.characters(aryEq(new char[]{'4', '2'}), eq(0), eq(2)); - handlerMock.endElement("http://samples.springframework.org/flight", "number", "tns:number"); - handlerMock.endElement("http://samples.springframework.org/flight", "flight", "tns:flight"); - handlerMock.endElement("http://samples.springframework.org/flight", "flights", "tns:flights"); - handlerMock.endPrefixMapping("tns"); - handlerMock.endDocument(); - - replay(handlerMock); - SAXResult result = new SAXResult(handlerMock); + ContentHandler contentHandler = mock(ContentHandler.class); + SAXResult result = new SAXResult(contentHandler); marshaller.marshal(flights, result); - verify(handlerMock); + InOrder ordered = inOrder(contentHandler); + ordered.verify(contentHandler).startDocument(); + ordered.verify(contentHandler).startPrefixMapping("tns", "http://samples.springframework.org/flight"); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("tns:flights"), isA(Attributes.class)); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("tns:flight"), isA(Attributes.class)); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("tns:number"), isA(Attributes.class)); + ordered.verify(contentHandler).characters(eq(new char[]{'4', '2'}), eq(0), eq(2)); + ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "number", "tns:number"); + ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flight", "tns:flight"); + ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flights", "tns:flights"); + ordered.verify(contentHandler).endPrefixMapping("tns"); + ordered.verify(contentHandler).endDocument(); } @Test @@ -300,7 +292,6 @@ private void assertXpathEvaluatesTo(String msg, String expected, String xpath, S Document doc = XMLUnit.buildControlDocument(xmlDoc); NodeList node = engine.getMatchingNodes(xpath, doc); - assertEquals(msg, expected, node.item(0).getNodeValue()); } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java index 43101e62d0a0..aa3eca07778f 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java @@ -16,19 +16,6 @@ package org.springframework.oxm.jaxb; -import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.createStrictMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.ByteArrayOutputStream; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; @@ -47,6 +34,7 @@ import javax.xml.transform.stream.StreamResult; import org.junit.Test; +import org.mockito.InOrder; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.oxm.AbstractMarshallerTests; @@ -63,6 +51,10 @@ import org.xml.sax.ContentHandler; import org.xml.sax.Locator; +import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + public class Jaxb2MarshallerTests extends AbstractMarshallerTests { private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb.test"; @@ -90,27 +82,22 @@ protected Object createFlights() { @Test public void marshalSAXResult() throws Exception { - ContentHandler handlerMock = createStrictMock(ContentHandler.class); - handlerMock.setDocumentLocator(isA(Locator.class)); - handlerMock.startDocument(); - handlerMock.startPrefixMapping("", "http://samples.springframework.org/flight"); - handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("flights"), - isA(Attributes.class)); - handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("flight"), - isA(Attributes.class)); - handlerMock.startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("number"), - isA(Attributes.class)); - handlerMock.characters(isA(char[].class), eq(0), eq(2)); - handlerMock.endElement("http://samples.springframework.org/flight", "number", "number"); - handlerMock.endElement("http://samples.springframework.org/flight", "flight", "flight"); - handlerMock.endElement("http://samples.springframework.org/flight", "flights", "flights"); - handlerMock.endPrefixMapping(""); - handlerMock.endDocument(); - replay(handlerMock); - - SAXResult result = new SAXResult(handlerMock); + ContentHandler contentHandler = mock(ContentHandler.class); + SAXResult result = new SAXResult(contentHandler); marshaller.marshal(flights, result); - verify(handlerMock); + InOrder ordered = inOrder(contentHandler); + ordered.verify(contentHandler).setDocumentLocator(isA(Locator.class)); + ordered.verify(contentHandler).startDocument(); + ordered.verify(contentHandler).startPrefixMapping("", "http://samples.springframework.org/flight"); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("flights"), isA(Attributes.class)); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("flight"), isA(Attributes.class)); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("number"), isA(Attributes.class)); + ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2)); + ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "number", "number"); + ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flight", "flight"); + ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flights", "flights"); + ordered.verify(contentHandler).endPrefixMapping(""); + ordered.verify(contentHandler).endDocument(); } @Test @@ -280,25 +267,22 @@ public void marshalAttachments() throws Exception { marshaller.setClassesToBeBound(BinaryObject.class); marshaller.setMtomEnabled(true); marshaller.afterPropertiesSet(); - MimeContainer mimeContainer = createMock(MimeContainer.class); + MimeContainer mimeContainer = mock(MimeContainer.class); Resource logo = new ClassPathResource("spring-ws.png", getClass()); DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile())); - expect(mimeContainer.convertToXopPackage()).andReturn(true); - mimeContainer.addAttachment(isA(String.class), isA(DataHandler.class)); - expectLastCall().times(3); - - replay(mimeContainer); + given(mimeContainer.convertToXopPackage()).willReturn(true); byte[] bytes = FileCopyUtils.copyToByteArray(logo.getInputStream()); BinaryObject object = new BinaryObject(bytes, dataHandler); StringWriter writer = new StringWriter(); marshaller.marshal(object, new StreamResult(writer), mimeContainer); - verify(mimeContainer); assertTrue("No XML written", writer.toString().length() > 0); + verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class)); } @XmlRootElement + @SuppressWarnings("unused") public static class DummyRootElement { private DummyType t = new DummyType(); @@ -306,9 +290,11 @@ public static class DummyRootElement { } @XmlType + @SuppressWarnings("unused") public static class DummyType { private String s = "Hello"; + } @SuppressWarnings("unused") diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java index 8b4ce76a802e..55a3f8d22649 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.oxm.jaxb; import java.io.StringReader; + import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.xml.bind.JAXBElement; @@ -25,10 +26,7 @@ import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Test; - import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.oxm.AbstractUnmarshallerTests; @@ -38,6 +36,9 @@ import org.springframework.oxm.mime.MimeContainer; import org.springframework.util.xml.StaxUtils; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests { private static final String INPUT_STRING = "" + @@ -60,19 +61,15 @@ public void marshalAttachments() throws Exception { unmarshaller.setClassesToBeBound(BinaryObject.class); unmarshaller.setMtomEnabled(true); unmarshaller.afterPropertiesSet(); - MimeContainer mimeContainer = createMock(MimeContainer.class); + MimeContainer mimeContainer = mock(MimeContainer.class); Resource logo = new ClassPathResource("spring-ws.png", getClass()); DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile())); - expect(mimeContainer.isXopPackage()).andReturn(true); - expect(mimeContainer.getAttachment( - "<6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws>")).andReturn(dataHandler); - expect(mimeContainer.getAttachment( - "<99bd1592-0521-41a2-9688-a8bfb40192fb@http://springframework.org/spring-ws>")).andReturn(dataHandler); - expect(mimeContainer.getAttachment("696cfb9a-4d2d-402f-bb5c-59fa69e7f0b3@spring-ws.png")) - .andReturn(dataHandler); - replay(mimeContainer); + given(mimeContainer.isXopPackage()).willReturn(true); + given(mimeContainer.getAttachment("<6b76528d-7a9c-4def-8e13-095ab89e9bb7@http://springframework.org/spring-ws>")).willReturn(dataHandler); + given(mimeContainer.getAttachment("<99bd1592-0521-41a2-9688-a8bfb40192fb@http://springframework.org/spring-ws>")).willReturn(dataHandler); + given(mimeContainer.getAttachment("696cfb9a-4d2d-402f-bb5c-59fa69e7f0b3@spring-ws.png")).willReturn(dataHandler); String content = "" + "" + "" + "" + "" + @@ -84,7 +81,6 @@ public void marshalAttachments() throws Exception { StringReader reader = new StringReader(content); Object result = unmarshaller.unmarshal(new StreamSource(reader), mimeContainer); assertTrue("Result is not a BinaryObject", result instanceof BinaryObject); - verify(mimeContainer); BinaryObject object = (BinaryObject) result; assertNotNull("bytes property not set", object.getBytes()); assertTrue("bytes property not set", object.getBytes().length > 0); diff --git a/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java index 7979e4d5c523..ce49ce166d79 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/xstream/XStreamMarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLEventWriter; @@ -36,26 +37,28 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; -import com.thoughtworks.xstream.converters.Converter; -import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; -import com.thoughtworks.xstream.io.HierarchicalStreamWriter; -import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; -import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; -import com.thoughtworks.xstream.io.json.JsonWriter; -import static org.custommonkey.xmlunit.XMLAssert.*; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; +import org.mockito.InOrder; +import org.springframework.util.xml.StaxUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; -import org.springframework.util.xml.StaxUtils; +import com.thoughtworks.xstream.converters.Converter; +import com.thoughtworks.xstream.converters.extended.EncodedByteArrayConverter; +import com.thoughtworks.xstream.io.HierarchicalStreamWriter; +import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; +import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver; +import com.thoughtworks.xstream.io.json.JsonWriter; + +import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; +import static org.custommonkey.xmlunit.XMLAssert.assertXpathExists; +import static org.custommonkey.xmlunit.XMLAssert.assertXpathNotExists; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * @author Arjen Poutsma @@ -143,19 +146,17 @@ public void marshalStreamResultOutputStream() throws Exception { @Test public void marshalSaxResult() throws Exception { - ContentHandler handlerMock = createStrictMock(ContentHandler.class); - handlerMock.startDocument(); - handlerMock.startElement(eq(""), eq("flight"), eq("flight"), isA(Attributes.class)); - handlerMock.startElement(eq(""), eq("flightNumber"), eq("flightNumber"), isA(Attributes.class)); - handlerMock.characters(isA(char[].class), eq(0), eq(2)); - handlerMock.endElement("", "flightNumber", "flightNumber"); - handlerMock.endElement("", "flight", "flight"); - handlerMock.endDocument(); - - replay(handlerMock); - SAXResult result = new SAXResult(handlerMock); + ContentHandler contentHandler = mock(ContentHandler.class); + SAXResult result = new SAXResult(contentHandler); marshaller.marshal(flight, result); - verify(handlerMock); + InOrder ordered = inOrder(contentHandler); + ordered.verify(contentHandler).startDocument(); + ordered.verify(contentHandler).startElement(eq(""), eq("flight"), eq("flight"), isA(Attributes.class)); + ordered.verify(contentHandler).startElement(eq(""), eq("flightNumber"), eq("flightNumber"), isA(Attributes.class)); + ordered.verify(contentHandler).characters(isA(char[].class), eq(0), eq(2)); + ordered.verify(contentHandler).endElement("", "flightNumber", "flightNumber"); + ordered.verify(contentHandler).endElement("", "flight", "flight"); + ordered.verify(contentHandler).endDocument(); } @Test diff --git a/spring-struts/src/test/java/org/springframework/web/struts/StrutsSupportTests.java b/spring-struts/src/test/java/org/springframework/web/struts/StrutsSupportTests.java index ad97b300b558..22db7be93aac 100644 --- a/spring-struts/src/test/java/org/springframework/web/struts/StrutsSupportTests.java +++ b/spring-struts/src/test/java/org/springframework/web/struts/StrutsSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; + import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -26,16 +27,16 @@ import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionServlet; import org.apache.struts.config.ModuleConfig; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Test; - import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 09.04.2004 @@ -228,9 +229,8 @@ public ServletContext getServletContext() { } }; - ModuleConfig moduleConfig = createMock(ModuleConfig.class); - expect(moduleConfig.getPrefix()).andReturn("").anyTimes(); - replay(moduleConfig); + ModuleConfig moduleConfig = mock(ModuleConfig.class); + given(moduleConfig.getPrefix()).willReturn(""); plugin.init(actionServlet, moduleConfig); assertTrue(servletContext.getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX) != null); @@ -249,8 +249,6 @@ public ServletContext getServletContext() { proxy.setServlet(null); plugin.destroy(); assertTrue(testAction.getServlet() == null); - - verify(moduleConfig); } @Test @@ -270,9 +268,8 @@ public ServletContext getServletContext() { } }; - ModuleConfig moduleConfig = createMock(ModuleConfig.class); - expect(moduleConfig.getPrefix()).andReturn("/module").anyTimes(); - replay(moduleConfig); + ModuleConfig moduleConfig = mock(ModuleConfig.class); + given(moduleConfig.getPrefix()).willReturn("/module"); plugin.init(actionServlet, moduleConfig); assertTrue(servletContext.getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX) == null); @@ -313,13 +310,12 @@ public ServletContext getServletContext() { } }; - ModuleConfig defaultModuleConfig = createMock(ModuleConfig.class); - expect(defaultModuleConfig.getPrefix()).andReturn("").anyTimes(); + ModuleConfig defaultModuleConfig = mock(ModuleConfig.class); + given(defaultModuleConfig.getPrefix()).willReturn(""); - ModuleConfig moduleConfig = createMock(ModuleConfig.class); - expect(moduleConfig.getPrefix()).andReturn("/module").anyTimes(); + ModuleConfig moduleConfig = mock(ModuleConfig.class); + given(moduleConfig.getPrefix()).willReturn("/module"); - replay(defaultModuleConfig, moduleConfig); plugin.init(actionServlet, defaultModuleConfig); assertTrue(servletContext.getAttribute(ContextLoaderPlugIn.SERVLET_CONTEXT_PREFIX) != null); @@ -339,8 +335,6 @@ public ServletContext getServletContext() { proxy.setServlet(null); plugin.destroy(); assertTrue(testAction.getServlet() == null); - - verify(defaultModuleConfig, moduleConfig); } } diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.java index 56d4c5b40ddd..b0488791f9f5 100644 --- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.java +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/DefaultMvcResultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,20 +15,17 @@ */ package org.springframework.test.web.servlet; -import static org.easymock.EasyMock.expect; -import static org.easymock.classextension.EasyMock.replay; -import static org.easymock.classextension.EasyMock.verify; - import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.servlet.AsyncContext; -import org.easymock.classextension.EasyMock; import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; +import static org.mockito.BDDMockito.*; + /** * Test fixture for {@link DefaultMvcResult}. * @@ -48,7 +45,7 @@ public void setup() { ExtendedMockHttpServletRequest request = new ExtendedMockHttpServletRequest(); request.setAsyncStarted(true); - this.countDownLatch = EasyMock.createMock(CountDownLatch.class); + this.countDownLatch = mock(CountDownLatch.class); this.mvcResult = new DefaultMvcResult(request, null); this.mvcResult.setAsyncResultLatch(this.countDownLatch); @@ -57,50 +54,35 @@ public void setup() { @Test public void getAsyncResultWithTimeout() throws Exception { long timeout = 1234L; - - expect(this.countDownLatch.await(timeout, TimeUnit.MILLISECONDS)).andReturn(true); - replay(this.countDownLatch); - + given(this.countDownLatch.await(timeout, TimeUnit.MILLISECONDS)).willReturn(true); this.mvcResult.getAsyncResult(timeout); - - verify(this.countDownLatch); + verify(this.countDownLatch).await(timeout, TimeUnit.MILLISECONDS); } @Test public void getAsyncResultWithTimeoutNegativeOne() throws Exception { - expect(this.countDownLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)).andReturn(true); - replay(this.countDownLatch); - + given(this.countDownLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)).willReturn(true); this.mvcResult.getAsyncResult(-1); - - verify(this.countDownLatch); + verify(this.countDownLatch).await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); } @Test public void getAsyncResultWithoutTimeout() throws Exception { - expect(this.countDownLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)).andReturn(true); - replay(this.countDownLatch); - + given(this.countDownLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)).willReturn(true); this.mvcResult.getAsyncResult(); - - verify(this.countDownLatch); + verify(this.countDownLatch).await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); } @Test public void getAsyncResultWithTimeoutZero() throws Exception { - replay(this.countDownLatch); - this.mvcResult.getAsyncResult(0); - - verify(this.countDownLatch); + verifyZeroInteractions(this.countDownLatch); } @Test(expected=IllegalStateException.class) public void getAsyncResultAndTimeOut() throws Exception { - expect(this.countDownLatch.await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS)).andReturn(false); - replay(this.countDownLatch); - this.mvcResult.getAsyncResult(-1); + verify(this.countDownLatch).await(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); } @@ -111,9 +93,8 @@ private static class ExtendedMockHttpServletRequest extends MockHttpServletReque public ExtendedMockHttpServletRequest() { super(); - this.asyncContext = EasyMock.createMock(AsyncContext.class); - expect(this.asyncContext.getTimeout()).andReturn(new Long(DEFAULT_TIMEOUT)); - replay(this.asyncContext); + this.asyncContext = mock(AsyncContext.class); + given(this.asyncContext.getTimeout()).willReturn(new Long(DEFAULT_TIMEOUT)); } public void setAsyncStarted(boolean asyncStarted) { diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java index a254398c4ed6..61240cb40216 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockFilterChainTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at @@ -12,10 +12,6 @@ */ package org.springframework.mock.web; -import static org.easymock.EasyMock.*; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; - import java.io.IOException; import javax.servlet.Filter; @@ -29,6 +25,10 @@ import org.junit.Before; import org.junit.Test; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Test fixture for {@link MockFilterChain}. * @@ -53,7 +53,7 @@ public void constructorNullServlet() { @Test(expected=IllegalArgumentException.class) public void constructorNullFilter() { - new MockFilterChain(createMock(Servlet.class), (Filter) null); + new MockFilterChain(mock(Servlet.class), (Filter) null); } @Test(expected = IllegalArgumentException.class) @@ -87,16 +87,10 @@ public void doFilterEmptyChain() throws Exception { @Test public void doFilterWithServlet() throws Exception { - Servlet servlet = createMock(Servlet.class); - + Servlet servlet = mock(Servlet.class); MockFilterChain chain = new MockFilterChain(servlet); - servlet.service(this.request, this.response); - replay(servlet); - chain.doFilter(this.request, this.response); - - verify(servlet); - + verify(servlet).service(this.request, this.response); try { chain.doFilter(this.request, this.response); fail("Expected Exception"); @@ -108,9 +102,7 @@ public void doFilterWithServlet() throws Exception { @Test public void doFilterWithServletAndFilters() throws Exception { - Servlet servlet = createMock(Servlet.class); - servlet.service(this.request, this.response); - replay(servlet); + Servlet servlet = mock(Servlet.class); MockFilter filter2 = new MockFilter(servlet); MockFilter filter1 = new MockFilter(null); @@ -121,7 +113,7 @@ public void doFilterWithServletAndFilters() throws Exception { assertTrue(filter1.invoked); assertTrue(filter2.invoked); - verify(servlet); + verify(servlet).service(this.request, this.response); try { chain.doFilter(this.request, this.response); diff --git a/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java b/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java index 2038b8ecc074..9a5b2c1243e3 100644 --- a/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/cci/CciLocalTransactionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.jca.cci; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertTrue; - import javax.resource.ResourceException; import javax.resource.cci.Connection; import javax.resource.cci.ConnectionFactory; @@ -29,6 +26,7 @@ import org.junit.Test; import org.springframework.dao.DataRetrievalFailureException; +import org.springframework.jca.cci.connection.CciLocalTransactionManager; import org.springframework.jca.cci.core.CciTemplate; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; @@ -36,6 +34,9 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thierry Templier * @author Chris Beams @@ -49,34 +50,20 @@ public class CciLocalTransactionTests { */ @Test public void testLocalTransactionCommit() throws ResourceException { - final ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - LocalTransaction localTransaction = createMock(LocalTransaction.class); - final Record record = createMock(Record.class); - final InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.getLocalTransaction()).andReturn(localTransaction); - - localTransaction.begin(); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, record, record)).andReturn(true); - - interaction.close(); - - expect(connection.getLocalTransaction()).andReturn(localTransaction); - - localTransaction.commit(); - - connection.close(); - - replay(connectionFactory, connection, localTransaction, interaction, record); - - org.springframework.jca.cci.connection.CciLocalTransactionManager tm = new org.springframework.jca.cci.connection.CciLocalTransactionManager(); + final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + LocalTransaction localTransaction = mock(LocalTransaction.class); + final Record record = mock(Record.class); + final InteractionSpec interactionSpec = mock(InteractionSpec.class); + + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.getLocalTransaction()).willReturn(localTransaction); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, record, record)).willReturn(true); + given(connection.getLocalTransaction()).willReturn(localTransaction); + + CciLocalTransactionManager tm = new CciLocalTransactionManager(); tm.setConnectionFactory(connectionFactory); TransactionTemplate tt = new TransactionTemplate(tm); @@ -89,7 +76,10 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { } }); - verify(connectionFactory, connection, localTransaction, interaction, record); + verify(localTransaction).begin(); + verify(interaction).close(); + verify(localTransaction).commit(); + verify(connection).close(); } /** @@ -99,34 +89,20 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { */ @Test public void testLocalTransactionRollback() throws ResourceException { - final ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - LocalTransaction localTransaction = createMock(LocalTransaction.class); - final Record record = createMock(Record.class); - final InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.getLocalTransaction()).andReturn(localTransaction); - - localTransaction.begin(); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, record, record)).andReturn(true); - - interaction.close(); - - expect(connection.getLocalTransaction()).andReturn(localTransaction); - - localTransaction.rollback(); - - connection.close(); - - replay(connectionFactory, connection, localTransaction, interaction, record); - - org.springframework.jca.cci.connection.CciLocalTransactionManager tm = new org.springframework.jca.cci.connection.CciLocalTransactionManager(); + final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + LocalTransaction localTransaction = mock(LocalTransaction.class); + final Record record = mock(Record.class); + final InteractionSpec interactionSpec = mock(InteractionSpec.class); + + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.getLocalTransaction()).willReturn(localTransaction); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, record, record)).willReturn(true); + given(connection.getLocalTransaction()).willReturn(localTransaction); + + CciLocalTransactionManager tm = new CciLocalTransactionManager(); tm.setConnectionFactory(connectionFactory); TransactionTemplate tt = new TransactionTemplate(tm); @@ -144,6 +120,9 @@ public Object doInTransaction(TransactionStatus status) { catch (Exception ex) { } - verify(connectionFactory, connection, localTransaction, interaction, record); + verify(localTransaction).begin(); + verify(interaction).close(); + verify(localTransaction).rollback(); + verify(connection).close(); } } diff --git a/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java b/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java index ddbdc8006939..f934ebe7976d 100644 --- a/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/cci/CciTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,6 @@ package org.springframework.jca.cci; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import java.sql.SQLException; import javax.resource.NotSupportedException; @@ -48,6 +40,9 @@ import org.springframework.jca.cci.core.RecordCreator; import org.springframework.jca.cci.core.RecordExtractor; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thierry Templier * @author Juergen Hoeller @@ -57,99 +52,73 @@ public class CciTemplateTests { @Test public void testCreateIndexedRecord() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - IndexedRecord indexedRecord = createMock(IndexedRecord.class); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(recordFactory.createIndexedRecord("name")).andReturn( - indexedRecord); - - replay(connectionFactory, recordFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + IndexedRecord indexedRecord = mock(IndexedRecord.class); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(recordFactory.createIndexedRecord("name")).willReturn(indexedRecord); CciTemplate ct = new CciTemplate(connectionFactory); ct.createIndexedRecord("name"); - verify(connectionFactory, recordFactory); + verify(recordFactory).createIndexedRecord("name"); } @Test public void testCreateMappedRecord() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - MappedRecord mappedRecord = createMock(MappedRecord.class); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + MappedRecord mappedRecord = mock(MappedRecord.class); - expect(recordFactory.createMappedRecord("name")) - .andReturn(mappedRecord); - - replay(connectionFactory, recordFactory); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(recordFactory.createMappedRecord("name")).willReturn(mappedRecord); CciTemplate ct = new CciTemplate(connectionFactory); ct.createMappedRecord("name"); - verify(connectionFactory, recordFactory); + verify(recordFactory).createMappedRecord("name"); } @Test public void testTemplateExecuteInputOutput() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - expect(connectionFactory.getConnection()).andReturn(connection); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connection.createInteraction()).andReturn(interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, inputRecord, outputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputRecord, outputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteWithCreatorAndRecordFactoryNotSupported() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - - Record inputRecord = createMock(Record.class); - final Record outputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connectionFactory.getRecordFactory()).andThrow( - new NotSupportedException("not supported")); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - expect(connection.createInteraction()).andReturn(interaction); + Record inputRecord = mock(Record.class); + final Record outputRecord = mock(Record.class); - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connectionFactory.getRecordFactory()).willThrow(new NotSupportedException("not supported")); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); CciTemplate ct = new CciTemplate(connectionFactory); ct.setOutputRecordCreator(new RecordCreator() { @@ -161,352 +130,265 @@ public Record createRecord(RecordFactory recordFactory) { }); ct.execute(interactionSpec, inputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputRecord, outputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteInputTrueWithCreator2() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordCreator creator = createMock(RecordCreator.class); - - Record inputRecord = createMock(Record.class); - final Record outputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(creator.createRecord(recordFactory)).andReturn(outputRecord); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordCreator creator = mock(RecordCreator.class); - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); + Record inputRecord = mock(Record.class); + final Record outputRecord = mock(Record.class); - interaction.close(); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - connection.close(); - - replay(connectionFactory, connection, interaction, creator); + given(connectionFactory.getConnection()).willReturn(connection); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(connection.createInteraction()).willReturn(interaction); + given(creator.createRecord(recordFactory)).willReturn(outputRecord); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); CciTemplate ct = new CciTemplate(connectionFactory); ct.setOutputRecordCreator(creator); ct.execute(interactionSpec, inputRecord); - verify(connectionFactory, connection, interaction, creator); + verify(interaction).execute(interactionSpec, inputRecord, outputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteInputFalse() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - expect(connection.createInteraction()).andReturn(interaction); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - expect(interaction.execute(interactionSpec, inputRecord)).andReturn( - outputRecord); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord)).willReturn(outputRecord); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, inputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputRecord); + verify(interaction).close(); + verify(connection).close(); } @SuppressWarnings("unchecked") @Test public void testTemplateExecuteInputExtractorTrueWithCreator() throws ResourceException, SQLException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordExtractor extractor = createMock(RecordExtractor.class); - RecordCreator creator = createMock(RecordCreator.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordExtractor extractor = mock(RecordExtractor.class); + RecordCreator creator = mock(RecordCreator.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - expect(connectionFactory.getConnection()).andReturn(connection); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connection.createInteraction()).andReturn(interaction); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(creator.createRecord(recordFactory)).andReturn(outputRecord); - - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); - - expect(extractor.extractData(outputRecord)).andStubReturn(new Object()); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, extractor, creator); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(creator.createRecord(recordFactory)).willReturn(outputRecord); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); + given(extractor.extractData(outputRecord)).willReturn(new Object()); CciTemplate ct = new CciTemplate(connectionFactory); ct.setOutputRecordCreator(creator); ct.execute(interactionSpec, inputRecord, extractor); - verify(connectionFactory, connection, interaction, extractor, creator); + verify(extractor).extractData(outputRecord); + verify(interaction).close(); + verify(connection).close(); } @SuppressWarnings("unchecked") @Test public void testTemplateExecuteInputExtractorFalse() throws ResourceException, SQLException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordExtractor extractor = createMock(RecordExtractor.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordExtractor extractor = mock(RecordExtractor.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - expect(connectionFactory.getConnection()).andReturn(connection); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, inputRecord)).andReturn( - outputRecord); - - expect(extractor.extractData(outputRecord)).andStubReturn(new Object()); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, extractor); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord)).willReturn(outputRecord); + given(extractor.extractData(outputRecord)).willReturn(new Object()); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, inputRecord, extractor); - verify(connectionFactory, connection, interaction, extractor); + verify(extractor).extractData(outputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteInputGeneratorTrueWithCreator() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordCreator generator = createMock(RecordCreator.class); - RecordCreator creator = createMock(RecordCreator.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordCreator generator = mock(RecordCreator.class); + RecordCreator creator = mock(RecordCreator.class); - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - expect(generator.createRecord(recordFactory)).andReturn(inputRecord); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connectionFactory.getConnection()).andReturn(connection); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(generator.createRecord(recordFactory)).willReturn(inputRecord); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(creator.createRecord(recordFactory)).willReturn(outputRecord); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); - expect(connection.createInteraction()).andReturn(interaction); - - expect(creator.createRecord(recordFactory)).andReturn(outputRecord); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, generator, creator); CciTemplate ct = new CciTemplate(connectionFactory); ct.setOutputRecordCreator(creator); ct.execute(interactionSpec, generator); - verify(connectionFactory, connection, interaction, generator, creator); + verify(interaction).execute(interactionSpec, inputRecord, outputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteInputGeneratorFalse() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordCreator generator = createMock(RecordCreator.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordCreator generator = mock(RecordCreator.class); - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - expect(connectionFactory.getConnection()).andReturn(connection); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connection.createInteraction()).andReturn(interaction); - - expect(generator.createRecord(recordFactory)).andReturn(inputRecord); - - expect(interaction.execute(interactionSpec, inputRecord)).andReturn( - outputRecord); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, generator); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(generator.createRecord(recordFactory)).willReturn(inputRecord); + given(interaction.execute(interactionSpec, inputRecord)).willReturn(outputRecord); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, generator); - verify(connectionFactory, connection, interaction, generator); + verify(interaction).execute(interactionSpec, inputRecord); + verify(interaction).close(); + verify(connection).close(); } @SuppressWarnings("unchecked") @Test public void testTemplateExecuteInputGeneratorExtractorTrueWithCreator() throws ResourceException, SQLException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordCreator generator = createMock(RecordCreator.class); - RecordExtractor extractor = createMock(RecordExtractor.class); - RecordCreator creator = createMock(RecordCreator.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordCreator generator = mock(RecordCreator.class); + RecordExtractor extractor = mock(RecordExtractor.class); + RecordCreator creator = mock(RecordCreator.class); - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); Object obj = new Object(); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(connectionFactory.getConnection()).andReturn(connection); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connection.createInteraction()).andReturn(interaction); - - expect(creator.createRecord(recordFactory)).andReturn(outputRecord); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(generator.createRecord(recordFactory)).andReturn(inputRecord); - - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); - - expect(extractor.extractData(outputRecord)).andStubReturn(obj); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, generator, creator, - extractor); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(creator.createRecord(recordFactory)).willReturn(outputRecord); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(generator.createRecord(recordFactory)).willReturn(inputRecord); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); + given(extractor.extractData(outputRecord)).willReturn(obj); CciTemplate ct = new CciTemplate(connectionFactory); ct.setOutputRecordCreator(creator); assertEquals(obj, ct.execute(interactionSpec, generator, extractor)); - verify(connectionFactory, connection, interaction, generator, creator, - extractor); + verify(interaction).close(); + verify(connection).close(); } @SuppressWarnings("unchecked") @Test public void testTemplateExecuteInputGeneratorExtractorFalse() throws ResourceException, SQLException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordCreator generator = createMock(RecordCreator.class); - RecordExtractor extractor = createMock(RecordExtractor.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(generator.createRecord(recordFactory)).andReturn(inputRecord); - - expect(interaction.execute(interactionSpec, inputRecord)).andReturn( - outputRecord); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordCreator generator = mock(RecordCreator.class); + RecordExtractor extractor = mock(RecordExtractor.class); - expect(extractor.extractData(outputRecord)).andStubReturn(new Object()); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - interaction.close(); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - connection.close(); - - replay(connectionFactory, connection, interaction, generator, extractor); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(generator.createRecord(recordFactory)).willReturn(inputRecord); + given(interaction.execute(interactionSpec, inputRecord)).willReturn(outputRecord); + given(extractor.extractData(outputRecord)).willReturn(new Object()); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, generator, extractor); - verify(connectionFactory, connection, interaction, generator, extractor); + verify(extractor).extractData(outputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test - public void testTemplateExecuteInputOutputConnectionSpec() - throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - ConnectionSpec connectionSpec = createMock(ConnectionSpec.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + public void testTemplateExecuteInputOutputConnectionSpec() throws ResourceException { + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + ConnectionSpec connectionSpec = mock(ConnectionSpec.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - expect(connectionFactory.getConnection(connectionSpec)).andReturn( - connection); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - expect(connection.createInteraction()).andReturn(interaction); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection(connectionSpec)).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); ConnectionSpecConnectionFactoryAdapter adapter = new ConnectionSpecConnectionFactoryAdapter(); adapter.setTargetConnectionFactory(connectionFactory); @@ -514,197 +396,146 @@ public void testTemplateExecuteInputOutputConnectionSpec() CciTemplate ct = new CciTemplate(adapter); ct.execute(interactionSpec, inputRecord, outputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputRecord, outputRecord); + verify(interaction).close(); + verify(connection).close(); } @SuppressWarnings("unchecked") @Test public void testTemplateExecuteInputOutputResultsSetFalse() throws ResourceException, SQLException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - RecordFactory recordFactory = createMock(RecordFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - Record record = createMock(Record.class); - ResultSet resultset = createMock(ResultSet.class); - RecordCreator generator = createMock(RecordCreator.class); - RecordExtractor extractor = createMock(RecordExtractor.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(generator.createRecord(recordFactory)).andReturn(record); - - expect(interaction.execute(interactionSpec, record)).andReturn( - resultset); - - expect(extractor.extractData(resultset)).andStubReturn(new Object()); - - resultset.close(); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, generator, - extractor, resultset); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + Record record = mock(Record.class); + ResultSet resultset = mock(ResultSet.class); + RecordCreator generator = mock(RecordCreator.class); + RecordExtractor extractor = mock(RecordExtractor.class); + + InteractionSpec interactionSpec = mock(InteractionSpec.class); + + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(generator.createRecord(recordFactory)).willReturn(record); + given(interaction.execute(interactionSpec, record)).willReturn(resultset); + given(extractor.extractData(resultset)).willReturn(new Object()); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, generator, extractor); - verify(connectionFactory, connection, interaction, generator, - extractor, resultset); + verify(extractor).extractData(resultset); + verify(resultset).close(); + verify(interaction).close(); + verify(connection).close(); } @SuppressWarnings("unchecked") @Test public void testTemplateExecuteConnectionCallback() throws ResourceException, SQLException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - ConnectionCallback connectionCallback = createMock(ConnectionCallback.class); - - expect(connectionFactory.getConnection()).andReturn(connection); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + ConnectionCallback connectionCallback = mock(ConnectionCallback.class); - expect(connectionCallback.doInConnection(connection, connectionFactory)) - .andStubReturn(new Object()); - - connection.close(); - - replay(connectionFactory, connection, connectionCallback); + given(connectionFactory.getConnection()).willReturn(connection); + given(connectionCallback.doInConnection(connection, connectionFactory)).willReturn(new Object()); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(connectionCallback); - verify(connectionFactory, connection, connectionCallback); + verify(connectionCallback).doInConnection(connection, connectionFactory); + verify(connection).close(); } @SuppressWarnings("unchecked") @Test public void testTemplateExecuteInteractionCallback() throws ResourceException, SQLException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - InteractionCallback interactionCallback = createMock(InteractionCallback.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + InteractionCallback interactionCallback = mock(InteractionCallback.class); - expect( - interactionCallback.doInInteraction(interaction, - connectionFactory)).andStubReturn(new Object()); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, interactionCallback); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interactionCallback.doInInteraction(interaction,connectionFactory)).willReturn(new Object()); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionCallback); - verify(connectionFactory, connection, interaction, interactionCallback); + verify(interactionCallback).doInInteraction(interaction,connectionFactory); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteInputTrueTrueWithCreator() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordCreator creator = createMock(RecordCreator.class); - - Record inputOutputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordCreator creator = mock(RecordCreator.class); - expect( - interaction.execute(interactionSpec, inputOutputRecord, - inputOutputRecord)).andReturn(true); + Record inputOutputRecord = mock(Record.class); - interaction.close(); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - connection.close(); - - replay(connectionFactory, connection, interaction, creator); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputOutputRecord, inputOutputRecord)).willReturn(true); CciTemplate ct = new CciTemplate(connectionFactory); ct.setOutputRecordCreator(creator); ct.execute(interactionSpec, inputOutputRecord, inputOutputRecord); - verify(connectionFactory, connection, interaction, creator); + verify(interaction).execute(interactionSpec, inputOutputRecord, inputOutputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteInputTrueTrue() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - - Record inputOutputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect( - interaction.execute(interactionSpec, inputOutputRecord, - inputOutputRecord)).andReturn(true); - - interaction.close(); - - connection.close(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + Record inputOutputRecord = mock(Record.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputOutputRecord, inputOutputRecord)).willReturn(true); CciTemplate ct = new CciTemplate(connectionFactory); ct.execute(interactionSpec, inputOutputRecord, inputOutputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputOutputRecord, inputOutputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testTemplateExecuteInputFalseTrue() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - - Record inputOutputRecord = createMock(Record.class); - - InteractionSpec interactionSpec = createMock(InteractionSpec.class); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, inputOutputRecord)) - .andReturn(null); - - interaction.close(); - - connection.close(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + Record inputOutputRecord = mock(Record.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputOutputRecord)).willReturn(null); CciTemplate ct = new CciTemplate(connectionFactory); Record tmpOutputRecord = ct.execute(interactionSpec, inputOutputRecord); assertNull(tmpOutputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputOutputRecord); + verify(interaction).close(); + verify(connection).close(); } } diff --git a/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java b/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java index 4e5a3281d49f..e5e2f8a61752 100644 --- a/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/cci/EisOperationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.jca.cci; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.assertSame; - import javax.resource.ResourceException; import javax.resource.cci.Connection; import javax.resource.cci.ConnectionFactory; @@ -32,6 +29,9 @@ import org.springframework.jca.cci.object.MappingRecordOperation; import org.springframework.jca.cci.object.SimpleRecordOperation; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Thierry Templier * @author Chris Beams @@ -40,106 +40,88 @@ public class EisOperationTests { @Test public void testSimpleRecordOperation() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); SimpleRecordOperation query = new SimpleRecordOperation(connectionFactory, interactionSpec); - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, inputRecord)).andReturn(outputRecord); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord)).willReturn(outputRecord); query.execute(inputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testSimpleRecordOperationWithExplicitOutputRecord() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); SimpleRecordOperation operation = new SimpleRecordOperation(connectionFactory, interactionSpec); - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)).andReturn(true); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); operation.execute(inputRecord, outputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputRecord, outputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testSimpleRecordOperationWithInputOutputRecord() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - Record inputOutputRecord = createMock(Record.class); + Record inputOutputRecord = mock(Record.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); SimpleRecordOperation query = new SimpleRecordOperation(connectionFactory, interactionSpec); - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, inputOutputRecord, inputOutputRecord)).andReturn(true); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputOutputRecord, inputOutputRecord)).willReturn(true); query.execute(inputOutputRecord, inputOutputRecord); - verify(connectionFactory, connection, interaction); + verify(interaction).execute(interactionSpec, inputOutputRecord, inputOutputRecord); + verify(interaction).close(); + verify(connection).close(); } @Test public void testMappingRecordOperation() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordFactory recordFactory = createMock(RecordFactory.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordFactory recordFactory = mock(RecordFactory.class); - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - QueryCallDetector callDetector = createMock(QueryCallDetector.class); + QueryCallDetector callDetector = mock(QueryCallDetector.class); MappingRecordOperationImpl query = new MappingRecordOperationImpl(connectionFactory, interactionSpec); query.setCallDetector(callDetector); @@ -147,44 +129,33 @@ public void testMappingRecordOperation() throws ResourceException { Object inObj = new Object(); Object outObj = new Object(); - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(callDetector.callCreateInputRecord(recordFactory, inObj)).andReturn(inputRecord); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(interaction.execute(interactionSpec, inputRecord)).andReturn(outputRecord); - - expect(callDetector.callExtractOutputData(outputRecord)).andReturn(outObj); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, callDetector); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(callDetector.callCreateInputRecord(recordFactory, inObj)).willReturn(inputRecord); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord)).willReturn(outputRecord); + given(callDetector.callExtractOutputData(outputRecord)).willReturn(outObj); assertSame(outObj, query.execute(inObj)); - - verify(connectionFactory, connection, interaction, callDetector); + verify(interaction).close(); + verify(connection).close(); } @Test public void testMappingRecordOperationWithOutputRecordCreator() throws ResourceException { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - Connection connection = createMock(Connection.class); - Interaction interaction = createMock(Interaction.class); - RecordFactory recordFactory = createMock(RecordFactory.class); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordFactory recordFactory = mock(RecordFactory.class); - Record inputRecord = createMock(Record.class); - Record outputRecord = createMock(Record.class); + Record inputRecord = mock(Record.class); + Record outputRecord = mock(Record.class); - RecordCreator outputCreator = createMock(RecordCreator.class); + RecordCreator outputCreator = mock(RecordCreator.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - QueryCallDetector callDetector = createMock(QueryCallDetector.class); + QueryCallDetector callDetector = mock(QueryCallDetector.class); MappingRecordOperationImpl query = new MappingRecordOperationImpl(connectionFactory, interactionSpec); query.setOutputRecordCreator(outputCreator); @@ -193,31 +164,18 @@ public void testMappingRecordOperationWithOutputRecordCreator() throws ResourceE Object inObj = new Object(); Object outObj = new Object(); - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(callDetector.callCreateInputRecord(recordFactory, inObj)).andReturn(inputRecord); - - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(outputCreator.createRecord(recordFactory)).andReturn(outputRecord); - - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)).andReturn(true); - - expect(callDetector.callExtractOutputData(outputRecord)).andReturn(outObj); - - interaction.close(); - - connection.close(); - - replay(connectionFactory, connection, interaction, outputCreator, callDetector); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(callDetector.callCreateInputRecord(recordFactory, inObj)).willReturn(inputRecord); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(connectionFactory.getRecordFactory()).willReturn(recordFactory); + given(outputCreator.createRecord(recordFactory)).willReturn(outputRecord); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); + given(callDetector.callExtractOutputData(outputRecord)).willReturn(outObj); assertSame(outObj, query.execute(inObj)); - - verify(connectionFactory, connection, interaction, outputCreator, callDetector); + verify(interaction).close(); + verify(connection).close(); } diff --git a/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java b/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java index c19efddd551a..617f47f2413d 100644 --- a/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java +++ b/spring-tx/src/test/java/org/springframework/jca/support/LocalConnectionFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,14 @@ package org.springframework.jca.support; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; - import javax.resource.spi.ConnectionManager; import javax.resource.spi.ManagedConnectionFactory; import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Unit tests for the {@link LocalConnectionFactoryBean} class. * @@ -51,38 +51,24 @@ public void testGetObjectTypeIsNullIfConnectionFactoryHasNotBeenConfigured() thr @Test public void testCreatesVanillaConnectionFactoryIfNoConnectionManagerHasBeenConfigured() throws Exception { - final Object CONNECTION_FACTORY = new Object(); - - ManagedConnectionFactory managedConnectionFactory = createMock(ManagedConnectionFactory.class); - - expect(managedConnectionFactory.createConnectionFactory()).andReturn(CONNECTION_FACTORY); - replay(managedConnectionFactory); - + ManagedConnectionFactory managedConnectionFactory = mock(ManagedConnectionFactory.class); + given(managedConnectionFactory.createConnectionFactory()).willReturn(CONNECTION_FACTORY); LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean(); factory.setManagedConnectionFactory(managedConnectionFactory); factory.afterPropertiesSet(); assertEquals(CONNECTION_FACTORY, factory.getObject()); - - verify(managedConnectionFactory); } @Test public void testCreatesManagedConnectionFactoryIfAConnectionManagerHasBeenConfigured() throws Exception { - ManagedConnectionFactory managedConnectionFactory = createMock(ManagedConnectionFactory.class); - - ConnectionManager connectionManager = createMock(ConnectionManager.class); - - expect(managedConnectionFactory.createConnectionFactory(connectionManager)).andReturn(null); - - replay(connectionManager, managedConnectionFactory); - + ManagedConnectionFactory managedConnectionFactory = mock(ManagedConnectionFactory.class); + ConnectionManager connectionManager = mock(ConnectionManager.class); LocalConnectionFactoryBean factory = new LocalConnectionFactoryBean(); factory.setManagedConnectionFactory(managedConnectionFactory); factory.setConnectionManager(connectionManager); factory.afterPropertiesSet(); - - verify(connectionManager, managedConnectionFactory); + verify(managedConnectionFactory).createConnectionFactory(connectionManager); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java index 04e937b7eccc..510b1ccf471a 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java @@ -21,7 +21,6 @@ import javax.transaction.UserTransaction; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; import org.springframework.transaction.jta.JtaTransactionManager; @@ -30,6 +29,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 05.08.2005 @@ -55,33 +56,14 @@ public void testJtaTransactionManagerWithDefaultJndiLookupsAndNoUtFound() throws private void doTestJtaTransactionManagerWithDefaultJndiLookups(String tmName, boolean tmFound, boolean defaultUt) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); + UserTransaction ut = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); if (defaultUt) { - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); } - utControl.replay(); - - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - if (!defaultUt) { - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 2); - tm.begin(); - tmControl.setVoidCallable(1); - tm.commit(); - tmControl.setVoidCallable(1); + else { + given(tm.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); } - tmControl.replay(); JtaTransactionManager ptm = new JtaTransactionManager(); ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate(); @@ -122,25 +104,23 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - utControl.verify(); - tmControl.verify(); + + if (defaultUt) { + verify(ut).begin(); + verify(ut).commit(); + } + else { + verify(tm).begin(); + verify(tm).commit(); + } + } public void testJtaTransactionManagerWithCustomJndiLookups() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + + TransactionManager tm = mock(TransactionManager.class); JtaTransactionManager ptm = new JtaTransactionManager(); ptm.setUserTransactionName("jndi-ut"); @@ -168,33 +148,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - utControl.verify(); + verify(ut).begin(); + verify(ut).commit(); } public void testJtaTransactionManagerWithNotCacheUserTransaction() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl ut2Control = MockControl.createControl(UserTransaction.class); - UserTransaction ut2 = (UserTransaction) ut2Control.getMock(); - ut2.getStatus(); - ut2Control.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut2.getStatus(); - ut2Control.setReturnValue(Status.STATUS_ACTIVE, 2); - ut2.begin(); - ut2Control.setVoidCallable(1); - ut2.commit(); - ut2Control.setVoidCallable(1); - ut2Control.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + + UserTransaction ut2 = mock(UserTransaction.class); + given(ut2.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); JtaTransactionManager ptm = new JtaTransactionManager(); ptm.setJndiTemplate(new ExpectedLookupTemplate("java:comp/UserTransaction", ut)); @@ -228,8 +191,10 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - utControl.verify(); - ut2Control.verify(); + verify(ut).begin(); + verify(ut).commit(); + verify(ut2).begin(); + verify(ut2).commit(); } /** diff --git a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java index c13ea6bc4173..2c5a55790573 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java @@ -27,7 +27,6 @@ import javax.transaction.UserTransaction; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.tests.transaction.MockJtaTransaction; @@ -39,6 +38,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 12.05.2003 @@ -46,29 +47,10 @@ public class JtaTransactionManagerTests extends TestCase { public void testJtaTransactionManagerWithCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCommit(false); - synchControl.setVoidCallable(1); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCommit(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_COMMITTED); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -92,34 +74,19 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - utControl.verify(); - synchControl.verify(); + verify(ut).begin(); + verify(ut).commit(); + verify(synch).beforeCommit(false); + verify(synch).beforeCompletion(); + verify(synch).afterCommit(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_COMMITTED); } public void testJtaTransactionManagerWithCommitAndSynchronizationOnActual() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCommit(false); - synchControl.setVoidCallable(1); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCommit(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_COMMITTED); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -135,22 +102,18 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).begin(); + verify(ut).commit(); + verify(synch).beforeCommit(false); + verify(synch).beforeCompletion(); + verify(synch).afterCommit(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_COMMITTED); } public void testJtaTransactionManagerWithCommitAndSynchronizationNever() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn( + Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -166,31 +129,14 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); + verify(ut).begin(); + verify(ut).commit(); } public void testJtaTransactionManagerWithRollback() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.setTransactionTimeout(10); - utControl.setVoidCallable(1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -214,32 +160,17 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - utControl.verify(); - synchControl.verify(); + verify(ut).setTransactionTimeout(10); + verify(ut).begin(); + verify(ut).rollback(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } public void testJtaTransactionManagerWithRollbackAndSynchronizationOnActual() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.setTransactionTimeout(10); - utControl.setVoidCallable(1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -256,24 +187,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).setTransactionTimeout(10); + verify(ut).begin(); + verify(ut).rollback(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } public void testJtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.setTransactionTimeout(10); - utControl.setVoidCallable(1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -291,25 +214,17 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); + verify(ut).setTransactionTimeout(10); + verify(ut).begin(); + verify(ut, atLeastOnce()).getStatus(); + verify(ut).rollback(); } public void testJtaTransactionManagerWithExistingTransactionAndRollbackOnly() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -324,26 +239,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).setRollbackOnly(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } public void testJtaTransactionManagerWithExistingTransactionAndException() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -364,28 +269,17 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { } assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).setRollbackOnly(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } public void testJtaTransactionManagerWithExistingTransactionAndCommitException() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCommit(false); - synchControl.setThrowable(new OptimisticLockingFailureException("")); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); + willThrow(new OptimisticLockingFailureException("")).given(synch).beforeCommit(false); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -405,26 +299,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { } assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).setRollbackOnly(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } public void testJtaTransactionManagerWithExistingTransactionAndRollbackOnlyAndNoGlobalRollback() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); ptm.setGlobalRollbackOnParticipationFailure(false); @@ -440,24 +324,15 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).setRollbackOnly(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } public void testJtaTransactionManagerWithExistingTransactionAndExceptionAndNoGlobalRollback() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); ptm.setGlobalRollbackOnParticipationFailure(false); @@ -479,34 +354,19 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { } assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } public void testJtaTransactionManagerWithExistingTransactionAndJtaSynchronization() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + UserTransaction ut = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction tx = new MockJtaTransaction(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - tm.getTransaction(); - tmControl.setReturnValue(tx, 1); - - utControl.replay(); - tmControl.replay(); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(tx); - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); - synchControl.setVoidCallable(1); - synchControl.replay(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -524,27 +384,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { tx.getSynchronization().beforeCompletion(); tx.getSynchronization().afterCompletion(Status.STATUS_ROLLEDBACK); - utControl.verify(); - tmControl.verify(); - synchControl.verify(); + verify(ut).setRollbackOnly(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } public void testJtaTransactionManagerWithExistingTransactionAndSynchronizationOnActual() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -560,18 +409,14 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).setRollbackOnly(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } public void testJtaTransactionManagerWithExistingTransactionAndSynchronizationNever() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -588,25 +433,14 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); + verify(ut).setRollbackOnly(); } public void testJtaTransactionManagerWithExistingAndPropagationSupports() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -622,24 +456,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(ut).setRollbackOnly(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } public void testJtaTransactionManagerWithPropagationSupports() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - utControl.replay(); - - MockControl synchControl = MockControl.createControl(TransactionSynchronization.class); - final TransactionSynchronization synch = (TransactionSynchronization) synchControl.getMock(); - synch.beforeCompletion(); - synchControl.setVoidCallable(1); - synch.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); - synchControl.setVoidCallable(1); - synchControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); + + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -655,16 +481,13 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - synchControl.verify(); + verify(synch).beforeCompletion(); + verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } public void testJtaTransactionManagerWithPropagationSupportsAndSynchronizationOnActual() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -681,16 +504,11 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { } }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - - utControl.verify(); } public void testJtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -707,25 +525,14 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { } }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - - utControl.verify(); } public void testJtaTransactionManagerWithPropagationNotSupported() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.suspend(); - tmControl.setReturnValue(tx, 1); - tm.resume(tx); - tmControl.setVoidCallable(1); - utControl.replay(); - tmControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); + Transaction tx = mock(Transaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.suspend()).willReturn(tx); JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -740,35 +547,17 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - tmControl.verify(); + verify(tm).resume(tx); } public void testJtaTransactionManagerWithPropagationRequiresNew() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 5); - tm.suspend(); - tmControl.setReturnValue(tx, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - tm.resume(tx); - tmControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); - tmControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); + Transaction tx = mock(Transaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + given(tm.suspend()).willReturn(tx); final JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -803,22 +592,15 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - tmControl.verify(); + verify(ut, times(2)).begin(); + verify(ut, times(2)).commit(); + verify(tm).resume(tx); } public void testJtaTransactionManagerWithPropagationRequiresNewWithinSupports() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); final JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -850,28 +632,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); + verify(ut).begin(); + verify(ut).commit(); } public void testJtaTransactionManagerWithPropagationRequiresNewAndExisting() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - tm.suspend(); - tmControl.setReturnValue(tx, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - tm.resume(tx); - tmControl.setVoidCallable(1); - utControl.replay(); - tmControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); + Transaction tx = mock(Transaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.suspend()).willReturn(tx); JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -885,21 +655,16 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - tmControl.verify(); + verify(ut).begin(); + verify(ut).commit(); + verify(tm).resume(tx); } public void testJtaTransactionManagerWithPropagationRequiresNewAndExistingWithSuspendException() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.suspend(); - tmControl.setThrowable(new SystemException()); - utControl.replay(); - tmControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + willThrow(new SystemException()).given(tm).suspend(); JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -918,28 +683,15 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { // expected } assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - - utControl.verify(); - tmControl.verify(); } public void testJtaTransactionManagerWithPropagationRequiresNewAndExistingWithBeginException() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.suspend(); - tmControl.setReturnValue(tx, 1); - ut.begin(); - utControl.setThrowable(new SystemException()); - tm.resume(tx); - tmControl.setVoidCallable(1); - utControl.replay(); - tmControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); + Transaction tx = mock(Transaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.suspend()).willReturn(tx); + willThrow(new SystemException()).given(ut).begin(); JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -958,27 +710,14 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { // expected } assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - - utControl.verify(); - tmControl.verify(); + verify(tm).resume(tx); } public void testJtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 3); - tm.suspend(); - tmControl.setReturnValue(tx, 1); - tm.begin(); - tmControl.setVoidCallable(1); - tm.commit(); - tmControl.setVoidCallable(1); - tm.resume(tx); - tmControl.setVoidCallable(1); - tmControl.replay(); + TransactionManager tm = mock(TransactionManager.class); + Transaction tx = mock(Transaction.class); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.suspend()).willReturn(tx); JtaTransactionManager ptm = newJtaTransactionManager(tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -992,15 +731,14 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { }); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - tmControl.verify(); + verify(tm).begin(); + verify(tm).commit(); + verify(tm).resume(tx); } public void testJtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -1018,16 +756,11 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { // expected } assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - - utControl.verify(); } public void testJtaTransactionManagerWithIsolationLevel() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1044,16 +777,11 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { catch (InvalidIsolationLevelException ex) { // expected } - - utControl.verify(); } public void testJtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setThrowable(new SystemException("system exception")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willThrow(new SystemException("system exception")); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1069,20 +797,11 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { catch (TransactionSystemException ex) { // expected } - - utControl.verify(); } public void testJtaTransactionManagerWithNestedBegin() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -1094,17 +813,14 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { } }); - utControl.verify(); + verify(ut).begin(); + verify(ut).commit(); } public void testJtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.begin(); - utControl.setThrowable(new NotSupportedException("not supported")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + willThrow(new NotSupportedException("not supported")).given(ut).begin(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1121,18 +837,12 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { catch (NestedTransactionNotSupportedException ex) { // expected } - - utControl.verify(); } public void testJtaTransactionManagerWithUnsupportedOperationExceptionOnNestedBegin() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.begin(); - utControl.setThrowable(new UnsupportedOperationException("not supported")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + willThrow(new UnsupportedOperationException("not supported")).given(ut).begin(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1149,18 +859,12 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { catch (NestedTransactionNotSupportedException ex) { // expected } - - utControl.verify(); } public void testJtaTransactionManagerWithSystemExceptionOnBegin() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setThrowable(new SystemException("system exception")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); + willThrow(new SystemException("system exception")).given(ut).begin(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1176,22 +880,13 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { catch (CannotCreateTransactionException ex) { // expected } - - utControl.verify(); } public void testJtaTransactionManagerWithRollbackExceptionOnCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setThrowable(new RollbackException("unexpected rollback")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + willThrow(new RollbackException("unexpected rollback")).given(ut).commit(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1214,7 +909,7 @@ public void afterCompletion(int status) { // expected } - utControl.verify(); + verify(ut).begin(); } public void testJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnly() throws Exception { @@ -1226,22 +921,10 @@ public void testJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnlyAndFailE } private void doTestJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnly(boolean failEarly) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_MARKED_ROLLBACK, 3); - ut.begin(); - utControl.setVoidCallable(1); - if (failEarly) { - ut.rollback(); - } - else { - ut.commit(); - } - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_MARKED_ROLLBACK, Status.STATUS_MARKED_ROLLBACK, + Status.STATUS_MARKED_ROLLBACK); JtaTransactionManager tm = newJtaTransactionManager(ut); if (failEarly) { @@ -1285,21 +968,20 @@ public void afterCompletion(int status) { } } - utControl.verify(); + verify(ut).begin(); + if (failEarly) { + verify(ut).rollback(); + } + else { + verify(ut).commit(); + } } public void testJtaTransactionManagerWithHeuristicMixedExceptionOnCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setThrowable(new HeuristicMixedException("heuristic exception")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + willThrow(new HeuristicMixedException("heuristic exception")).given(ut).commit(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1323,21 +1005,14 @@ public void afterCompletion(int status) { assertTrue(ex.getOutcomeState() == HeuristicCompletionException.STATE_MIXED); } - utControl.verify(); + verify(ut).begin(); } public void testJtaTransactionManagerWithHeuristicRollbackExceptionOnCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setThrowable(new HeuristicRollbackException("heuristic exception")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + willThrow(new HeuristicRollbackException("heuristic exception")).given(ut).commit(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1361,21 +1036,14 @@ public void afterCompletion(int status) { assertTrue(ex.getOutcomeState() == HeuristicCompletionException.STATE_ROLLED_BACK); } - utControl.verify(); + verify(ut).begin(); } public void testJtaTransactionManagerWithSystemExceptionOnCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setThrowable(new SystemException("system exception")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + willThrow(new SystemException("system exception")).given(ut).commit(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1398,21 +1066,13 @@ public void afterCompletion(int status) { // expected } - utControl.verify(); + verify(ut).begin(); } public void testJtaTransactionManagerWithSystemExceptionOnRollback() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setThrowable(new SystemException("system exception")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); + willThrow(new SystemException("system exception")).given(ut).rollback(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1435,17 +1095,13 @@ public void afterCompletion(int status) { // expected } - utControl.verify(); + verify(ut).begin(); } public void testJtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.setRollbackOnly(); - utControl.setThrowable(new IllegalStateException("no existing transaction")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1461,18 +1117,12 @@ protected void doInTransactionWithoutResult(TransactionStatus status) { catch (TransactionSystemException ex) { // expected } - - utControl.verify(); } public void testJtaTransactionManagerWithSystemExceptionOnRollbackOnly() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.setRollbackOnly(); - utControl.setThrowable(new SystemException("system exception")); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + willThrow(new SystemException("system exception")).given(ut).setRollbackOnly(); try { JtaTransactionManager ptm = newJtaTransactionManager(ut); @@ -1494,22 +1144,12 @@ public void afterCompletion(int status) { catch (TransactionSystemException ex) { // expected } - - utControl.verify(); } public void testJtaTransactionManagerWithDoubleCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); @@ -1527,21 +1167,13 @@ public void testJtaTransactionManagerWithDoubleCommit() throws Exception { // expected } - utControl.verify(); + verify(ut).begin(); + verify(ut).commit(); } public void testJtaTransactionManagerWithDoubleRollback() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); @@ -1559,21 +1191,13 @@ public void testJtaTransactionManagerWithDoubleRollback() throws Exception { // expected } - utControl.verify(); + verify(ut).begin(); + verify(ut).rollback(); } public void testJtaTransactionManagerWithRollbackAndCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); JtaTransactionManager ptm = newJtaTransactionManager(ut); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); @@ -1591,7 +1215,8 @@ public void testJtaTransactionManagerWithRollbackAndCommit() throws Exception { // expected } - utControl.verify(); + verify(ut).begin(); + verify(ut).rollback(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java index 0a49a21b6369..b097bf382c36 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java @@ -19,11 +19,10 @@ import java.lang.reflect.Method; import junit.framework.TestCase; -import org.easymock.MockControl; +import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; -import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.MockCallbackPreferringTransactionManager; import org.springframework.transaction.NoTransactionException; @@ -34,6 +33,8 @@ import org.springframework.transaction.UnexpectedRollbackException; import org.springframework.transaction.interceptor.TransactionAspectSupport.TransactionInfo; +import static org.mockito.BDDMockito.*; + /** * Mock object based tests for transaction aspects. * True unit test in that it tests how the transaction aspect uses @@ -69,11 +70,7 @@ public AbstractTransactionAspectTests() { public void testNoTransaction() throws Exception { - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); - - // expect no calls - ptmControl.replay(); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); TestBean tb = new TestBean(); TransactionAttributeSource tas = new MapTransactionAttributeSource(); @@ -87,7 +84,8 @@ public void testNoTransaction() throws Exception { itb.getName(); checkTransactionStatus(false); - ptmControl.verify(); + // expect no calls + verifyZeroInteractions(ptm); } /** @@ -99,15 +97,10 @@ public void testTransactionShouldSucceed() throws Exception { MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(getNameMethod, txatt); - TransactionStatus status = transactionStatusForNewTransaction(); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + TransactionStatus status = mock(TransactionStatus.class); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); // expect a transaction - ptm.getTransaction(txatt); - ptmControl.setReturnValue(status, 1); - ptm.commit(status); - ptmControl.setVoidCallable(1); - ptmControl.replay(); + given(ptm.getTransaction(txatt)).willReturn(status); TestBean tb = new TestBean(); ITestBean itb = (ITestBean) advised(tb, ptm, tas); @@ -116,7 +109,7 @@ public void testTransactionShouldSucceed() throws Exception { itb.getName(); checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(status); } /** @@ -178,15 +171,10 @@ public void testTwoTransactionsShouldSucceed() throws Exception { MapTransactionAttributeSource tas2 = new MapTransactionAttributeSource(); tas2.register(setNameMethod, txatt); - TransactionStatus status = transactionStatusForNewTransaction(); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + TransactionStatus status = mock(TransactionStatus.class); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); // expect a transaction - ptm.getTransaction(txatt); - ptmControl.setReturnValue(status, 2); - ptm.commit(status); - ptmControl.setVoidCallable(2); - ptmControl.replay(); + given(ptm.getTransaction(txatt)).willReturn(status); TestBean tb = new TestBean(); ITestBean itb = (ITestBean) advised(tb, ptm, new TransactionAttributeSource[] {tas1, tas2}); @@ -197,7 +185,7 @@ public void testTwoTransactionsShouldSucceed() throws Exception { itb.setName("myName"); checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm, times(2)).commit(status); } /** @@ -209,16 +197,10 @@ public void testTransactionShouldSucceedWithNotNew() throws Exception { MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(getNameMethod, txatt); - MockControl statusControl = MockControl.createControl(TransactionStatus.class); - TransactionStatus status = (TransactionStatus) statusControl.getMock(); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + TransactionStatus status = mock(TransactionStatus.class); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); // expect a transaction - ptm.getTransaction(txatt); - ptmControl.setReturnValue(status, 1); - ptm.commit(status); - ptmControl.setVoidCallable(1); - ptmControl.replay(); + given(ptm.getTransaction(txatt)).willReturn(status); TestBean tb = new TestBean(); ITestBean itb = (ITestBean) advised(tb, ptm, tas); @@ -228,7 +210,7 @@ public void testTransactionShouldSucceedWithNotNew() throws Exception { itb.getName(); checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(status); } public void testEnclosingTransactionWithNonTransactionMethodOnAdvisedInside() throws Throwable { @@ -237,15 +219,10 @@ public void testEnclosingTransactionWithNonTransactionMethodOnAdvisedInside() th MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(exceptionalMethod, txatt); - TransactionStatus status = transactionStatusForNewTransaction(); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + TransactionStatus status = mock(TransactionStatus.class); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); // Expect a transaction - ptm.getTransaction(txatt); - ptmControl.setReturnValue(status, 1); - ptm.commit(status); - ptmControl.setVoidCallable(1); - ptmControl.replay(); + given(ptm.getTransaction(txatt)).willReturn(status); final String spouseName = "innerName"; @@ -278,7 +255,7 @@ public String getName() { checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(status); } public void testEnclosingTransactionWithNestedTransactionOnAdvisedInside() throws Throwable { @@ -291,24 +268,13 @@ public void testEnclosingTransactionWithNestedTransactionOnAdvisedInside() throw tas.register(outerMethod, outerTxatt); tas.register(innerMethod, innerTxatt); - TransactionStatus outerStatus = transactionStatusForNewTransaction(); - TransactionStatus innerStatus = transactionStatusForNewTransaction(); + TransactionStatus outerStatus = mock(TransactionStatus.class); + TransactionStatus innerStatus = mock(TransactionStatus.class); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); // Expect a transaction - ptm.getTransaction(outerTxatt); - ptmControl.setReturnValue(outerStatus, 1); - - ptm.getTransaction(innerTxatt); - ptmControl.setReturnValue(innerStatus, 1); - - ptm.commit(innerStatus); - ptmControl.setVoidCallable(1); - - ptm.commit(outerStatus); - ptmControl.setVoidCallable(1); - ptmControl.replay(); + given(ptm.getTransaction(outerTxatt)).willReturn(outerStatus); + given(ptm.getTransaction(innerTxatt)).willReturn(innerStatus); final String spouseName = "innerName"; @@ -344,7 +310,8 @@ public String getName() { checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(innerStatus); + verify(ptm).commit(outerStatus); } public void testRollbackOnCheckedException() throws Throwable { @@ -401,29 +368,21 @@ public boolean rollbackOn(Throwable t) { MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(m, txatt); - MockControl statusControl = MockControl.createControl(TransactionStatus.class); - TransactionStatus status = (TransactionStatus) statusControl.getMock(); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + TransactionStatus status = mock(TransactionStatus.class); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); // Gets additional call(s) from TransactionControl - ptm.getTransaction(txatt); - ptmControl.setReturnValue(status, 1); + given(ptm.getTransaction(txatt)).willReturn(status); - if (shouldRollback) { - ptm.rollback(status); - } - else { - ptm.commit(status); - } TransactionSystemException tex = new TransactionSystemException("system exception"); if (rollbackException) { - ptmControl.setThrowable(tex, 1); - } - else { - ptmControl.setVoidCallable(1); + if (shouldRollback) { + willThrow(tex).given(ptm).rollback(status); + } + else { + willThrow(tex).given(ptm).commit(status); + } } - ptmControl.replay(); TestBean tb = new TestBean(); ITestBean itb = (ITestBean) advised(tb, ptm, tas); @@ -441,7 +400,14 @@ public boolean rollbackOn(Throwable t) { } } - ptmControl.verify(); + if (!rollbackException) { + if (shouldRollback) { + verify(ptm).rollback(status); + } + else { + verify(ptm).commit(status); + } + } } /** @@ -454,15 +420,10 @@ public void testProgrammaticRollback() throws Exception { MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(m, txatt); - TransactionStatus status = transactionStatusForNewTransaction(); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + TransactionStatus status = mock(TransactionStatus.class); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); - ptm.getTransaction(txatt); - ptmControl.setReturnValue(status, 1); - ptm.commit(status); - ptmControl.setVoidCallable(1); - ptmControl.replay(); + given(ptm.getTransaction(txatt)).willReturn(status); final String name = "jenny"; TestBean tb = new TestBean() { @@ -479,15 +440,7 @@ public String getName() { // verification!? assertTrue(name.equals(itb.getName())); - ptmControl.verify(); - } - - /** - * @return a TransactionStatus object configured for a new transaction - */ - private TransactionStatus transactionStatusForNewTransaction() { - MockControl statusControl = MockControl.createControl(TransactionStatus.class); - return (TransactionStatus) statusControl.getMock(); + verify(ptm).commit(status); } /** @@ -501,13 +454,10 @@ public void testCannotCreateTransaction() throws Exception { MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(m, txatt); - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); // Expect a transaction - ptm.getTransaction(txatt); CannotCreateTransactionException ex = new CannotCreateTransactionException("foobar", null); - ptmControl.setThrowable(ex); - ptmControl.replay(); + given(ptm.getTransaction(txatt)).willThrow(ex); TestBean tb = new TestBean() { @Override @@ -525,7 +475,6 @@ public String getName() { catch (CannotCreateTransactionException thrown) { assertTrue(thrown == ex); } - ptmControl.verify(); } /** @@ -542,16 +491,12 @@ public void testCannotCommitTransaction() throws Exception { // Method m2 = getNameMethod; // No attributes for m2 - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); - TransactionStatus status = transactionStatusForNewTransaction(); - ptm.getTransaction(txatt); - ptmControl.setReturnValue(status); + TransactionStatus status = mock(TransactionStatus.class); + given(ptm.getTransaction(txatt)).willReturn(status); UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null); - ptm.commit(status); - ptmControl.setThrowable(ex); - ptmControl.replay(); + willThrow(ex).given(ptm).commit(status); TestBean tb = new TestBean(); ITestBean itb = (ITestBean) advised(tb, ptm, tas); @@ -567,7 +512,6 @@ public void testCannotCommitTransaction() throws Exception { // Should have invoked target and changed name assertTrue(itb.getName() == name); - ptmControl.verify(); } protected void checkTransactionStatus(boolean expected) { diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java index 1dda314ddadf..268cee7bb7bb 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java @@ -24,23 +24,24 @@ import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -import org.easymock.MockControl; import org.springframework.aop.support.AopUtils; import org.springframework.aop.support.StaticMethodMatcherPointcut; import org.springframework.aop.target.HotSwappableTargetSource; -import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.beans.FatalBeanException; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionStatus; +import static org.mockito.BDDMockito.*; + /** * Test cases for AOP transaction management. * @@ -116,19 +117,16 @@ public void testGetsAreNotTransactionalWithProxyFactory3() throws NoSuchMethodEx private void doTestGetsAreNotTransactional(final ITestBean testBean) { // Install facade - MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); - PlatformTransactionManager ptm = (PlatformTransactionManager) ptmControl.getMock(); - // Expect no methods - ptmControl.replay(); + PlatformTransactionManager ptm = mock(PlatformTransactionManager.class); PlatformTransactionManagerFacade.delegate = ptm; assertTrue("Age should not be " + testBean.getAge(), testBean.getAge() == 666); - // Check no calls - ptmControl.verify(); + + // Expect no methods + verifyZeroInteractions(ptm); // Install facade expecting a call - MockControl statusControl = MockControl.createControl(TransactionStatus.class); - final TransactionStatus ts = (TransactionStatus) statusControl.getMock(); + final TransactionStatus ts = mock(TransactionStatus.class); ptm = new PlatformTransactionManager() { private boolean invoked; @Override @@ -158,7 +156,6 @@ public void rollback(TransactionStatus status) throws TransactionException { int age = 666; testBean.setAge(age); assertTrue(testBean.getAge() == age); - ptmControl.verify(); } public void testGetBeansOfTypeWithAbstract() { diff --git a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java index 5630bd821974..802b7fd028c8 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java @@ -20,11 +20,7 @@ import javax.transaction.Status; import javax.transaction.UserTransaction; -import com.ibm.wsspi.uow.UOWAction; -import com.ibm.wsspi.uow.UOWException; -import com.ibm.wsspi.uow.UOWManager; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; @@ -37,6 +33,12 @@ import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionSynchronizationManager; +import com.ibm.wsspi.uow.UOWAction; +import com.ibm.wsspi.uow.UOWException; +import com.ibm.wsspi.uow.UOWManager; + +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller */ @@ -64,17 +66,8 @@ public Object doInTransaction(TransactionStatus status) { } public void testUowManagerAndUserTransactionFoundInJndi() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn( Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); MockUOWManager manager = new MockUOWManager(); ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate(); @@ -97,6 +90,8 @@ public Object doInTransaction(TransactionStatus status) { assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); assertFalse(manager.getJoined()); assertFalse(manager.getRollbackOnly()); + verify(ut).begin(); + verify(ut).commit(); } public void testPropagationMandatoryFailsInCaseOfNoExistingTransaction() { diff --git a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java index ff819d3ede57..c0c567c1d3d8 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java @@ -16,8 +16,6 @@ package org.springframework.transaction.support; -import static org.easymock.EasyMock.createMock; - import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; @@ -27,15 +25,17 @@ import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.util.SerializationTestUtils; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson */ public class JtaTransactionManagerSerializationTests extends TestCase { public void testSerializable() throws Exception { - UserTransaction ut1 = createMock(UserTransaction.class); - UserTransaction ut2 = createMock(UserTransaction.class); - TransactionManager tm = createMock(TransactionManager.class); + UserTransaction ut1 = mock(UserTransaction.class); + UserTransaction ut2 = mock(UserTransaction.class); + TransactionManager tm = mock(TransactionManager.class); JtaTransactionManager jtam = new JtaTransactionManager(); jtam.setUserTransaction(ut1); diff --git a/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java b/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java index 9939aaf03493..cb08fa91a116 100644 --- a/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java +++ b/spring-web/src/test/java/org/springframework/http/MockHttpOutputMessage.java @@ -16,13 +16,13 @@ package org.springframework.http; -import static org.mockito.Mockito.spy; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; +import static org.mockito.BDDMockito.*; + /** * @author Arjen Poutsma */ diff --git a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java index 0ea0462a5045..1c11bb0a1959 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java @@ -22,6 +22,7 @@ import java.io.StringReader; import java.nio.charset.Charset; import java.util.List; + import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; @@ -32,7 +33,6 @@ import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.junit.Before; import org.junit.Test; - import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; @@ -45,8 +45,7 @@ import org.springframework.util.MultiValueMap; import static org.junit.Assert.*; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; +import static org.mockito.BDDMockito.*; /** * @author Arjen Poutsma diff --git a/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java index 7fd414b627cd..75de8e40199c 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/xml/MarshallingHttpMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,18 +19,20 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; - import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; -/** @author Arjen Poutsma */ +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + +/** + * @author Arjen Poutsma + */ public class MarshallingHttpMessageConverterTests { private MarshallingHttpMessageConverter converter; @@ -41,9 +43,8 @@ public class MarshallingHttpMessageConverterTests { @Before public void setUp() { - marshaller = createMock(Marshaller.class); - unmarshaller = createMock(Unmarshaller.class); - + marshaller = mock(Marshaller.class); + unmarshaller = mock(Unmarshaller.class); converter = new MarshallingHttpMessageConverter(marshaller, unmarshaller); } @@ -52,12 +53,10 @@ public void read() throws Exception { String body = "Hello World"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8")); - expect(unmarshaller.unmarshal(isA(StreamSource.class))).andReturn(body); + given(unmarshaller.unmarshal(isA(StreamSource.class))).willReturn(body); - replay(marshaller, unmarshaller); String result = (String) converter.read(Object.class, inputMessage); assertEquals("Invalid result", body, result); - verify(marshaller, unmarshaller); } @Test @@ -65,12 +64,9 @@ public void write() throws Exception { String body = "Hello World"; MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); - marshaller.marshal(eq(body), isA(StreamResult.class)); - - replay(marshaller, unmarshaller); converter.write(body, null, outputMessage); assertEquals("Invalid content-type", new MediaType("application", "xml"), outputMessage.getHeaders().getContentType()); - verify(marshaller, unmarshaller); + verify(marshaller).marshal(eq(body), isA(StreamResult.class)); } } diff --git a/spring-web/src/test/java/org/springframework/remoting/jaxrpc/JaxRpcSupportTests.java b/spring-web/src/test/java/org/springframework/remoting/jaxrpc/JaxRpcSupportTests.java index 975d9537a304..d5606f9f3a26 100644 --- a/spring-web/src/test/java/org/springframework/remoting/jaxrpc/JaxRpcSupportTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/jaxrpc/JaxRpcSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import java.net.URL; import java.rmi.Remote; import java.rmi.RemoteException; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -34,12 +33,11 @@ import javax.xml.rpc.Stub; import junit.framework.TestCase; -import org.easymock.ArgumentsMatcher; -import org.easymock.MockControl; import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.RemoteLookupFailureException; -import org.springframework.util.ObjectUtils; + +import static org.mockito.BDDMockito.*; /** * @author Juergen Hoeller @@ -117,7 +115,6 @@ public void testJaxRpcPortProxyFactoryBean() throws Exception { IRemoteBean proxy = (IRemoteBean) factory.getObject(); proxy.setName("myName"); assertEquals("myName", RemoteBean.name); - MockServiceFactory.service1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithProperties() throws Exception { @@ -145,7 +142,6 @@ public void testJaxRpcPortProxyFactoryBeanWithProperties() throws Exception { IRemoteBean proxy = (IRemoteBean) factory.getObject(); proxy.setName("myName"); assertEquals("myName", RemoteBean.name); - MockServiceFactory.service1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithCustomProperties() throws Exception { @@ -173,7 +169,6 @@ public void testJaxRpcPortProxyFactoryBeanWithCustomProperties() throws Exceptio IRemoteBean proxy = (IRemoteBean) factory.getObject(); proxy.setName("myName"); assertEquals("myName", RemoteBean.name); - MockServiceFactory.service1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithCustomPropertyMap() throws Exception { @@ -203,7 +198,6 @@ public void testJaxRpcPortProxyFactoryBeanWithCustomPropertyMap() throws Excepti IRemoteBean proxy = (IRemoteBean) factory.getObject(); proxy.setName("myName"); assertEquals("myName", RemoteBean.name); - MockServiceFactory.service1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithDynamicCalls() throws Exception { @@ -219,13 +213,11 @@ public void testJaxRpcPortProxyFactoryBeanWithDynamicCalls() throws Exception { assertTrue(factory.getObject() instanceof IBusinessBean); IBusinessBean proxy = (IBusinessBean) factory.getObject(); proxy.setName("myName"); - MockServiceFactory.service1Control.verify(); - CallMockServiceFactory.call1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndProperties() throws Exception { JaxRpcPortProxyFactoryBean factory = new JaxRpcPortProxyFactoryBean(); - factory.setServiceFactoryClass(CallWithPropertiesMockServiceFactory.class); + factory.setServiceFactoryClass(CallMockServiceFactory.class); factory.setNamespaceUri("myNamespace"); factory.setServiceName("myService1"); factory.setPortName("myPort"); @@ -240,8 +232,11 @@ public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndProperties() throws assertTrue(factory.getObject() instanceof IBusinessBean); IBusinessBean proxy = (IBusinessBean) factory.getObject(); proxy.setName("myName"); - MockServiceFactory.service1Control.verify(); - CallMockServiceFactory.call1Control.verify(); + + verify(CallMockServiceFactory.call1).setProperty(Call.USERNAME_PROPERTY, "user"); + verify(CallMockServiceFactory.call1).setProperty(Call.PASSWORD_PROPERTY, "pw"); + verify(CallMockServiceFactory.call1).setTargetEndpointAddress("ea"); + verify(CallMockServiceFactory.call1).setProperty(Call.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); } public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndServiceException() throws Exception { @@ -310,9 +305,6 @@ public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndRemoteException_() assertEquals("myName", RemoteBean.name); assertEquals(1, serviceFactory.serviceCount); - MockServiceFactory.service1Control.verify(); - CallMockServiceFactory.call1Control.verify(); - ExceptionCallMockServiceFactory.call2Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndRemoteExceptionAndRefresh() throws Exception { @@ -344,9 +336,6 @@ public void testJaxRpcPortProxyFactoryBeanWithDynamicCallsAndRemoteExceptionAndR assertEquals("myName", RemoteBean.name); assertEquals(2, serviceFactory.serviceCount); - MockServiceFactory.service1Control.verify(); - CallMockServiceFactory.call1Control.verify(); - ExceptionCallMockServiceFactory.call2Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithPortInterface() throws Exception { @@ -363,7 +352,6 @@ public void testJaxRpcPortProxyFactoryBeanWithPortInterface() throws Exception { IBusinessBean proxy = (IBusinessBean) factory.getObject(); proxy.setName("myName"); assertEquals("myName", RemoteBean.name); - MockServiceFactory.service1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndServiceException() throws Exception { @@ -436,7 +424,6 @@ public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteException() assertEquals("myName", RemoteBean.name); assertEquals(1, serviceFactory.serviceCount); - MockServiceFactory.service1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteExceptionAndRefresh() throws Exception { @@ -470,30 +457,25 @@ public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteExceptionAnd assertEquals("myName", RemoteBean.name); assertEquals(2, serviceFactory.serviceCount); - MockServiceFactory.service1Control.verify(); } public static class MockServiceFactory extends ServiceFactory { - protected static MockControl service1Control; protected static Service service1; - protected static MockControl service2Control; protected static Service service2; protected int serviceCount = 0; public MockServiceFactory() throws Exception { - service1Control = MockControl.createControl(Service.class); - service1 = (Service) service1Control.getMock(); - service2Control = MockControl.createControl(Service.class); - service2 = (Service) service2Control.getMock(); + service1 = mock(Service.class); + service2 = mock(Service.class); initMocks(); - service1Control.replay(); } protected void initMocks() throws Exception { - service1.getPort(new QName("myNamespace", "myPort"), IRemoteBean.class); - service1Control.setReturnValue(new RemoteBean()); + RemoteBean remoteBean = new RemoteBean(); + given(service1.getPort(new QName("myNamespace", "myPort"), + IRemoteBean.class)).willReturn(remoteBean); } @Override @@ -572,15 +554,14 @@ public ExceptionMockServiceFactory() throws Exception { @Override protected void initMocks() throws Exception { super.initMocks(); - service1.getPort(new QName("myNamespace", "myPort"), IRemoteBean.class); - service1Control.setReturnValue(new RemoteBean()); + given(service1.getPort(new QName("myNamespace", "myPort"), + IRemoteBean.class)).willReturn(new RemoteBean()); } } public static class CallMockServiceFactory extends MockServiceFactory { - protected static MockControl call1Control; protected static Call call1; public CallMockServiceFactory() throws Exception { @@ -589,38 +570,15 @@ public CallMockServiceFactory() throws Exception { @Override protected void initMocks() throws Exception { - initStandardCall(1); - } - - protected void initStandardCall(int count) throws Exception { - call1Control = MockControl.createControl(Call.class); - call1 = (Call) call1Control.getMock(); - service1.createCall(new QName("myNamespace", "myPort"), "setName"); - service1Control.setReturnValue(call1, count); - call1.invoke(new Object[] {"myName"}); - call1Control.setMatcher(new ArgumentsMatcher() { - @Override - public boolean matches(Object[] objects, Object[] objects1) { - return Arrays.equals((Object[]) objects[0], (Object[]) objects1[0]); - } - @Override - public String toString(Object[] objects) { - return ObjectUtils.nullSafeToString(objects[0]); - } - }); - call1Control.setReturnValue(null, count); - extendStandardCall(); - call1Control.replay(); - } - - protected void extendStandardCall() { + call1 = mock(Call.class); + given(service1.createCall(new QName("myNamespace", "myPort"), "setName")).willReturn(call1); } } - public static class ExceptionCallMockServiceFactory extends CallMockServiceFactory { + public static class ExceptionCallMockServiceFactory extends MockServiceFactory { - protected static MockControl call2Control; + protected static Call call1; protected static Call call2; public ExceptionCallMockServiceFactory() throws Exception { @@ -628,47 +586,10 @@ public ExceptionCallMockServiceFactory() throws Exception { @Override protected void initMocks() throws Exception { - initExceptionCall(); - initStandardCall(2); - } - - protected void initExceptionCall() throws Exception { - call2Control = MockControl.createControl(Call.class); - call2 = (Call) call2Control.getMock(); - service1.createCall(new QName("myNamespace", "myPort"), "setName"); - service1Control.setReturnValue(call2); - call2.invoke(new Object[] {"exception"}); - call2Control.setMatcher(new ArgumentsMatcher() { - @Override - public boolean matches(Object[] objects, Object[] objects1) { - return Arrays.equals((Object[]) objects[0], (Object[]) objects1[0]); - } - @Override - public String toString(Object[] objects) { - return ObjectUtils.nullSafeToString(objects[0]); - } - }); - call2Control.setThrowable(new RemoteException()); - call2Control.replay(); - } - } - - - public static class CallWithPropertiesMockServiceFactory extends CallMockServiceFactory { - - public CallWithPropertiesMockServiceFactory() throws Exception { - } - - @Override - protected void extendStandardCall() { - call1.setProperty(Call.USERNAME_PROPERTY, "user"); - call1Control.setVoidCallable(); - call1.setProperty(Call.PASSWORD_PROPERTY, "pw"); - call1Control.setVoidCallable(); - call1.setTargetEndpointAddress("ea"); - call1Control.setVoidCallable(); - call1.setProperty(Call.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE); - call1Control.setVoidCallable(); + call1 = mock(Call.class); + call2 = mock(Call.class); + given(service1.createCall(new QName("myNamespace", "myPort"), "setName")).willReturn(call2, call1); + given(call2.invoke(new Object[] { "exception" })).willThrow(new RemoteException()); } } diff --git a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java index 7149dece12f2..55457d59821d 100644 --- a/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/DefaultResponseErrorHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,15 +21,13 @@ import org.junit.Before; import org.junit.Test; - import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpResponse; -import static org.easymock.EasyMock.*; - import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * Unit tests for {@link DefaultResponseErrorHandler}. @@ -45,27 +43,19 @@ public class DefaultResponseErrorHandlerTests { @Before public void setUp() throws Exception { handler = new DefaultResponseErrorHandler(); - response = createMock(ClientHttpResponse.class); + response = mock(ClientHttpResponse.class); } @Test public void hasErrorTrue() throws Exception { - expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND); - - replay(response); + given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND); assertTrue(handler.hasError(response)); - - verify(response); } @Test public void hasErrorFalse() throws Exception { - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - - replay(response); + given(response.getStatusCode()).willReturn(HttpStatus.OK); assertFalse(handler.hasError(response)); - - verify(response); } @Test @@ -73,12 +63,10 @@ public void handleError() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); - expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND); - expect(response.getStatusText()).andReturn("Not Found"); - expect(response.getHeaders()).andReturn(headers).atLeastOnce(); - expect(response.getBody()).andReturn(new ByteArrayInputStream("Hello World".getBytes("UTF-8"))); - - replay(response); + given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND); + given(response.getStatusText()).willReturn("Not Found"); + given(response.getHeaders()).willReturn(headers); + given(response.getBody()).willReturn(new ByteArrayInputStream("Hello World".getBytes("UTF-8"))); try { handler.handleError(response); @@ -87,8 +75,6 @@ public void handleError() throws Exception { catch (HttpClientErrorException e) { assertSame(headers, e.getResponseHeaders()); } - - verify(response); } @Test(expected = HttpClientErrorException.class) @@ -96,16 +82,12 @@ public void handleErrorIOException() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); - expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND); - expect(response.getStatusText()).andReturn("Not Found"); - expect(response.getHeaders()).andReturn(headers).atLeastOnce(); - expect(response.getBody()).andThrow(new IOException()); - - replay(response); + given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND); + given(response.getStatusText()).willReturn("Not Found"); + given(response.getHeaders()).willReturn(headers); + given(response.getBody()).willThrow(new IOException()); handler.handleError(response); - - verify(response); } @Test(expected = HttpClientErrorException.class) @@ -113,16 +95,11 @@ public void handleErrorNullResponse() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); - expect(response.getStatusCode()).andReturn(HttpStatus.NOT_FOUND); - expect(response.getStatusText()).andReturn("Not Found"); - expect(response.getHeaders()).andReturn(headers).atLeastOnce(); - expect(response.getBody()).andReturn(null); - - replay(response); + given(response.getStatusCode()).willReturn(HttpStatus.NOT_FOUND); + given(response.getStatusText()).willReturn("Not Found"); + given(response.getHeaders()).willReturn(headers); handler.handleError(response); - - verify(response); } // SPR-9406 @@ -132,13 +109,10 @@ public void unknownStatusCode() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_PLAIN); - expect(response.getStatusCode()).andThrow(new IllegalArgumentException("No matching constant for 999")); - expect(response.getRawStatusCode()).andReturn(999); - expect(response.getStatusText()).andReturn("Custom status code"); - expect(response.getHeaders()).andReturn(headers).atLeastOnce(); - expect(response.getBody()).andReturn(null); - - replay(response); + given(response.getStatusCode()).willThrow(new IllegalArgumentException("No matching constant for 999")); + given(response.getRawStatusCode()).willReturn(999); + given(response.getStatusText()).willReturn("Custom status code"); + given(response.getHeaders()).willReturn(headers); handler.handleError(response); } diff --git a/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java b/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java index f9c587248ec5..1ce003da4b3b 100644 --- a/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/HttpMessageConverterExtractorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,6 @@ package org.springframework.web.client; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; @@ -39,6 +31,9 @@ import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Test fixture for {@link HttpMessageConverter}. * @@ -52,101 +47,80 @@ public class HttpMessageConverterExtractorTests { @Before public void createMocks() { - response = createMock(ClientHttpResponse.class); + response = mock(ClientHttpResponse.class); } @Test public void noContent() throws IOException { - HttpMessageConverter converter = createMock(HttpMessageConverter.class); - + HttpMessageConverter converter = mock(HttpMessageConverter.class); extractor = new HttpMessageConverterExtractor(String.class, createConverterList(converter)); + given(response.getStatusCode()).willReturn(HttpStatus.NO_CONTENT); - expect(response.getStatusCode()).andReturn(HttpStatus.NO_CONTENT); - - replay(response, converter); Object result = extractor.extractData(response); assertNull(result); - verify(response, converter); } @Test public void notModified() throws IOException { - HttpMessageConverter converter = createMock(HttpMessageConverter.class); - + HttpMessageConverter converter = mock(HttpMessageConverter.class); extractor = new HttpMessageConverterExtractor(String.class, createConverterList(converter)); + given(response.getStatusCode()).willReturn(HttpStatus.NOT_MODIFIED); - expect(response.getStatusCode()).andReturn(HttpStatus.NOT_MODIFIED); - - replay(response, converter); Object result = extractor.extractData(response); assertNull(result); - verify(response, converter); } @Test public void zeroContentLength() throws IOException { - HttpMessageConverter converter = createMock(HttpMessageConverter.class); + HttpMessageConverter converter = mock(HttpMessageConverter.class); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentLength(0); - extractor = new HttpMessageConverterExtractor(String.class, createConverterList(converter)); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders); - - replay(response, converter); Object result = extractor.extractData(response); assertNull(result); - verify(response, converter); } @Test @SuppressWarnings("unchecked") public void normal() throws IOException { - HttpMessageConverter converter = createMock(HttpMessageConverter.class); + HttpMessageConverter converter = mock(HttpMessageConverter.class); List> converters = new ArrayList>(); converters.add(converter); - HttpHeaders responseHeaders = new HttpHeaders(); MediaType contentType = MediaType.TEXT_PLAIN; responseHeaders.setContentType(contentType); String expected = "Foo"; - extractor = new HttpMessageConverterExtractor(String.class, converters); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(String.class, contentType)).willReturn(true); + given(converter.read(String.class, response)).willReturn(expected); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(2); - expect(converter.canRead(String.class, contentType)).andReturn(true); - expect(converter.read(String.class, response)).andReturn(expected); - - replay(response, converter); Object result = extractor.extractData(response); assertEquals(expected, result); - verify(response, converter); } @Test @SuppressWarnings("unchecked") public void cannotRead() throws IOException { - HttpMessageConverter converter = createMock(HttpMessageConverter.class); + HttpMessageConverter converter = mock(HttpMessageConverter.class); List> converters = new ArrayList>(); converters.add(converter); - HttpHeaders responseHeaders = new HttpHeaders(); MediaType contentType = MediaType.TEXT_PLAIN; responseHeaders.setContentType(contentType); - extractor = new HttpMessageConverterExtractor(String.class, converters); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(String.class, contentType)).willReturn(false); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(2); - expect(converter.canRead(String.class, contentType)).andReturn(false); - - replay(response, converter); try { extractor.extractData(response); fail("RestClientException expected"); @@ -154,36 +128,28 @@ public void cannotRead() throws IOException { catch (RestClientException expected) { // expected } - - verify(response, converter); } @Test @SuppressWarnings("unchecked") public void generics() throws IOException { - GenericHttpMessageConverter converter = createMock(GenericHttpMessageConverter.class); + GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class); List> converters = createConverterList(converter); - HttpHeaders responseHeaders = new HttpHeaders(); MediaType contentType = MediaType.TEXT_PLAIN; responseHeaders.setContentType(contentType); String expected = "Foo"; - ParameterizedTypeReference> reference = new ParameterizedTypeReference>() {}; Type type = reference.getType(); - extractor = new HttpMessageConverterExtractor>(type, converters); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(type, null, contentType)).willReturn(true); + given(converter.read(type, null, response)).willReturn(expected); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(2); - expect(converter.canRead(type, null, contentType)).andReturn(true); - expect(converter.read(type, null, response)).andReturn(expected); - - replay(response, converter); Object result = extractor.extractData(response); assertEquals(expected, result); - verify(response, converter); } private List> createConverterList(HttpMessageConverter converter) { diff --git a/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java b/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java index faca295254db..fcfc34077045 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,11 +25,8 @@ import java.util.Map; import java.util.Set; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; - import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -43,7 +40,12 @@ import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; -/** @author Arjen Poutsma */ +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + +/** + * @author Arjen Poutsma + */ @SuppressWarnings("unchecked") public class RestTemplateTests { @@ -61,11 +63,11 @@ public class RestTemplateTests { @Before public void setUp() { - requestFactory = createMock(ClientHttpRequestFactory.class); - request = createMock(ClientHttpRequest.class); - response = createMock(ClientHttpResponse.class); - errorHandler = createMock(ResponseErrorHandler.class); - converter = createMock(HttpMessageConverter.class); + requestFactory = mock(ClientHttpRequestFactory.class); + request = mock(ClientHttpRequest.class); + response = mock(ClientHttpResponse.class); + errorHandler = mock(ResponseErrorHandler.class); + converter = mock(HttpMessageConverter.class); template = new RestTemplate(requestFactory); template.setErrorHandler(errorHandler); template.setMessageConverters(Collections.>singletonList(converter)); @@ -73,85 +75,77 @@ public void setUp() { @Test public void varArgsTemplateVariables() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/21"), HttpMethod.GET)) - .andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/21"), HttpMethod.GET)) + .willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); template.execute("http://example.com/hotels/{hotel}/bookings/{booking}", HttpMethod.GET, null, null, "42", "21"); - verifyMocks(); + verify(response).close(); } @Test public void varArgsNullTemplateVariable() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET)) - .andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET)) + .willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, null, "foo"); - verifyMocks(); + verify(response).close(); } @Test public void mapTemplateVariables() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/42"), HttpMethod.GET)) - .andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(requestFactory.createRequest(new URI("http://example.com/hotels/42/bookings/42"), HttpMethod.GET)) + .willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); Map vars = Collections.singletonMap("hotel", "42"); template.execute("http://example.com/hotels/{hotel}/bookings/{hotel}", HttpMethod.GET, null, null, vars); - verifyMocks(); + verify(response).close(); } @Test public void mapNullTemplateVariable() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET)) - .andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(requestFactory.createRequest(new URI("http://example.com/-foo"), HttpMethod.GET)) + .willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); Map vars = new HashMap(2); vars.put("first", null); vars.put("last", "foo"); template.execute("http://example.com/{first}-{last}", HttpMethod.GET, null, null, vars); - verifyMocks(); + verify(response).close(); } @Test public void errorHandling() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(true); - expect(response.getStatusCode()).andReturn(HttpStatus.INTERNAL_SERVER_ERROR); - expect(response.getStatusText()).andReturn("Internal Server Error"); - errorHandler.handleError(response); - expectLastCall().andThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)); - response.close(); - - replayMocks(); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(true); + given(response.getStatusCode()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR); + given(response.getStatusText()).willReturn("Internal Server Error"); + willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR)).given(errorHandler).handleError(response); try { template.execute("http://example.com", HttpMethod.GET, null, null); @@ -160,60 +154,59 @@ public void errorHandling() throws Exception { catch (HttpServerErrorException ex) { // expected } - verifyMocks(); + + verify(response).close(); } @Test public void getForObject() throws Exception { - expect(converter.canRead(String.class, null)).andReturn(true); + given(converter.canRead(String.class, null)).willReturn(true); MediaType textPlain = new MediaType("text", "plain"); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).andReturn(request); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.getHeaders()).willReturn(requestHeaders); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(textPlain); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(2); - expect(converter.canRead(String.class, textPlain)).andReturn(true); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(String.class, textPlain)).willReturn(true); String expected = "Hello World"; - expect(converter.read(String.class, response)).andReturn(expected); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(converter.read(String.class, response)).willReturn(expected); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); String result = template.getForObject("http://example.com", String.class); assertEquals("Invalid GET result", expected, result); assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept")); - verifyMocks(); + verify(response).close(); } @Test public void getUnsupportedMediaType() throws Exception { - expect(converter.canRead(String.class, null)).andReturn(true); + given(converter.canRead(String.class, null)).willReturn(true); MediaType supportedMediaType = new MediaType("foo", "bar"); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(supportedMediaType)); - expect(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).andReturn(request); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(supportedMediaType)); + given(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).willReturn(request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.getHeaders()).willReturn(requestHeaders); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); MediaType contentType = new MediaType("bar", "baz"); responseHeaders.setContentType(contentType); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(2); - expect(converter.canRead(String.class, contentType)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(String.class, contentType)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); try { template.getForObject("http://example.com/{p}", String.class, "resource"); @@ -222,33 +215,33 @@ public void getUnsupportedMediaType() throws Exception { catch (RestClientException ex) { // expected } - verifyMocks(); + + verify(response).close(); } @Test public void getForEntity() throws Exception { - expect(converter.canRead(String.class, null)).andReturn(true); + given(converter.canRead(String.class, null)).willReturn(true); MediaType textPlain = new MediaType("text", "plain"); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).andReturn(request); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.GET)).willReturn(request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.getHeaders()).willReturn(requestHeaders); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(textPlain); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(3); - expect(converter.canRead(String.class, textPlain)).andReturn(true); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(String.class, textPlain)).willReturn(true); String expected = "Hello World"; - expect(converter.read(String.class, response)).andReturn(expected); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(converter.read(String.class, response)).willReturn(expected); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); ResponseEntity result = template.getForEntity("http://example.com", String.class); assertEquals("Invalid GET result", expected, result.getBody()); @@ -256,70 +249,68 @@ public void getForEntity() throws Exception { assertEquals("Invalid Content-Type header", textPlain, result.getHeaders().getContentType()); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); - verifyMocks(); + verify(response).close(); } @Test public void headForHeaders() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.HEAD)).andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.HEAD)).willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); - expect(response.getHeaders()).andReturn(responseHeaders); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); + given(response.getHeaders()).willReturn(responseHeaders); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); - replayMocks(); HttpHeaders result = template.headForHeaders("http://example.com"); assertSame("Invalid headers returned", responseHeaders, result); - verifyMocks(); + verify(response).close(); } @Test public void postForLocation() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request); String helloWorld = "Hello World"; - expect(converter.canWrite(String.class, null)).andReturn(true); + given(converter.canWrite(String.class, null)).willReturn(true); converter.write(helloWorld, null, request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); URI expected = new URI("http://example.com/hotels"); responseHeaders.setLocation(expected); - expect(response.getHeaders()).andReturn(responseHeaders); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getHeaders()).willReturn(responseHeaders); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); URI result = template.postForLocation("http://example.com", helloWorld); assertEquals("Invalid POST result", expected, result); - verifyMocks(); + verify(response).close(); } @Test public void postForLocationEntityContentType() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request); String helloWorld = "Hello World"; MediaType contentType = MediaType.TEXT_PLAIN; - expect(converter.canWrite(String.class, contentType)).andReturn(true); + given(converter.canWrite(String.class, contentType)).willReturn(true); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders); + given(request.getHeaders()).willReturn(requestHeaders); converter.write(helloWorld, contentType, request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); URI expected = new URI("http://example.com/hotels"); responseHeaders.setLocation(expected); - expect(response.getHeaders()).andReturn(responseHeaders); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getHeaders()).willReturn(responseHeaders); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.setContentType(contentType); @@ -328,27 +319,26 @@ public void postForLocationEntityContentType() throws Exception { URI result = template.postForLocation("http://example.com", entity); assertEquals("Invalid POST result", expected, result); - verifyMocks(); + verify(response).close(); } @Test public void postForLocationEntityCustomHeader() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request); String helloWorld = "Hello World"; - expect(converter.canWrite(String.class, null)).andReturn(true); + given(converter.canWrite(String.class, null)).willReturn(true); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders); + given(request.getHeaders()).willReturn(requestHeaders); converter.write(helloWorld, null, request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); URI expected = new URI("http://example.com/hotels"); responseHeaders.setLocation(expected); - expect(response.getHeaders()).andReturn(responseHeaders); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getHeaders()).willReturn(responseHeaders); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.set("MyHeader", "MyValue"); @@ -358,108 +348,105 @@ public void postForLocationEntityCustomHeader() throws Exception { assertEquals("Invalid POST result", expected, result); assertEquals("No custom header set", "MyValue", requestHeaders.getFirst("MyHeader")); - verifyMocks(); + verify(response).close(); } @Test public void postForLocationNoLocation() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request); String helloWorld = "Hello World"; - expect(converter.canWrite(String.class, null)).andReturn(true); + given(converter.canWrite(String.class, null)).willReturn(true); converter.write(helloWorld, null, request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); - expect(response.getHeaders()).andReturn(responseHeaders); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getHeaders()).willReturn(responseHeaders); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); URI result = template.postForLocation("http://example.com", helloWorld); assertNull("Invalid POST result", result); - verifyMocks(); + verify(response).close(); } @Test public void postForLocationNull() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.getHeaders()).willReturn(requestHeaders); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); - expect(response.getHeaders()).andReturn(responseHeaders); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); + given(response.getHeaders()).willReturn(responseHeaders); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); - replayMocks(); template.postForLocation("http://example.com", null); assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); - verifyMocks(); + verify(response).close(); } @Test public void postForObject() throws Exception { MediaType textPlain = new MediaType("text", "plain"); - expect(converter.canRead(Integer.class, null)).andReturn(true); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request); + given(converter.canRead(Integer.class, null)).willReturn(true); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(this.request.getHeaders()).andReturn(requestHeaders); + given(this.request.getHeaders()).willReturn(requestHeaders); String request = "Hello World"; - expect(converter.canWrite(String.class, null)).andReturn(true); + given(converter.canWrite(String.class, null)).willReturn(true); converter.write(request, null, this.request); - expect(this.request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(this.request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(textPlain); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(2); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); Integer expected = 42; - expect(converter.canRead(Integer.class, textPlain)).andReturn(true); - expect(converter.read(Integer.class, response)).andReturn(expected); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(converter.canRead(Integer.class, textPlain)).willReturn(true); + given(converter.read(Integer.class, response)).willReturn(expected); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); Integer result = template.postForObject("http://example.com", request, Integer.class); assertEquals("Invalid POST result", expected, result); assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept")); - verifyMocks(); + verify(response).close(); } @Test public void postForEntity() throws Exception { MediaType textPlain = new MediaType("text", "plain"); - expect(converter.canRead(Integer.class, null)).andReturn(true); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request); + given(converter.canRead(Integer.class, null)).willReturn(true); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(this.request.getHeaders()).andReturn(requestHeaders); + given(this.request.getHeaders()).willReturn(requestHeaders); String request = "Hello World"; - expect(converter.canWrite(String.class, null)).andReturn(true); + given(converter.canWrite(String.class, null)).willReturn(true); converter.write(request, null, this.request); - expect(this.request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(this.request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(textPlain); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(3); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); Integer expected = 42; - expect(converter.canRead(Integer.class, textPlain)).andReturn(true); - expect(converter.read(Integer.class, response)).andReturn(expected); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(converter.canRead(Integer.class, textPlain)).willReturn(true); + given(converter.read(Integer.class, response)).willReturn(expected); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); ResponseEntity result = template.postForEntity("http://example.com", request, Integer.class); assertEquals("Invalid POST result", expected, result.getBody()); @@ -467,148 +454,143 @@ public void postForEntity() throws Exception { assertEquals("Invalid Accept header", textPlain.toString(), requestHeaders.getFirst("Accept")); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); - verifyMocks(); + verify(response).close(); } @Test public void postForObjectNull() throws Exception { MediaType textPlain = new MediaType("text", "plain"); - expect(converter.canRead(Integer.class, null)).andReturn(true); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request); + given(converter.canRead(Integer.class, null)).willReturn(true); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders).times(2); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.getHeaders()).willReturn(requestHeaders); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(textPlain); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(2); - expect(converter.canRead(Integer.class, textPlain)).andReturn(true); - expect(converter.read(Integer.class, response)).andReturn(null); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(Integer.class, textPlain)).willReturn(true); + given(converter.read(Integer.class, response)).willReturn(null); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); + Integer result = template.postForObject("http://example.com", null, Integer.class); assertNull("Invalid POST result", result); assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); - verifyMocks(); + verify(response).close(); } @Test public void postForEntityNull() throws Exception { MediaType textPlain = new MediaType("text", "plain"); - expect(converter.canRead(Integer.class, null)).andReturn(true); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(textPlain)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(request); + given(converter.canRead(Integer.class, null)).willReturn(true); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(textPlain)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders).times(2); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(request.getHeaders()).willReturn(requestHeaders); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(textPlain); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(3); - expect(converter.canRead(Integer.class, textPlain)).andReturn(true); - expect(converter.read(Integer.class, response)).andReturn(null); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); + given(converter.canRead(Integer.class, textPlain)).willReturn(true); + given(converter.read(Integer.class, response)).willReturn(null); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); + ResponseEntity result = template.postForEntity("http://example.com", null, Integer.class); assertFalse("Invalid POST result", result.hasBody()); assertEquals("Invalid Content-Type", textPlain, result.getHeaders().getContentType()); assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); - verifyMocks(); + verify(response).close(); } @Test public void put() throws Exception { - expect(converter.canWrite(String.class, null)).andReturn(true); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).andReturn(request); + given(converter.canWrite(String.class, null)).willReturn(true); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).willReturn(request); String helloWorld = "Hello World"; converter.write(helloWorld, null, request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); template.put("http://example.com", helloWorld); - verifyMocks(); + verify(response).close(); } @Test public void putNull() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).andReturn(request); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.PUT)).willReturn(request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(request.getHeaders()).andReturn(requestHeaders); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); + given(request.getHeaders()).willReturn(requestHeaders); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); - replayMocks(); template.put("http://example.com", null); assertEquals("Invalid content length", 0, requestHeaders.getContentLength()); - verifyMocks(); + verify(response).close(); } @Test public void delete() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.DELETE)).andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.DELETE)).willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); template.delete("http://example.com"); - verifyMocks(); + verify(response).close(); } @Test public void optionsForAllow() throws Exception { - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.OPTIONS)).andReturn(request); - expect(request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.OPTIONS)).willReturn(request); + given(request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); EnumSet expected = EnumSet.of(HttpMethod.GET, HttpMethod.POST); responseHeaders.setAllow(expected); - expect(response.getHeaders()).andReturn(responseHeaders); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(response.getHeaders()).willReturn(responseHeaders); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); Set result = template.optionsForAllow("http://example.com"); assertEquals("Invalid OPTIONS result", expected, result); - verifyMocks(); + verify(response).close(); } @Test public void ioException() throws Exception { - expect(converter.canRead(String.class, null)).andReturn(true); + given(converter.canRead(String.class, null)).willReturn(true); MediaType mediaType = new MediaType("foo", "bar"); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(mediaType)); - expect(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).andReturn(request); - expect(request.getHeaders()).andReturn(new HttpHeaders()); - expect(request.execute()).andThrow(new IOException()); - - replayMocks(); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(mediaType)); + given(requestFactory.createRequest(new URI("http://example.com/resource"), HttpMethod.GET)).willReturn(request); + given(request.getHeaders()).willReturn(new HttpHeaders()); + given(request.execute()).willThrow(new IOException()); try { template.getForObject("http://example.com/resource", String.class); @@ -617,35 +599,32 @@ public void ioException() throws Exception { catch (ResourceAccessException ex) { // expected } - - verifyMocks(); } @Test public void exchange() throws Exception { - expect(converter.canRead(Integer.class, null)).andReturn(true); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request); + given(converter.canRead(Integer.class, null)).willReturn(true); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(this.request.getHeaders()).andReturn(requestHeaders).times(2); - expect(converter.canWrite(String.class, null)).andReturn(true); + given(this.request.getHeaders()).willReturn(requestHeaders); + given(converter.canWrite(String.class, null)).willReturn(true); String body = "Hello World"; converter.write(body, null, this.request); - expect(this.request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(this.request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_PLAIN); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(3); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); Integer expected = 42; - expect(converter.canRead(Integer.class, MediaType.TEXT_PLAIN)).andReturn(true); - expect(converter.read(Integer.class, response)).andReturn(expected); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replayMocks(); + given(converter.canRead(Integer.class, MediaType.TEXT_PLAIN)).willReturn(true); + given(converter.read(Integer.class, response)).willReturn(expected); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.set("MyHeader", "MyValue"); @@ -657,38 +636,37 @@ public void exchange() throws Exception { assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); - verifyMocks(); + verify(response).close(); } @Test public void exchangeParameterizedType() throws Exception { - GenericHttpMessageConverter converter = createMock(GenericHttpMessageConverter.class); + GenericHttpMessageConverter converter = mock(GenericHttpMessageConverter.class); template.setMessageConverters(Collections.>singletonList(converter)); ParameterizedTypeReference> intList = new ParameterizedTypeReference>() {}; - expect(converter.canRead(intList.getType(), null, null)).andReturn(true); - expect(converter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).andReturn(this.request); + given(converter.canRead(intList.getType(), null, null)).willReturn(true); + given(converter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.POST)).willReturn(this.request); HttpHeaders requestHeaders = new HttpHeaders(); - expect(this.request.getHeaders()).andReturn(requestHeaders).times(2); - expect(converter.canWrite(String.class, null)).andReturn(true); + given(this.request.getHeaders()).willReturn(requestHeaders); + given(converter.canWrite(String.class, null)).willReturn(true); String requestBody = "Hello World"; converter.write(requestBody, null, this.request); - expect(this.request.execute()).andReturn(response); - expect(errorHandler.hasError(response)).andReturn(false); + given(this.request.execute()).willReturn(response); + given(errorHandler.hasError(response)).willReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_PLAIN); responseHeaders.setContentLength(10); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - expect(response.getHeaders()).andReturn(responseHeaders).times(3); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + given(response.getHeaders()).willReturn(responseHeaders); List expected = Collections.singletonList(42); - expect(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).andReturn(true); - expect(converter.read(intList.getType(), null, response)).andReturn(expected); - expect(response.getStatusCode()).andReturn(HttpStatus.OK); - addLogResponseStatusExpectations(HttpStatus.OK); - response.close(); - - replay(requestFactory, request, response, errorHandler, converter); + given(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).willReturn(true); + given(converter.read(intList.getType(), null, response)).willReturn(expected); + given(response.getStatusCode()).willReturn(HttpStatus.OK); + HttpStatus status = HttpStatus.OK; + given(response.getStatusCode()).willReturn(status); + given(response.getStatusText()).willReturn(status.getReasonPhrase()); HttpHeaders entityHeaders = new HttpHeaders(); entityHeaders.set("MyHeader", "MyValue"); @@ -700,22 +678,6 @@ public void exchangeParameterizedType() throws Exception { assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader")); assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode()); - verify(requestFactory, request, response, errorHandler, converter); + verify(response).close(); } - - - private void addLogResponseStatusExpectations(HttpStatus status) throws IOException { - expect(response.getStatusCode()).andReturn(status).times(0, 1); - expect(response.getStatusText()).andReturn(status.getReasonPhrase()).times(0, 1); - } - - private void replayMocks() { - replay(requestFactory, request, response, errorHandler, converter); - } - - private void verifyMocks() { - verify(requestFactory, request, response, errorHandler, converter); - } - - } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java index dc6ea054101b..2e5688857f82 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,15 +17,16 @@ package org.springframework.web.context.request; import java.io.Serializable; + import javax.servlet.http.HttpServletRequest; -import org.easymock.MockControl; -import static org.junit.Assert.*; import org.junit.Test; - import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpSession; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller @@ -132,17 +133,12 @@ public void setGlobalSessionScopedAttributeAfterCompletion() throws Exception { @Test public void getSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception { - MockControl mockRequest = MockControl.createControl(HttpServletRequest.class); - HttpServletRequest request = (HttpServletRequest) mockRequest.getMock(); - request.getSession(false); - mockRequest.setReturnValue(null, 1); - mockRequest.replay(); + HttpServletRequest request = mock(HttpServletRequest.class); ServletRequestAttributes attrs = new ServletRequestAttributes(request); Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION); assertNull(value); - - mockRequest.verify(); + verify(request).getSession(false); } @Test @@ -159,16 +155,11 @@ public void removeSessionScopedAttribute() throws Exception { @Test public void removeSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception { - MockControl mockRequest = MockControl.createControl(HttpServletRequest.class); - HttpServletRequest request = (HttpServletRequest) mockRequest.getMock(); - request.getSession(false); - mockRequest.setReturnValue(null, 1); - mockRequest.replay(); + HttpServletRequest request = mock(HttpServletRequest.class); ServletRequestAttributes attrs = new ServletRequestAttributes(request); attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION); - - mockRequest.verify(); + verify(request).getSession(false); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java index 2590481d3d3d..dbdf0a5a2be3 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,12 @@ package org.springframework.web.context.request.async; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import org.junit.Test; import org.springframework.web.context.request.async.DeferredResult.DeferredResultHandler; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * DeferredResult tests. * @@ -35,23 +31,18 @@ public class DeferredResultTests { @Test public void setResult() { - DeferredResultHandler handler = createMock(DeferredResultHandler.class); - handler.handleResult("hello"); - replay(handler); + DeferredResultHandler handler = mock(DeferredResultHandler.class); DeferredResult result = new DeferredResult(); result.setResultHandler(handler); assertTrue(result.setResult("hello")); - - verify(handler); + verify(handler).handleResult("hello"); } @Test public void setResultTwice() { - DeferredResultHandler handler = createMock(DeferredResultHandler.class); - handler.handleResult("hello"); - replay(handler); + DeferredResultHandler handler = mock(DeferredResultHandler.class); DeferredResult result = new DeferredResult(); result.setResultHandler(handler); @@ -59,14 +50,12 @@ public void setResultTwice() { assertTrue(result.setResult("hello")); assertFalse(result.setResult("hi")); - verify(handler); + verify(handler).handleResult("hello"); } @Test public void isSetOrExpired() { - DeferredResultHandler handler = createMock(DeferredResultHandler.class); - handler.handleResult("hello"); - replay(handler); + DeferredResultHandler handler = mock(DeferredResultHandler.class); DeferredResult result = new DeferredResult(); result.setResultHandler(handler); @@ -77,7 +66,7 @@ public void isSetOrExpired() { assertTrue(result.isSetOrExpired()); - verify(handler); + verify(handler).handleResult("hello"); } @Test @@ -102,9 +91,7 @@ public void run() { public void onTimeout() throws Exception { final StringBuilder sb = new StringBuilder(); - DeferredResultHandler handler = createMock(DeferredResultHandler.class); - handler.handleResult("timeout result"); - replay(handler); + DeferredResultHandler handler = mock(DeferredResultHandler.class); DeferredResult result = new DeferredResult(null, "timeout result"); result.setResultHandler(handler); @@ -119,7 +106,7 @@ public void run() { assertEquals("timeout event", sb.toString()); assertFalse("Should not be able to set result a second time", result.setResult("hello")); - verify(handler); + verify(handler).handleResult("timeout result"); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java index cbd7dfeee2ec..d378bd8edca3 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,26 +17,18 @@ package org.springframework.web.context.request.async; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -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.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import javax.servlet.AsyncEvent; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.test.MockAsyncContext; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * A test fixture with a {@link StandardServletAsyncWebRequest}. * @@ -124,14 +116,12 @@ public void onTimeoutDefaultBehavior() throws Exception { @Test public void onTimeoutTimeoutHandler() throws Exception { - Runnable timeoutHandler = EasyMock.createMock(Runnable.class); - timeoutHandler.run(); - replay(timeoutHandler); + Runnable timeoutHandler = mock(Runnable.class); this.asyncRequest.addTimeoutHandler(timeoutHandler); this.asyncRequest.onTimeout(new AsyncEvent(null)); - verify(timeoutHandler); + verify(timeoutHandler).run(); } @Test(expected=IllegalStateException.class) diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java index 506201f5ba58..f9ec9666ecdf 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,30 +16,19 @@ package org.springframework.web.context.request.async; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.createStrictMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.notNull; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.util.concurrent.Callable; import javax.servlet.http.HttpServletRequest; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mock.web.test.MockHttpServletRequest; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Test fixture with an {@link WebAsyncManager} with a mock AsyncWebRequest. * @@ -59,14 +48,9 @@ public void setUp() { this.servletRequest = new MockHttpServletRequest(); this.asyncManager = WebAsyncUtils.getAsyncManager(servletRequest); this.asyncManager.setTaskExecutor(new SyncTaskExecutor()); - - this.asyncWebRequest = createStrictMock(AsyncWebRequest.class); - this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); - replay(this.asyncWebRequest); - + this.asyncWebRequest = mock(AsyncWebRequest.class); this.asyncManager.setAsyncWebRequest(this.asyncWebRequest); - - verify(this.asyncWebRequest); + verify(this.asyncWebRequest).addCompletionHandler((Runnable) notNull()); reset(this.asyncWebRequest); } @@ -93,21 +77,14 @@ public void startAsyncProcessingWithoutAsyncWebRequest() throws Exception { @Test public void isConcurrentHandlingStarted() { - - expect(this.asyncWebRequest.isAsyncStarted()).andReturn(false); - replay(this.asyncWebRequest); + given(this.asyncWebRequest.isAsyncStarted()).willReturn(false); assertFalse(this.asyncManager.isConcurrentHandlingStarted()); - verify(this.asyncWebRequest); reset(this.asyncWebRequest); - - expect(this.asyncWebRequest.isAsyncStarted()).andReturn(true); - replay(this.asyncWebRequest); + given(this.asyncWebRequest.isAsyncStarted()).willReturn(true); assertTrue(this.asyncManager.isConcurrentHandlingStarted()); - - verify(this.asyncWebRequest); } @Test(expected=IllegalArgumentException.class) @@ -122,11 +99,7 @@ public void startCallableProcessing() throws Exception { int concurrentResult = 21; Callable task = new StubCallable(concurrentResult); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); - interceptor.preProcess(this.asyncWebRequest, task); - interceptor.postProcess(this.asyncWebRequest, task, new Integer(concurrentResult)); - replay(interceptor); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); setupDefaultAsyncScenario(); @@ -136,7 +109,10 @@ public void startCallableProcessing() throws Exception { assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(concurrentResult, this.asyncManager.getConcurrentResult()); - verify(interceptor, this.asyncWebRequest); + verifyDefaultAsyncScenario(); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); + verify(interceptor).preProcess(this.asyncWebRequest, task); + verify(interceptor).postProcess(this.asyncWebRequest, task, new Integer(concurrentResult)); } @Test @@ -145,11 +121,7 @@ public void startCallableProcessingCallableException() throws Exception { Exception concurrentResult = new Exception(); Callable task = new StubCallable(concurrentResult); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); - interceptor.preProcess(this.asyncWebRequest, task); - interceptor.postProcess(this.asyncWebRequest, task, concurrentResult); - replay(interceptor); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); setupDefaultAsyncScenario(); @@ -159,7 +131,10 @@ public void startCallableProcessingCallableException() throws Exception { assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(concurrentResult, this.asyncManager.getConcurrentResult()); - verify(interceptor, this.asyncWebRequest); + verifyDefaultAsyncScenario(); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); + verify(interceptor).preProcess(this.asyncWebRequest, task); + verify(interceptor).postProcess(this.asyncWebRequest, task, concurrentResult); } @Test @@ -167,14 +142,8 @@ public void startCallableProcessingBeforeConcurrentHandlingException() throws Ex Callable task = new StubCallable(21); Exception exception = new Exception(); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); - expectLastCall().andThrow(exception); - replay(interceptor); - - this.asyncWebRequest.addTimeoutHandler((Runnable) notNull()); - this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); - replay(this.asyncWebRequest); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); + willThrow(exception).given(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); this.asyncManager.registerCallableInterceptor("interceptor", interceptor); @@ -187,7 +156,8 @@ public void startCallableProcessingBeforeConcurrentHandlingException() throws Ex assertFalse(this.asyncManager.hasConcurrentResult()); - verify(this.asyncWebRequest, interceptor); + verify(this.asyncWebRequest).addTimeoutHandler((Runnable) notNull()); + verify(this.asyncWebRequest).addCompletionHandler((Runnable) notNull()); } @Test @@ -196,11 +166,8 @@ public void startCallableProcessingPreProcessException() throws Exception { Callable task = new StubCallable(21); Exception exception = new Exception(); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); - interceptor.preProcess(this.asyncWebRequest, task); - expectLastCall().andThrow(exception); - replay(interceptor); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); + willThrow(exception).given(interceptor).preProcess(this.asyncWebRequest, task); setupDefaultAsyncScenario(); @@ -210,7 +177,8 @@ public void startCallableProcessingPreProcessException() throws Exception { assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(exception, this.asyncManager.getConcurrentResult()); - verify(interceptor, this.asyncWebRequest); + verifyDefaultAsyncScenario(); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); } @Test @@ -219,12 +187,8 @@ public void startCallableProcessingPostProcessException() throws Exception { Callable task = new StubCallable(21); Exception exception = new Exception(); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, task); - interceptor.preProcess(this.asyncWebRequest, task); - interceptor.postProcess(this.asyncWebRequest, task, 21); - expectLastCall().andThrow(exception); - replay(interceptor); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); + willThrow(exception).given(interceptor).postProcess(this.asyncWebRequest, task, 21); setupDefaultAsyncScenario(); @@ -234,7 +198,9 @@ public void startCallableProcessingPostProcessException() throws Exception { assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(exception, this.asyncManager.getConcurrentResult()); - verify(interceptor, this.asyncWebRequest); + verifyDefaultAsyncScenario(); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, task); + verify(interceptor).preProcess(this.asyncWebRequest, task); } @Test @@ -243,18 +209,9 @@ public void startCallableProcessingPostProcessContinueAfterException() throws Ex Callable task = new StubCallable(21); Exception exception = new Exception(); - CallableProcessingInterceptor interceptor1 = createMock(CallableProcessingInterceptor.class); - interceptor1.beforeConcurrentHandling(this.asyncWebRequest, task); - interceptor1.preProcess(this.asyncWebRequest, task); - interceptor1.postProcess(this.asyncWebRequest, task, 21); - replay(interceptor1); - - CallableProcessingInterceptor interceptor2 = createMock(CallableProcessingInterceptor.class); - interceptor2.beforeConcurrentHandling(this.asyncWebRequest, task); - interceptor2.preProcess(this.asyncWebRequest, task); - interceptor2.postProcess(this.asyncWebRequest, task, 21); - expectLastCall().andThrow(exception); - replay(interceptor2); + CallableProcessingInterceptor interceptor1 = mock(CallableProcessingInterceptor.class); + CallableProcessingInterceptor interceptor2 = mock(CallableProcessingInterceptor.class); + willThrow(exception).given(interceptor2).postProcess(this.asyncWebRequest, task, 21); setupDefaultAsyncScenario(); @@ -264,30 +221,29 @@ public void startCallableProcessingPostProcessContinueAfterException() throws Ex assertTrue(this.asyncManager.hasConcurrentResult()); assertEquals(exception, this.asyncManager.getConcurrentResult()); - verify(interceptor1); - verify(interceptor2); - verify(this.asyncWebRequest); + verifyDefaultAsyncScenario(); + verify(interceptor1).beforeConcurrentHandling(this.asyncWebRequest, task); + verify(interceptor1).preProcess(this.asyncWebRequest, task); + verify(interceptor1).postProcess(this.asyncWebRequest, task, 21); + verify(interceptor2).beforeConcurrentHandling(this.asyncWebRequest, task); + verify(interceptor2).preProcess(this.asyncWebRequest, task); } @Test public void startCallableProcessingWithAsyncTask() throws Exception { - AsyncTaskExecutor executor = createMock(AsyncTaskExecutor.class); - expect(executor.submit((Runnable) notNull())).andReturn(null); - replay(executor); - - this.asyncWebRequest.setTimeout(1000L); - this.asyncWebRequest.addTimeoutHandler(EasyMock.anyObject()); - this.asyncWebRequest.addCompletionHandler(EasyMock.anyObject()); - this.asyncWebRequest.startAsync(); - expect(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).andReturn(this.servletRequest).times(0, 1); - replay(this.asyncWebRequest); + AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class); + given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest); @SuppressWarnings("unchecked") - WebAsyncTask asyncTask = new WebAsyncTask(1000L, executor, createMock(Callable.class)); + WebAsyncTask asyncTask = new WebAsyncTask(1000L, executor, mock(Callable.class)); this.asyncManager.startCallableProcessing(asyncTask); - verify(executor, this.asyncWebRequest); + verify(executor).submit((Runnable) notNull()); + verify(this.asyncWebRequest).setTimeout(1000L); + verify(this.asyncWebRequest).addTimeoutHandler(any(Runnable.class)); + verify(this.asyncWebRequest).addCompletionHandler(any(Runnable.class)); + verify(this.asyncWebRequest).startAsync(); } @Test @@ -307,13 +263,8 @@ public void startDeferredResultProcessing() throws Exception { DeferredResult deferredResult = new DeferredResult(1000L); String concurrentResult = "abc"; - DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); - interceptor.preProcess(this.asyncWebRequest, deferredResult); - interceptor.postProcess(asyncWebRequest, deferredResult, concurrentResult); - replay(interceptor); + DeferredResultProcessingInterceptor interceptor = mock(DeferredResultProcessingInterceptor.class); - this.asyncWebRequest.setTimeout(1000L); setupDefaultAsyncScenario(); this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); @@ -322,7 +273,11 @@ public void startDeferredResultProcessing() throws Exception { deferredResult.setResult(concurrentResult); assertEquals(concurrentResult, this.asyncManager.getConcurrentResult()); - verify(this.asyncWebRequest, interceptor); + verifyDefaultAsyncScenario(); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); + verify(interceptor).preProcess(this.asyncWebRequest, deferredResult); + verify(interceptor).postProcess(asyncWebRequest, deferredResult, concurrentResult); + verify(this.asyncWebRequest).setTimeout(1000L); } @Test @@ -331,14 +286,8 @@ public void startDeferredResultProcessingBeforeConcurrentHandlingException() thr DeferredResult deferredResult = new DeferredResult(); Exception exception = new Exception(); - DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); - expectLastCall().andThrow(exception); - replay(interceptor); - - this.asyncWebRequest.addTimeoutHandler((Runnable) notNull()); - this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); - replay(this.asyncWebRequest); + DeferredResultProcessingInterceptor interceptor = mock(DeferredResultProcessingInterceptor.class); + willThrow(exception).given(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); @@ -352,7 +301,8 @@ public void startDeferredResultProcessingBeforeConcurrentHandlingException() thr assertFalse(this.asyncManager.hasConcurrentResult()); - verify(this.asyncWebRequest, interceptor); + verify(this.asyncWebRequest).addTimeoutHandler((Runnable) notNull()); + verify(this.asyncWebRequest).addCompletionHandler((Runnable) notNull()); } @Test @@ -361,11 +311,8 @@ public void startDeferredResultProcessingPreProcessException() throws Exception DeferredResult deferredResult = new DeferredResult(); Exception exception = new Exception(); - DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); - interceptor.preProcess(this.asyncWebRequest, deferredResult); - expectLastCall().andThrow(exception); - replay(interceptor); + DeferredResultProcessingInterceptor interceptor = mock(DeferredResultProcessingInterceptor.class); + willThrow(exception).given(interceptor).preProcess(this.asyncWebRequest, deferredResult); setupDefaultAsyncScenario(); @@ -375,7 +322,8 @@ public void startDeferredResultProcessingPreProcessException() throws Exception deferredResult.setResult(25); assertEquals(exception, this.asyncManager.getConcurrentResult()); - verify(this.asyncWebRequest, interceptor); + verifyDefaultAsyncScenario(); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); } @Test @@ -384,12 +332,8 @@ public void startDeferredResultProcessingPostProcessException() throws Exception DeferredResult deferredResult = new DeferredResult(); Exception exception = new Exception(); - DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); - interceptor.preProcess(this.asyncWebRequest, deferredResult); - interceptor.postProcess(this.asyncWebRequest, deferredResult, 25); - expectLastCall().andThrow(exception); - replay(interceptor); + DeferredResultProcessingInterceptor interceptor = mock(DeferredResultProcessingInterceptor.class); + willThrow(exception).given(interceptor).postProcess(this.asyncWebRequest, deferredResult, 25);; setupDefaultAsyncScenario(); @@ -399,7 +343,9 @@ public void startDeferredResultProcessingPostProcessException() throws Exception deferredResult.setResult(25); assertEquals(exception, this.asyncManager.getConcurrentResult()); - verify(this.asyncWebRequest, interceptor); + verifyDefaultAsyncScenario(); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); + verify(interceptor).preProcess(this.asyncWebRequest, deferredResult); } @Test @@ -414,15 +360,16 @@ public void startDeferredResultProcessingNullInput() throws Exception { } private void setupDefaultAsyncScenario() { - this.asyncWebRequest.addTimeoutHandler((Runnable) notNull()); - this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); - this.asyncWebRequest.startAsync(); - expect(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).andReturn(this.servletRequest).times(0, 1); - expect(this.asyncWebRequest.isAsyncComplete()).andReturn(false); - this.asyncWebRequest.dispatch(); - replay(this.asyncWebRequest); + given(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).willReturn(this.servletRequest); + given(this.asyncWebRequest.isAsyncComplete()).willReturn(false); } + private void verifyDefaultAsyncScenario() { + verify(this.asyncWebRequest).addTimeoutHandler((Runnable) notNull()); + verify(this.asyncWebRequest).addCompletionHandler((Runnable) notNull()); + verify(this.asyncWebRequest).startAsync(); + verify(this.asyncWebRequest).dispatch(); + } private final class StubCallable implements Callable { diff --git a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java index 936be8d79aa7..adccdb11ebea 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,6 @@ package org.springframework.web.context.request.async; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.createStrictMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.notNull; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.springframework.web.context.request.async.CallableProcessingInterceptor.RESULT_NONE; - import java.util.concurrent.Callable; import javax.servlet.AsyncEvent; @@ -40,6 +29,10 @@ import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.context.request.NativeWebRequest; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.web.context.request.async.CallableProcessingInterceptor.*; + /** * {@link WebAsyncManager} tests where container-triggered timeout/completion * events are simulated. @@ -65,9 +58,7 @@ public void setUp() { this.servletResponse = new MockHttpServletResponse(); this.asyncWebRequest = new StandardServletAsyncWebRequest(servletRequest, servletResponse); - AsyncTaskExecutor executor = createMock(AsyncTaskExecutor.class); - expect(executor.submit((Runnable) notNull())).andReturn(null); - replay(executor); + AsyncTaskExecutor executor = mock(AsyncTaskExecutor.class); this.asyncManager = WebAsyncUtils.getAsyncManager(servletRequest); this.asyncManager.setTaskExecutor(executor); @@ -79,11 +70,8 @@ public void startCallableProcessingTimeoutAndComplete() throws Exception { StubCallable callable = new StubCallable(); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable); - expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andReturn(RESULT_NONE); - interceptor.afterCompletion(this.asyncWebRequest, callable); - replay(interceptor); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); + given(interceptor.handleTimeout(this.asyncWebRequest, callable)).willReturn(RESULT_NONE); this.asyncManager.registerCallableInterceptor("interceptor", interceptor); this.asyncManager.startCallableProcessing(callable); @@ -95,7 +83,8 @@ public void startCallableProcessingTimeoutAndComplete() throws Exception { assertEquals(DispatcherType.REQUEST, this.servletRequest.getDispatcherType()); assertEquals(503, this.servletResponse.getStatus()); - verify(interceptor); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); + verify(interceptor).afterCompletion(this.asyncWebRequest, callable); } @Test @@ -124,10 +113,8 @@ public void startCallableProcessingTimeoutAndResumeThroughInterceptor() throws E StubCallable callable = new StubCallable(); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable); - expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andReturn(22); - replay(interceptor); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); + given(interceptor.handleTimeout(this.asyncWebRequest, callable)).willReturn(22); this.asyncManager.registerCallableInterceptor("timeoutInterceptor", interceptor); this.asyncManager.startCallableProcessing(callable); @@ -138,7 +125,7 @@ public void startCallableProcessingTimeoutAndResumeThroughInterceptor() throws E assertEquals(22, this.asyncManager.getConcurrentResult()); assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); - verify(interceptor); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); } @Test @@ -147,10 +134,8 @@ public void startCallableProcessingAfterTimeoutException() throws Exception { StubCallable callable = new StubCallable(); Exception exception = new Exception(); - CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable); - expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andThrow(exception); - replay(interceptor); + CallableProcessingInterceptor interceptor = mock(CallableProcessingInterceptor.class); + given(interceptor.handleTimeout(this.asyncWebRequest, callable)).willThrow(exception); this.asyncManager.registerCallableInterceptor("timeoutInterceptor", interceptor); this.asyncManager.startCallableProcessing(callable); @@ -161,7 +146,7 @@ public void startCallableProcessingAfterTimeoutException() throws Exception { assertEquals(exception, this.asyncManager.getConcurrentResult()); assertEquals("/test", ((MockAsyncContext) this.servletRequest.getAsyncContext()).getDispatchedPath()); - verify(interceptor); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, callable); } @Test @@ -169,12 +154,8 @@ public void startDeferredResultProcessingTimeoutAndComplete() throws Exception { DeferredResult deferredResult = new DeferredResult(); - DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); - interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult); - interceptor.preProcess(this.asyncWebRequest, deferredResult); - expect(interceptor.handleTimeout(this.asyncWebRequest, deferredResult)).andReturn(true); - interceptor.afterCompletion(this.asyncWebRequest, deferredResult); - replay(interceptor); + DeferredResultProcessingInterceptor interceptor = mock(DeferredResultProcessingInterceptor.class); + given(interceptor.handleTimeout(this.asyncWebRequest, deferredResult)).willReturn(true); this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); this.asyncManager.startDeferredResultProcessing(deferredResult); @@ -186,7 +167,9 @@ public void startDeferredResultProcessingTimeoutAndComplete() throws Exception { assertEquals(DispatcherType.REQUEST, this.servletRequest.getDispatcherType()); assertEquals(503, this.servletResponse.getStatus()); - verify(interceptor); + verify(interceptor).beforeConcurrentHandling(this.asyncWebRequest, deferredResult); + verify(interceptor).preProcess(this.asyncWebRequest, deferredResult); + verify(interceptor).afterCompletion(this.asyncWebRequest, deferredResult); } @Test diff --git a/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java index 141d68cfaee0..6091fa6a80cb 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,6 @@ package org.springframework.web.filter; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.notNull; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.same; -import static org.easymock.EasyMock.verify; - import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -33,9 +25,10 @@ import org.springframework.mock.web.test.MockFilterConfig; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletContext; -import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.util.WebUtils; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller @@ -48,22 +41,13 @@ public class CharacterEncodingFilterTests extends TestCase { public void testForceAlwaysSetsEncoding() throws Exception { - HttpServletRequest request = createMock(HttpServletRequest.class); - addAsyncManagerExpectations(request); + HttpServletRequest request = mock(HttpServletRequest.class); request.setCharacterEncoding(ENCODING); - expect(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).andReturn(null); - expect(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).andReturn(null); - request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); - request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); - replay(request); - - HttpServletResponse response = createMock(HttpServletResponse.class); - response.setCharacterEncoding(ENCODING); - replay(response); + given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); + given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null); - FilterChain filterChain = createMock(FilterChain.class); - filterChain.doFilter(request, response); - replay(filterChain); + HttpServletResponse response = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setForceEncoding(true); @@ -71,27 +55,21 @@ public void testForceAlwaysSetsEncoding() throws Exception { filter.init(new MockFilterConfig(FILTER_NAME)); filter.doFilter(request, response, filterChain); - verify(request); - verify(response); - verify(filterChain); + verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); + verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); + verify(response).setCharacterEncoding(ENCODING); + verify(filterChain).doFilter(request, response); } public void testEncodingIfEmptyAndNotForced() throws Exception { - HttpServletRequest request = createMock(HttpServletRequest.class); - addAsyncManagerExpectations(request); - expect(request.getCharacterEncoding()).andReturn(null); - request.setCharacterEncoding(ENCODING); - expect(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).andReturn(null); - expect(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).andReturn(null); - request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); - request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); - replay(request); + HttpServletRequest request = mock(HttpServletRequest.class); + given(request.getCharacterEncoding()).willReturn(null); + given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); + given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null); MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain filterChain = createMock(FilterChain.class); - filterChain.doFilter(request, response); - replay(filterChain); + FilterChain filterChain = mock(FilterChain.class); CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setForceEncoding(false); @@ -99,51 +77,41 @@ public void testEncodingIfEmptyAndNotForced() throws Exception { filter.init(new MockFilterConfig(FILTER_NAME)); filter.doFilter(request, response, filterChain); - verify(request); - verify(filterChain); + verify(request).setCharacterEncoding(ENCODING); + verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); + verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); + verify(filterChain).doFilter(request, response); } public void testDoesNowtIfEncodingIsNotEmptyAndNotForced() throws Exception { - HttpServletRequest request = createMock(HttpServletRequest.class); - addAsyncManagerExpectations(request); - expect(request.getCharacterEncoding()).andReturn(ENCODING); - expect(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).andReturn(null); - expect(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).andReturn(null); - request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); - request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); - replay(request); + HttpServletRequest request = mock(HttpServletRequest.class); + given(request.getCharacterEncoding()).willReturn(ENCODING); + given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); + given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null); MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain filterChain = createMock(FilterChain.class); - filterChain.doFilter(request, response); - replay(filterChain); + FilterChain filterChain = mock(FilterChain.class); CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding(ENCODING); filter.init(new MockFilterConfig(FILTER_NAME)); filter.doFilter(request, response, filterChain); - verify(request); - verify(filterChain); + verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); + verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); + verify(filterChain).doFilter(request, response); } public void testWithBeanInitialization() throws Exception { - HttpServletRequest request = createMock(HttpServletRequest.class); - addAsyncManagerExpectations(request); - expect(request.getCharacterEncoding()).andReturn(null); - request.setCharacterEncoding(ENCODING); - expect(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).andReturn(null); - expect(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).andReturn(null); - request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); - request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); - replay(request); + HttpServletRequest request = mock(HttpServletRequest.class); + given(request.getCharacterEncoding()).willReturn(null); + given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); + given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null); MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain filterChain = createMock(FilterChain.class); - filterChain.doFilter(request, response); - replay(filterChain); + FilterChain filterChain = mock(FilterChain.class); CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding(ENCODING); @@ -151,40 +119,29 @@ public void testWithBeanInitialization() throws Exception { filter.setServletContext(new MockServletContext()); filter.doFilter(request, response, filterChain); - verify(request); - verify(filterChain); + verify(request).setCharacterEncoding(ENCODING); + verify(request).setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); + verify(request).removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); + verify(filterChain).doFilter(request, response); } public void testWithIncompleteInitialization() throws Exception { - HttpServletRequest request = createMock(HttpServletRequest.class); - addAsyncManagerExpectations(request); - expect(request.getCharacterEncoding()).andReturn(null); - request.setCharacterEncoding(ENCODING); - expect(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).andReturn(null); - expect(request.getAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).andReturn(null); - request.setAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); - request.removeAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); - replay(request); + HttpServletRequest request = mock(HttpServletRequest.class); + given(request.getCharacterEncoding()).willReturn(null); + given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); + given(request.getAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null); MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain filterChain = createMock(FilterChain.class); - filterChain.doFilter(request, response); - replay(filterChain); + FilterChain filterChain = mock(FilterChain.class); CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding(ENCODING); filter.doFilter(request, response, filterChain); - verify(request); - verify(filterChain); - } - - - private void addAsyncManagerExpectations(HttpServletRequest request) { - expect(request.getAttribute(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE)).andReturn(null); - expectLastCall().anyTimes(); - request.setAttribute(same(WebAsyncUtils.WEB_ASYNC_MANAGER_ATTRIBUTE), notNull()); - expectLastCall().anyTimes(); + verify(request).setCharacterEncoding(ENCODING); + verify(request).setAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE); + verify(request).removeAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); + verify(filterChain).doFilter(request, response); } } diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java index 42c13d267129..297f103e8769 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java @@ -22,10 +22,9 @@ import org.junit.Before; import org.junit.Test; - -import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.MethodParameter; import org.springframework.mock.web.test.MockHttpServletRequest; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; @@ -37,13 +36,14 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.method.annotation.ModelAttributeMethodProcessor; import org.springframework.web.method.support.ModelAndViewContainer; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.*; -import static org.easymock.EasyMock.*; import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; /** * Test fixture with {@link ModelAttributeMethodProcessor}. @@ -153,26 +153,23 @@ private void getAttributeFromModel(String expectedAttributeName, MethodParameter mavContainer.addAttribute(expectedAttributeName, target); WebDataBinder dataBinder = new WebRequestDataBinder(target); - WebDataBinderFactory factory = createMock(WebDataBinderFactory.class); - expect(factory.createBinder(webRequest, target, expectedAttributeName)).andReturn(dataBinder); - replay(factory); + WebDataBinderFactory factory = mock(WebDataBinderFactory.class); + given(factory.createBinder(webRequest, target, expectedAttributeName)).willReturn(dataBinder); processor.resolveArgument(param, mavContainer, webRequest, factory); - - verify(factory); + verify(factory).createBinder(webRequest, target, expectedAttributeName); } @Test public void resovleArgumentViaDefaultConstructor() throws Exception { WebDataBinder dataBinder = new WebRequestDataBinder(null); - WebDataBinderFactory factory = createMock(WebDataBinderFactory.class); - expect(factory.createBinder((NativeWebRequest) anyObject(), notNull(), eq("attrName"))).andReturn(dataBinder); - replay(factory); + WebDataBinderFactory factory = mock(WebDataBinderFactory.class); + given(factory.createBinder((NativeWebRequest) anyObject(), notNull(), eq("attrName"))).willReturn(dataBinder); processor.resolveArgument(paramNamedValidModelAttr, mavContainer, webRequest, factory); - verify(factory); + verify(factory).createBinder((NativeWebRequest) anyObject(), notNull(), eq("attrName")); } @Test @@ -182,9 +179,8 @@ public void resovleArgumentValidation() throws Exception { mavContainer.addAttribute(name, target); StubRequestDataBinder dataBinder = new StubRequestDataBinder(target, name); - WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class); - expect(binderFactory.createBinder(webRequest, target, name)).andReturn(dataBinder); - replay(binderFactory); + WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); + given(binderFactory.createBinder(webRequest, target, name)).willReturn(dataBinder); processor.resolveArgument(paramNamedValidModelAttr, mavContainer, webRequest, binderFactory); @@ -201,11 +197,11 @@ public void resovleArgumentBindException() throws Exception { StubRequestDataBinder dataBinder = new StubRequestDataBinder(target, name); dataBinder.getBindingResult().reject("error"); - WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class); - expect(binderFactory.createBinder(webRequest, target, name)).andReturn(dataBinder); - replay(binderFactory); + WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); + given(binderFactory.createBinder(webRequest, target, name)).willReturn(dataBinder); processor.resolveArgument(paramNonSimpleType, mavContainer, webRequest, binderFactory); + verify(binderFactory).createBinder(webRequest, target, name); } // SPR-9378 @@ -221,9 +217,8 @@ public void resolveArgumentOrdering() throws Exception { mavContainer.addAttribute("anotherTestBean", anotherTestBean); StubRequestDataBinder dataBinder = new StubRequestDataBinder(testBean, name); - WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class); - expect(binderFactory.createBinder(webRequest, testBean, name)).andReturn(dataBinder); - replay(binderFactory); + WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); + given(binderFactory.createBinder(webRequest, testBean, name)).willReturn(dataBinder); processor.resolveArgument(paramModelAttr, mavContainer, webRequest, binderFactory); diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java index 34ca840ce93e..bfa4e49d1e2b 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,6 @@ package org.springframework.web.method.annotation; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -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.junit.Assert.fail; - import java.lang.reflect.Method; import java.util.Arrays; @@ -48,6 +38,9 @@ import org.springframework.web.method.support.InvocableHandlerMethod; import org.springframework.web.method.support.ModelAndViewContainer; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Text fixture for {@link ModelFactory} tests. * @@ -153,9 +146,8 @@ public void updateModelBindingResultKeys() throws Exception { mavContainer.addAttribute(attrName, attrValue); WebDataBinder dataBinder = new WebDataBinder(attrValue, attrName); - WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class); - expect(binderFactory.createBinder(webRequest, attrValue, attrName)).andReturn(dataBinder); - replay(binderFactory); + WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); + given(binderFactory.createBinder(webRequest, attrValue, attrName)).willReturn(dataBinder); ModelFactory modelFactory = new ModelFactory(null, binderFactory, sessionAttrsHandler); modelFactory.updateModel(webRequest, mavContainer); @@ -163,8 +155,6 @@ public void updateModelBindingResultKeys() throws Exception { assertEquals(attrValue, mavContainer.getModel().remove(attrName)); assertSame(dataBinder.getBindingResult(), mavContainer.getModel().remove(bindingResultKey(attrName))); assertEquals(0, mavContainer.getModel().size()); - - verify(binderFactory); } @Test @@ -181,17 +171,14 @@ public void updateModelSessionStatusComplete() throws Exception { assertTrue(sessionAttrsHandler.isHandlerSessionAttribute(attrName, null)); WebDataBinder dataBinder = new WebDataBinder(attrValue, attrName); - WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class); - expect(binderFactory.createBinder(webRequest, attrValue, attrName)).andReturn(dataBinder); - replay(binderFactory); + WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); + given(binderFactory.createBinder(webRequest, attrValue, attrName)).willReturn(dataBinder); ModelFactory modelFactory = new ModelFactory(null, binderFactory, sessionAttrsHandler); modelFactory.updateModel(webRequest, mavContainer); assertEquals(attrValue, mavContainer.getModel().get(attrName)); assertNull(sessionAttributeStore.retrieveAttribute(webRequest, attrName)); - - verify(binderFactory); } private String bindingResultKey(String key) { diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java index 3cd926d20c51..4738e030e813 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/WebArgumentResolverAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,6 @@ package org.springframework.web.method.annotation; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -34,6 +26,9 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Test fixture with {@link WebArgumentResolverAdapterTests}. * @@ -52,7 +47,7 @@ public class WebArgumentResolverAdapterTests { @Before public void setUp() throws Exception { - adaptee = createMock(WebArgumentResolver.class); + adaptee = mock(WebArgumentResolver.class); adapter = new TestWebArgumentResolverAdapter(adaptee); parameter = new MethodParameter(getClass().getMethod("handle", Integer.TYPE), 0); webRequest = new ServletWebRequest(new MockHttpServletRequest()); @@ -68,85 +63,68 @@ public void resetRequestContextHolder() { @Test public void supportsParameter() throws Exception { - expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(42); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willReturn(42); assertTrue("Parameter not supported", adapter.supportsParameter(parameter)); - verify(adaptee); + verify(adaptee).resolveArgument(parameter, webRequest); } @Test public void supportsParameterUnresolved() throws Exception { - expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(WebArgumentResolver.UNRESOLVED); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willReturn(WebArgumentResolver.UNRESOLVED); assertFalse("Parameter supported", adapter.supportsParameter(parameter)); - verify(adaptee); + verify(adaptee).resolveArgument(parameter, webRequest); } @Test public void supportsParameterWrongType() throws Exception { - expect(adaptee.resolveArgument(parameter, webRequest)).andReturn("Foo"); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willReturn("Foo"); assertFalse("Parameter supported", adapter.supportsParameter(parameter)); - verify(adaptee); + verify(adaptee).resolveArgument(parameter, webRequest); } @Test public void supportsParameterThrowsException() throws Exception { - expect(adaptee.resolveArgument(parameter, webRequest)).andThrow(new Exception()); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willThrow(new Exception()); assertFalse("Parameter supported", adapter.supportsParameter(parameter)); - verify(adaptee); + verify(adaptee).resolveArgument(parameter, webRequest); } @Test public void resolveArgument() throws Exception { int expected = 42; - expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(expected); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willReturn(expected); Object result = adapter.resolveArgument(parameter, null, webRequest, null); assertEquals("Invalid result", expected, result); - - verify(adaptee); - } @Test(expected = IllegalStateException.class) public void resolveArgumentUnresolved() throws Exception { - expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(WebArgumentResolver.UNRESOLVED); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willReturn(WebArgumentResolver.UNRESOLVED); adapter.resolveArgument(parameter, null, webRequest, null); - - verify(adaptee); } @Test(expected = IllegalStateException.class) public void resolveArgumentWrongType() throws Exception { - expect(adaptee.resolveArgument(parameter, webRequest)).andReturn("Foo"); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willReturn("Foo"); adapter.resolveArgument(parameter, null, webRequest, null); - - verify(adaptee); } @Test(expected = Exception.class) public void resolveArgumentThrowsException() throws Exception { - expect(adaptee.resolveArgument(parameter, webRequest)).andThrow(new Exception()); - replay(adaptee); + given(adaptee.resolveArgument(parameter, webRequest)).willThrow(new Exception()); adapter.resolveArgument(parameter, null, webRequest, null); - - verify(adaptee); } public void handle(int param) { @@ -164,4 +142,4 @@ protected NativeWebRequest getWebRequest() { } } -} \ No newline at end of file +} diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java index 169f2477e01f..df10bd0d09ef 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,11 @@ import java.io.IOException; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.web.multipart.MultipartFile; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans */ @@ -63,30 +64,22 @@ public void testSetValueAsNullGetsBackEmptyString() throws Exception { public void testSetValueAsMultipartFile() throws Exception { String expectedValue = "That is comforting to know"; ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); - MockControl mock = MockControl.createControl(MultipartFile.class); - MultipartFile file = (MultipartFile) mock.getMock(); - file.getBytes(); - mock.setReturnValue(expectedValue.getBytes()); - mock.replay(); + MultipartFile file = mock(MultipartFile.class); + given(file.getBytes()).willReturn(expectedValue.getBytes()); editor.setValue(file); assertEquals(expectedValue, editor.getAsText()); - mock.verify(); } public void testSetValueAsMultipartFileWithBadBytes() throws Exception { ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); - MockControl mock = MockControl.createControl(MultipartFile.class); - MultipartFile file = (MultipartFile) mock.getMock(); - file.getBytes(); - mock.setThrowable(new IOException()); - mock.replay(); + MultipartFile file = mock(MultipartFile.class); + given(file.getBytes()).willThrow(new IOException()); try { editor.setValue(file); fail("Must have thrown an IllegalArgumentException: IOException thrown when reading MultipartFile bytes"); } catch (IllegalArgumentException expected) { } - mock.verify(); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java index e44f91457572..ee739b9831ee 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,6 @@ package org.springframework.web.portlet.context; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; - import java.io.Serializable; import javax.portlet.PortletRequest; @@ -28,6 +25,9 @@ import org.springframework.mock.web.portlet.MockPortletSession; import org.springframework.web.context.request.RequestAttributes; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rick Evans * @author Juergen Hoeller @@ -136,15 +136,13 @@ public void testSetGlobalSessionScopedAttributeAfterCompletion() throws Exceptio @Test public void testGetSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception { - PortletRequest request = createMock(PortletRequest.class); - expect(request.getPortletSession(false)).andReturn(null); - replay(request); + PortletRequest request = mock(PortletRequest.class); PortletRequestAttributes attrs = new PortletRequestAttributes(request); Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION); assertNull(value); - verify(request); + verify(request).getPortletSession(false); } @Test @@ -161,14 +159,12 @@ public void testRemoveSessionScopedAttribute() throws Exception { @Test public void testRemoveSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception { - PortletRequest request = createMock(PortletRequest.class); - expect(request.getPortletSession(false)).andReturn(null); - replay(request); + PortletRequest request = mock(PortletRequest.class); PortletRequestAttributes attrs = new PortletRequestAttributes(request); attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION); - verify(request); + verify(request).getPortletSession(false); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java index 8fd99d5357ff..f7192f7accd0 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java @@ -21,23 +21,23 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; + import javax.portlet.PortletContext; import javax.portlet.PortletRequest; import javax.portlet.PortletSession; import org.junit.Test; - -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.portlet.MockActionRequest; import org.springframework.mock.web.portlet.MockActionResponse; import org.springframework.mock.web.portlet.MockPortletContext; import org.springframework.mock.web.portlet.MockPortletRequest; import org.springframework.mock.web.portlet.MockPortletSession; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.util.WebUtils; -import static org.easymock.EasyMock.*; import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * @author Rick Evans @@ -60,9 +60,8 @@ public void testGetTempDirSunnyDay() throws Exception { public void testGetRealPathInterpretsLocationAsRelativeToWebAppRootIfPathDoesNotBeginWithALeadingSlash() throws Exception { final String originalPath = "web/foo"; final String expectedRealPath = "/" + originalPath; - PortletContext ctx = createMock(PortletContext.class); - expect(ctx.getRealPath(expectedRealPath)).andReturn(expectedRealPath); - replay(ctx); + PortletContext ctx = mock(PortletContext.class); + given(ctx.getRealPath(expectedRealPath)).willReturn(expectedRealPath); String actualRealPath = PortletUtils.getRealPath(ctx, originalPath); assertEquals(expectedRealPath, actualRealPath); @@ -402,13 +401,11 @@ public void testSetSessionAttributeWithNullPortletRequest() throws Exception { @Test public void testGetSessionAttributeDoes_Not_CreateANewSession() throws Exception { - PortletRequest request = createMock(PortletRequest.class); - expect(request.getPortletSession(false)).andReturn(null); - replay(request); + PortletRequest request = mock(PortletRequest.class); Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo"); assertNull("Must return null if session attribute does not exist (or if Session does not exist)", sessionAttribute); - verify(request); + verify(request).getPortletSession(false); } @Test @@ -416,15 +413,12 @@ public void testGetSessionAttributeWithExistingSession() throws Exception { MockPortletSession session = new MockPortletSession(); session.setAttribute("foo", "foo"); - PortletRequest request = createMock(PortletRequest.class); - expect(request.getPortletSession(false)).andReturn(session); - replay(request); + PortletRequest request = mock(PortletRequest.class); + given(request.getPortletSession(false)).willReturn(session); Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo"); assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); assertEquals("foo", sessionAttribute); - - verify(request); } @Test @@ -432,102 +426,72 @@ public void testGetRequiredSessionAttributeWithExistingSession() throws Exceptio MockPortletSession session = new MockPortletSession(); session.setAttribute("foo", "foo"); - PortletRequest request = createMock(PortletRequest.class); - expect(request.getPortletSession(false)).andReturn(session); - replay(request); + PortletRequest request = mock(PortletRequest.class); + given(request.getPortletSession(false)).willReturn(session); Object sessionAttribute = PortletUtils.getRequiredSessionAttribute(request, "foo"); assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); assertEquals("foo", sessionAttribute); - - verify(request); } @Test public void testGetRequiredSessionAttributeWithExistingSessionAndNoAttribute() throws Exception { MockPortletSession session = new MockPortletSession(); - final PortletRequest request = createMock(PortletRequest.class); - expect(request.getPortletSession(false)).andReturn(session); - replay(request); + final PortletRequest request = mock(PortletRequest.class); + given(request.getPortletSession(false)).willReturn(session); try { PortletUtils.getRequiredSessionAttribute(request, "foo"); fail("expected IllegalStateException"); } catch (IllegalStateException ex) { /* expected */ } - verify(request); + } @Test public void testSetSessionAttributeWithExistingSessionAndNullValue() throws Exception { - PortletSession session = createMock(PortletSession.class); - PortletRequest request = createMock(PortletRequest.class); - - expect(request.getPortletSession(false)).andReturn(session); // must not create Session for null value... - session.removeAttribute("foo", PortletSession.APPLICATION_SCOPE); - replay(request, session); - + PortletSession session = mock(PortletSession.class); + PortletRequest request = mock(PortletRequest.class); + given(request.getPortletSession(false)).willReturn(session); // must not create Session for null value... PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE); - - verify(request, session); + verify(session).removeAttribute("foo", PortletSession.APPLICATION_SCOPE); } @Test public void testSetSessionAttributeWithNoExistingSessionAndNullValue() throws Exception { - PortletRequest request = createMock(PortletRequest.class); - - expect(request.getPortletSession(false)).andReturn(null); // must not create Session for null value... - replay(request); - + PortletRequest request = mock(PortletRequest.class); PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE); - - verify(request); + verify(request).getPortletSession(false); // must not create Session for null value... } @Test public void testSetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception { - PortletSession session = createMock(PortletSession.class); - PortletRequest request = createMock(PortletRequest.class); - - expect(request.getPortletSession()).andReturn(session); // must not create Session ... - session.setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE); - replay(request, session); - + PortletSession session = mock(PortletSession.class); + PortletRequest request = mock(PortletRequest.class); + given(request.getPortletSession()).willReturn(session); // must not create Session ... PortletUtils.setSessionAttribute(request, "foo", "foo", PortletSession.APPLICATION_SCOPE); - - verify(request, session); + verify(session).setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE); } @Test public void testGetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception { - PortletSession session = createMock(PortletSession.class); - PortletRequest request = createMock(PortletRequest.class); - - expect(request.getPortletSession(false)).andReturn(session); - expect(session.getAttribute("foo", PortletSession.APPLICATION_SCOPE)).andReturn("foo"); - replay(request, session); - + PortletSession session = mock(PortletSession.class); + PortletRequest request = mock(PortletRequest.class); + given(request.getPortletSession(false)).willReturn(session); + given(session.getAttribute("foo", PortletSession.APPLICATION_SCOPE)).willReturn("foo"); Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo", PortletSession.APPLICATION_SCOPE); assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); assertEquals("foo", sessionAttribute); - - verify(request, session); } @Test public void testGetSessionAttributeWithExistingSessionDefaultsToPortletScope() throws Exception { - PortletSession session = createMock(PortletSession.class); - PortletRequest request = createMock(PortletRequest.class); - - expect(request.getPortletSession(false)).andReturn(session); - expect(session.getAttribute("foo", PortletSession.PORTLET_SCOPE)).andReturn("foo"); - - replay(request, session); - + PortletSession session = mock(PortletSession.class); + PortletRequest request = mock(PortletRequest.class); + given(request.getPortletSession(false)).willReturn(session); + given(session.getAttribute("foo", PortletSession.PORTLET_SCOPE)).willReturn("foo"); Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo"); assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); assertEquals("foo", sessionAttribute); - - verify(request, session); } diff --git a/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewResolverTests.java b/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewResolverTests.java index 896fef861802..a3c14a019312 100644 --- a/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewResolverTests.java +++ b/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,24 +15,18 @@ */ package org.springframework.web.servlet.view.tiles3; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import java.util.Locale; import org.apache.tiles.request.Request; import org.apache.tiles.request.render.Renderer; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.support.StaticWebApplicationContext; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Test fixture for {@link TilesViewResolver}. * @@ -51,7 +45,7 @@ public void setUp() { wac.setServletContext(new MockServletContext()); wac.refresh(); - this.renderer = EasyMock.createMock(Renderer.class); + this.renderer = mock(Renderer.class); this.viewResolver = new TilesViewResolver(); this.viewResolver.setRenderer(this.renderer); @@ -60,13 +54,13 @@ public void setUp() { @Test public void testResolve() throws Exception { - expect(this.renderer.isRenderable(eq("/template.test"), isA(Request.class))).andReturn(true); - expect(this.renderer.isRenderable(eq("/nonexistent.test"), isA(Request.class))).andReturn(false); - replay(this.renderer); + given(this.renderer.isRenderable(eq("/template.test"), isA(Request.class))).willReturn(true); + given(this.renderer.isRenderable(eq("/nonexistent.test"), isA(Request.class))).willReturn(false); assertTrue(this.viewResolver.resolveViewName("/template.test", Locale.ITALY) instanceof TilesView); assertNull(this.viewResolver.resolveViewName("/nonexistent.test", Locale.ITALY)); - verify(this.renderer); + verify(this.renderer).isRenderable(eq("/template.test"), isA(Request.class)); + verify(this.renderer).isRenderable(eq("/nonexistent.test"), isA(Request.class)); } } diff --git a/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewTests.java b/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewTests.java index 91bfef1bc691..4ebf4dab300e 100644 --- a/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewTests.java +++ b/spring-webmvc-tiles3/src/test/java/org/springframework/web/servlet/view/tiles3/TilesViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,18 +15,9 @@ */ package org.springframework.web.servlet.view.tiles3; -import static org.easymock.EasyMock.and; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; - import java.util.HashMap; import java.util.Map; -import org.apache.tiles.request.ApplicationContext; import org.apache.tiles.request.Request; import org.apache.tiles.request.render.Renderer; import org.junit.Before; @@ -37,6 +28,10 @@ import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; +import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.BDDMockito.*; + /** * Test fixture for {@link TilesView}. * @@ -67,7 +62,7 @@ public void setUp() throws Exception { response = new MockHttpServletResponse(); - renderer = createMock(Renderer.class); + renderer = mock(Renderer.class); view = new TilesView(); view.setServletContext(servletContext); @@ -80,16 +75,9 @@ public void setUp() throws Exception { public void testRender() throws Exception { Map model = new HashMap(); model.put("modelAttribute", "modelValue"); - - ApplicationContext tilesContext = createMock(ApplicationContext.class); - - renderer.render(eq(VIEW_PATH), and(isA(Request.class), isA(Request.class))); - replay(tilesContext, renderer); - view.render(model, request, response); - assertEquals("modelValue", request.getAttribute("modelAttribute")); - verify(tilesContext, renderer); + verify(renderer).render(eq(VIEW_PATH), isA(Request.class)); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index 667fb643b4b5..d5ed530e5879 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -61,8 +61,7 @@ import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.BDDMockito.*; /** * @author Rod Johnson diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java index dca233e91475..a4f9572dc152 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/HandlerExecutionChainTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,14 @@ package org.springframework.web.servlet; -import static org.easymock.EasyMock.createStrictMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertSame; - import org.junit.Before; import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * A test fixture with HandlerExecutionChain and mock handler interceptors. * @@ -56,9 +53,9 @@ public void setup() { this.handler = new Object(); this.chain = new HandlerExecutionChain(this.handler); - this.interceptor1 = createStrictMock(AsyncHandlerInterceptor.class); - this.interceptor2 = createStrictMock(AsyncHandlerInterceptor.class); - this.interceptor3 = createStrictMock(AsyncHandlerInterceptor.class); + this.interceptor1 = mock(AsyncHandlerInterceptor.class); + this.interceptor2 = mock(AsyncHandlerInterceptor.class); + this.interceptor3 = mock(AsyncHandlerInterceptor.class); this.chain.addInterceptor(this.interceptor1); this.chain.addInterceptor(this.interceptor2); @@ -69,79 +66,60 @@ public void setup() { public void successScenario() throws Exception { ModelAndView mav = new ModelAndView(); - expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor3.preHandle(this.request, this.response, this.handler)).andReturn(true); - - this.interceptor1.postHandle(this.request, this.response, this.handler, mav); - this.interceptor2.postHandle(this.request, this.response, this.handler, mav); - this.interceptor3.postHandle(this.request, this.response, this.handler, mav); - - this.interceptor3.afterCompletion(this.request, this.response, this.handler, null); - this.interceptor2.afterCompletion(this.request, this.response, this.handler, null); - this.interceptor1.afterCompletion(this.request, this.response, this.handler, null); - - replay(this.interceptor1, this.interceptor2, this.interceptor3); + given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor3.preHandle(this.request, this.response, this.handler)).willReturn(true); this.chain.applyPreHandle(request, response); this.chain.applyPostHandle(request, response, mav); this.chain.triggerAfterCompletion(this.request, this.response, null); - verify(this.interceptor1, this.interceptor2, this.interceptor3); + verify(this.interceptor1).postHandle(this.request, this.response, this.handler, mav); + verify(this.interceptor2).postHandle(this.request, this.response, this.handler, mav); + verify(this.interceptor3).postHandle(this.request, this.response, this.handler, mav); + + verify(this.interceptor3).afterCompletion(this.request, this.response, this.handler, null); + verify(this.interceptor2).afterCompletion(this.request, this.response, this.handler, null); + verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, null); } @Test public void successAsyncScenario() throws Exception { - expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor3.preHandle(this.request, this.response, this.handler)).andReturn(true); - - this.interceptor1.afterConcurrentHandlingStarted(request, response, this.handler); - this.interceptor2.afterConcurrentHandlingStarted(request, response, this.handler); - this.interceptor3.afterConcurrentHandlingStarted(request, response, this.handler); - - replay(this.interceptor1, this.interceptor2, this.interceptor3); + given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor3.preHandle(this.request, this.response, this.handler)).willReturn(true); this.chain.applyPreHandle(request, response); this.chain.applyAfterConcurrentHandlingStarted(request, response); this.chain.triggerAfterCompletion(this.request, this.response, null); - verify(this.interceptor1, this.interceptor2, this.interceptor3); + verify(this.interceptor1).afterConcurrentHandlingStarted(request, response, this.handler); + verify(this.interceptor2).afterConcurrentHandlingStarted(request, response, this.handler); + verify(this.interceptor3).afterConcurrentHandlingStarted(request, response, this.handler); } @Test public void earlyExitInPreHandle() throws Exception { - expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(false); - - this.interceptor1.afterCompletion(this.request, this.response, this.handler, null); - - replay(this.interceptor1, this.interceptor2, this.interceptor3); + given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(false); this.chain.applyPreHandle(request, response); - verify(this.interceptor1, this.interceptor2, this.interceptor3); + verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, null); } @Test public void exceptionBeforePreHandle() throws Exception { - replay(this.interceptor1, this.interceptor2, this.interceptor3); - this.chain.triggerAfterCompletion(this.request, this.response, null); - - verify(this.interceptor1, this.interceptor2, this.interceptor3); + verifyZeroInteractions(this.interceptor1, this.interceptor2, this.interceptor3); } @Test public void exceptionDuringPreHandle() throws Exception { Exception ex = new Exception(""); - expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andThrow(ex); - - this.interceptor1.afterCompletion(this.request, this.response, this.handler, ex); - - replay(this.interceptor1, this.interceptor2, this.interceptor3); + given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willThrow(ex); try { this.chain.applyPreHandle(request, response); @@ -151,27 +129,24 @@ public void exceptionDuringPreHandle() throws Exception { } this.chain.triggerAfterCompletion(this.request, this.response, ex); - verify(this.interceptor1, this.interceptor2, this.interceptor3); + verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, ex); + verify(this.interceptor3, never()).preHandle(this.request, this.response, this.handler); } @Test public void exceptionAfterPreHandle() throws Exception { Exception ex = new Exception(""); - expect(this.interceptor1.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor2.preHandle(this.request, this.response, this.handler)).andReturn(true); - expect(this.interceptor3.preHandle(this.request, this.response, this.handler)).andReturn(true); - - this.interceptor3.afterCompletion(this.request, this.response, this.handler, ex); - this.interceptor2.afterCompletion(this.request, this.response, this.handler, ex); - this.interceptor1.afterCompletion(this.request, this.response, this.handler, ex); - - replay(this.interceptor1, this.interceptor2, this.interceptor3); + given(this.interceptor1.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor2.preHandle(this.request, this.response, this.handler)).willReturn(true); + given(this.interceptor3.preHandle(this.request, this.response, this.handler)).willReturn(true); this.chain.applyPreHandle(request, response); this.chain.triggerAfterCompletion(this.request, this.response, ex); - verify(this.interceptor1, this.interceptor2, this.interceptor3); + verify(this.interceptor3).afterCompletion(this.request, this.response, this.handler, ex); + verify(this.interceptor2).afterCompletion(this.request, this.response, this.handler, ex); + verify(this.interceptor1).afterCompletion(this.request, this.response, this.handler, ex); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java index 7153c901f93f..392cb9b9799d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,23 +16,17 @@ package org.springframework.web.servlet.config.annotation; -import static org.easymock.EasyMock.capture; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -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 java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.easymock.Capture; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.convert.ConversionService; import org.springframework.format.support.FormattingConversionService; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; @@ -48,6 +42,9 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * A test fixture for {@link DelegatingWebMvcConfiguration} tests. * @@ -57,46 +54,59 @@ public class DelegatingWebMvcConfigurationTests { private DelegatingWebMvcConfiguration delegatingConfig; + @Mock private WebMvcConfigurer webMvcConfigurer; + @Captor + private ArgumentCaptor>> converters; + + @Captor + private ArgumentCaptor contentNegotiationConfigurer; + + @Captor + private ArgumentCaptor conversionService; + + @Captor + private ArgumentCaptor> resolvers; + + @Captor + private ArgumentCaptor> handlers; + + @Captor + private ArgumentCaptor asyncConfigurer; + + @Captor + private ArgumentCaptor> exceptionResolvers; + + @Before public void setUp() { - webMvcConfigurer = EasyMock.createMock(WebMvcConfigurer.class); + MockitoAnnotations.initMocks(this); delegatingConfig = new DelegatingWebMvcConfiguration(); } @Test public void requestMappingHandlerAdapter() throws Exception { - Capture>> converters = new Capture>>(); - Capture contentNegotiationConfigurer = new Capture(); - Capture conversionService = new Capture(); - Capture> resolvers = new Capture>(); - Capture> handlers = new Capture>(); - Capture asyncConfigurer = new Capture(); - - webMvcConfigurer.configureMessageConverters(capture(converters)); - webMvcConfigurer.configureContentNegotiation(capture(contentNegotiationConfigurer)); - expect(webMvcConfigurer.getValidator()).andReturn(null); - expect(webMvcConfigurer.getMessageCodesResolver()).andReturn(null); - webMvcConfigurer.addFormatters(capture(conversionService)); - webMvcConfigurer.addArgumentResolvers(capture(resolvers)); - webMvcConfigurer.addReturnValueHandlers(capture(handlers)); - webMvcConfigurer.configureAsyncSupport(capture(asyncConfigurer)); - replay(webMvcConfigurer); delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter(); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); - assertSame(conversionService.getValue(), initializer.getConversionService()); + ConversionService initializerConversionService = initializer.getConversionService(); assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean); + verify(webMvcConfigurer).configureMessageConverters(converters.capture()); + verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture()); + verify(webMvcConfigurer).addFormatters(conversionService.capture()); + verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture()); + verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture()); + verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture()); + + assertSame(conversionService.getValue(), initializerConversionService); assertEquals(0, resolvers.getValue().size()); assertEquals(0, handlers.getValue().size()); assertEquals(converters.getValue(), adapter.getMessageConverters()); assertNotNull(asyncConfigurer); - - verify(webMvcConfigurer); } @Test @@ -117,47 +127,39 @@ public void configureMessageConverters(List> converters) @Test public void getCustomValidator() { - expect(webMvcConfigurer.getValidator()).andReturn(new LocalValidatorFactoryBean()); - replay(webMvcConfigurer); + given(webMvcConfigurer.getValidator()).willReturn(new LocalValidatorFactoryBean()); delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); delegatingConfig.mvcValidator(); - verify(webMvcConfigurer); + verify(webMvcConfigurer).getValidator(); } @Test public void getCustomMessageCodesResolver() { - expect(webMvcConfigurer.getMessageCodesResolver()).andReturn(new DefaultMessageCodesResolver()); - replay(webMvcConfigurer); + given(webMvcConfigurer.getMessageCodesResolver()).willReturn(new DefaultMessageCodesResolver()); delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); delegatingConfig.getMessageCodesResolver(); - verify(webMvcConfigurer); + verify(webMvcConfigurer).getMessageCodesResolver(); } @Test public void handlerExceptionResolver() throws Exception { - Capture>> converters = new Capture>>(); - Capture> exceptionResolvers = new Capture>(); - Capture contentNegotiationConfigurer = new Capture(); - - webMvcConfigurer.configureMessageConverters(capture(converters)); - webMvcConfigurer.configureContentNegotiation(capture(contentNegotiationConfigurer)); - webMvcConfigurer.configureHandlerExceptionResolvers(capture(exceptionResolvers)); - replay(webMvcConfigurer); delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); delegatingConfig.handlerExceptionResolver(); + verify(webMvcConfigurer).configureMessageConverters(converters.capture()); + verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture()); + verify(webMvcConfigurer).configureHandlerExceptionResolvers(exceptionResolvers.capture()); + assertEquals(3, exceptionResolvers.getValue().size()); assertTrue(exceptionResolvers.getValue().get(0) instanceof ExceptionHandlerExceptionResolver); assertTrue(exceptionResolvers.getValue().get(1) instanceof ResponseStatusExceptionResolver); assertTrue(exceptionResolvers.getValue().get(2) instanceof DefaultHandlerExceptionResolver); assertTrue(converters.getValue().size() > 0); - - verify(webMvcConfigurer); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java index 208225c4333b..b7628eb630e1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; @@ -36,6 +35,8 @@ import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.WebUtils; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller @@ -74,43 +75,31 @@ public void testServletForwardingControllerWithBeanName() throws Exception { private void doTestServletForwardingController(ServletForwardingController sfc, boolean include) throws Exception { - MockControl requestControl = MockControl.createControl(HttpServletRequest.class); - HttpServletRequest request = (HttpServletRequest) requestControl.getMock(); - MockControl responseControl = MockControl.createControl(HttpServletResponse.class); - HttpServletResponse response = (HttpServletResponse) responseControl.getMock(); - MockControl contextControl = MockControl.createControl(ServletContext.class); - ServletContext context = (ServletContext) contextControl.getMock(); - MockControl dispatcherControl = MockControl.createControl(RequestDispatcher.class); - RequestDispatcher dispatcher = (RequestDispatcher) dispatcherControl.getMock(); - - request.getMethod(); - requestControl.setReturnValue("GET", 1); - context.getNamedDispatcher("action"); - contextControl.setReturnValue(dispatcher, 1); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ServletContext context = mock(ServletContext.class); + RequestDispatcher dispatcher = mock(RequestDispatcher.class); + + given(request.getMethod()).willReturn("GET"); + given(context.getNamedDispatcher("action")).willReturn(dispatcher); if (include) { - request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE); - requestControl.setReturnValue("somePath", 1); - dispatcher.include(request, response); - dispatcherControl.setVoidCallable(1); + given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn("somePath"); } else { - request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE); - requestControl.setReturnValue(null, 1); - dispatcher.forward(request, response); - dispatcherControl.setVoidCallable(1); + given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn(null); } - requestControl.replay(); - contextControl.replay(); - dispatcherControl.replay(); StaticWebApplicationContext sac = new StaticWebApplicationContext(); sac.setServletContext(context); sfc.setApplicationContext(sac); assertNull(sfc.handleRequest(request, response)); - requestControl.verify(); - contextControl.verify(); - dispatcherControl.verify(); + if (include) { + verify(dispatcher).include(request, response); + } + else { + verify(dispatcher).forward(request, response); + } } public void testServletWrappingController() throws Exception { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java index fde7ae794657..42aa80abf37c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,27 +15,14 @@ */ package org.springframework.web.servlet.mvc.method.annotation; -import static org.easymock.EasyMock.capture; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.springframework.web.servlet.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; -import org.easymock.Capture; import org.junit.Before; import org.junit.Test; +import org.mockito.ArgumentCaptor; import org.springframework.core.MethodParameter; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; @@ -52,7 +39,12 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.method.support.ModelAndViewContainer; -import org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor; + +import static org.mockito.Mockito.*; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.springframework.web.servlet.HandlerMapping.*; /** * Test fixture for {@link HttpEntityMethodProcessor} delegating to a mock @@ -88,9 +80,8 @@ public class HttpEntityMethodProcessorMockTests { @SuppressWarnings("unchecked") @Before public void setUp() throws Exception { - messageConverter = createMock(HttpMessageConverter.class); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - replay(messageConverter); + messageConverter = mock(HttpMessageConverter.class); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); processor = new HttpEntityMethodProcessor(Collections.>singletonList(messageConverter)); reset(messageConverter); @@ -135,16 +126,14 @@ public void resolveArgument() throws Exception { servletRequest.addHeader("Content-Type", contentType.toString()); String body = "Foo"; - expect(messageConverter.canRead(String.class, contentType)).andReturn(true); - expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); - replay(messageConverter); + given(messageConverter.canRead(String.class, contentType)).willReturn(true); + given(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body); Object result = processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); assertTrue(result instanceof HttpEntity); assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); assertEquals("Invalid argument", body, ((HttpEntity) result).getBody()); - verify(messageConverter); } @Test(expected = HttpMediaTypeNotSupportedException.class) @@ -152,9 +141,8 @@ public void resolveArgumentNotReadable() throws Exception { MediaType contentType = MediaType.TEXT_PLAIN; servletRequest.addHeader("Content-Type", contentType.toString()); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(contentType)); - expect(messageConverter.canRead(String.class, contentType)).andReturn(false); - replay(messageConverter); + given(messageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(contentType)); + given(messageConverter.canRead(String.class, contentType)).willReturn(false); processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); @@ -175,16 +163,14 @@ public void handleReturnValue() throws Exception { MediaType accepted = MediaType.TEXT_PLAIN; servletRequest.addHeader("Accept", accepted.toString()); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); - messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(messageConverter.canWrite(String.class, accepted)).willReturn(true); processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); - verify(messageConverter); + verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); } @Test @@ -195,14 +181,12 @@ public void handleReturnValueProduces() throws Exception { servletRequest.addHeader("Accept", "text/*"); servletRequest.setAttribute(PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); - expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true); - messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); - replay(messageConverter); + given(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).willReturn(true); processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); - verify(messageConverter); + verify(messageConverter).write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); } @Test(expected = HttpMediaTypeNotAcceptableException.class) @@ -213,10 +197,9 @@ public void handleReturnValueNotAcceptable() throws Exception { MediaType accepted = MediaType.APPLICATION_ATOM_XML; servletRequest.addHeader("Accept", accepted.toString()); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); + given(messageConverter.canWrite(String.class, accepted)).willReturn(false); processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); @@ -231,10 +214,9 @@ public void handleReturnValueNotAcceptableProduces() throws Exception { MediaType accepted = MediaType.TEXT_PLAIN; servletRequest.addHeader("Accept", accepted.toString()); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(messageConverter.canWrite(String.class, accepted)).willReturn(false); processor.handleReturnValue(returnValue, returnTypeResponseEntityProduces, mavContainer, webRequest); @@ -270,18 +252,16 @@ public void responseHeaderAndBody() throws Exception { responseHeaders.set("header", "headerValue"); ResponseEntity returnValue = new ResponseEntity("body", responseHeaders, HttpStatus.ACCEPTED); - Capture outputMessage = new Capture(); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).andReturn(true); - messageConverter.write(eq("body"), eq(MediaType.TEXT_PLAIN), capture(outputMessage)); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true); processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest); + ArgumentCaptor outputMessage = ArgumentCaptor.forClass(HttpOutputMessage.class); + verify(messageConverter).write(eq("body"), eq(MediaType.TEXT_PLAIN), outputMessage.capture()); assertTrue(mavContainer.isRequestHandled()); assertEquals("headerValue", outputMessage.getValue().getHeaders().get("header").get(0)); - verify(messageConverter); } public ResponseEntity handle1(HttpEntity httpEntity, ResponseEntity responseEntity, int i) { @@ -302,4 +282,4 @@ public ResponseEntity handle4() { } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java index 5f9869e1dc8d..dd5a4570bdd9 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,6 @@ package org.springframework.web.servlet.mvc.method.annotation; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; @@ -52,19 +38,21 @@ import org.springframework.mock.web.test.MockMultipartHttpServletRequest; import org.springframework.mock.web.test.MockPart; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.ServletWebRequest; -import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.support.MissingServletRequestPartException; import org.springframework.web.multipart.support.RequestPartServletServerHttpRequest; -import org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; /** * Test fixture with {@link RequestPartMethodArgumentResolver} and mock {@link HttpMessageConverter}. @@ -116,9 +104,8 @@ public void setUp() throws Exception { paramServlet30Part.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer()); paramRequestParamAnnot = new MethodParameter(method, 8); - messageConverter = createMock(HttpMessageConverter.class); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - replay(messageConverter); + messageConverter = mock(HttpMessageConverter.class); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); resolver = new RequestPartMethodArgumentResolver(Collections.>singletonList(messageConverter)); reset(messageConverter); @@ -246,17 +233,14 @@ public void isMultipartRequestPut() throws Exception { private void testResolveArgument(SimpleBean argValue, MethodParameter parameter) throws IOException, Exception { MediaType contentType = MediaType.TEXT_PLAIN; - expect(messageConverter.canRead(SimpleBean.class, contentType)).andReturn(true); - expect(messageConverter.read(eq(SimpleBean.class), isA(RequestPartServletServerHttpRequest.class))).andReturn(argValue); - replay(messageConverter); + given(messageConverter.canRead(SimpleBean.class, contentType)).willReturn(true); + given(messageConverter.read(eq(SimpleBean.class), isA(RequestPartServletServerHttpRequest.class))).willReturn(argValue); ModelAndViewContainer mavContainer = new ModelAndViewContainer(); Object actualValue = resolver.resolveArgument(parameter, mavContainer, webRequest, new ValidatingBinderFactory()); assertEquals("Invalid argument value", argValue, actualValue); assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); - - verify(messageConverter); } private static class SimpleBean { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java index 315040419e99..5eb6d49f42ca 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,6 @@ package org.springframework.web.servlet.mvc.method.annotation; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.eq; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.isA; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; -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.junit.Assert.fail; - import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; @@ -61,6 +47,9 @@ import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.servlet.HandlerMapping; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Test fixture for {@link RequestResponseBodyMethodProcessor} delegating to a * mock HttpMessageConverter. @@ -95,12 +84,10 @@ public class RequestResponseBodyMethodProcessorMockTests { @SuppressWarnings("unchecked") @Before public void setUp() throws Exception { - messageConverter = createMock(HttpMessageConverter.class); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - replay(messageConverter); + messageConverter = mock(HttpMessageConverter.class); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); processor = new RequestResponseBodyMethodProcessor(Collections.>singletonList(messageConverter)); - reset(messageConverter); Method methodHandle1 = getClass().getMethod("handle1", String.class, Integer.TYPE); paramRequestBodyString = new MethodParameter(methodHandle1, 0); @@ -138,15 +125,13 @@ public void resolveArgument() throws Exception { String body = "Foo"; servletRequest.setContent(body.getBytes()); - expect(messageConverter.canRead(String.class, contentType)).andReturn(true); - expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); - replay(messageConverter); + given(messageConverter.canRead(String.class, contentType)).willReturn(true); + given(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body); Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory()); assertEquals("Invalid argument", body, result); assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled()); - verify(messageConverter); } @Test @@ -172,16 +157,13 @@ private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOE servletRequest.setContent(new byte[] {}); @SuppressWarnings("unchecked") - HttpMessageConverter beanConverter = createMock(HttpMessageConverter.class); - expect(beanConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(beanConverter.canRead(SimpleBean.class, contentType)).andReturn(true); - expect(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).andReturn(simpleBean); - replay(beanConverter); + HttpMessageConverter beanConverter = mock(HttpMessageConverter.class); + given(beanConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(beanConverter.canRead(SimpleBean.class, contentType)).willReturn(true); + given(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).willReturn(simpleBean); processor = new RequestResponseBodyMethodProcessor(Collections.>singletonList(beanConverter)); processor.resolveArgument(paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory()); - - verify(beanConverter); } @Test(expected = HttpMediaTypeNotSupportedException.class) @@ -189,23 +171,20 @@ public void resolveArgumentCannotRead() throws Exception { MediaType contentType = MediaType.TEXT_PLAIN; servletRequest.addHeader("Content-Type", contentType.toString()); - expect(messageConverter.canRead(String.class, contentType)).andReturn(false); - replay(messageConverter); + given(messageConverter.canRead(String.class, contentType)).willReturn(false); processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); } @Test public void resolveArgumentNoContentType() throws Exception { - expect(messageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).andReturn(false); - replay(messageConverter); + given(messageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false); try { processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); fail("Expected exception"); } catch (HttpMediaTypeNotSupportedException ex) { } - verify(messageConverter); } @Test @@ -223,16 +202,14 @@ public void handleReturnValue() throws Exception { servletRequest.addHeader("Accept", accepted.toString()); String body = "Foo"; - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); - messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(messageConverter.canWrite(String.class, accepted)).willReturn(true); processor.handleReturnValue(body, returnTypeString, mavContainer, webRequest); assertTrue("The requestHandled flag wasn't set", mavContainer.isRequestHandled()); - verify(messageConverter); + verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); } @Test @@ -242,14 +219,12 @@ public void handleReturnValueProduces() throws Exception { servletRequest.addHeader("Accept", "text/*"); servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML)); - expect(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).andReturn(true); - messageConverter.write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); - replay(messageConverter); + given(messageConverter.canWrite(String.class, MediaType.TEXT_HTML)).willReturn(true); processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); - verify(messageConverter); + verify(messageConverter).write(eq(body), eq(MediaType.TEXT_HTML), isA(HttpOutputMessage.class)); } @@ -258,10 +233,9 @@ public void handleReturnValueNotAcceptable() throws Exception { MediaType accepted = MediaType.APPLICATION_ATOM_XML; servletRequest.addHeader("Accept", accepted.toString()); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Arrays.asList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(Arrays.asList(MediaType.TEXT_PLAIN)); + given(messageConverter.canWrite(String.class, accepted)).willReturn(false); processor.handleReturnValue("Foo", returnTypeString, mavContainer, webRequest); } @@ -271,10 +245,9 @@ public void handleReturnValueNotAcceptableProduces() throws Exception { MediaType accepted = MediaType.TEXT_PLAIN; servletRequest.addHeader("Accept", accepted.toString()); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(false); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); + given(messageConverter.canWrite(String.class, accepted)).willReturn(false); processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest); } @@ -289,16 +262,14 @@ public void handleReturnValueMediaTypeSuffix() throws Exception { servletRequest.addHeader("Accept", accepted); - expect(messageConverter.canWrite(String.class, null)).andReturn(true); - expect(messageConverter.getSupportedMediaTypes()).andReturn(supported); - expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); - messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); - replay(messageConverter); + given(messageConverter.canWrite(String.class, null)).willReturn(true); + given(messageConverter.getSupportedMediaTypes()).willReturn(supported); + given(messageConverter.canWrite(String.class, accepted)).willReturn(true); processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); assertTrue(mavContainer.isRequestHandled()); - verify(messageConverter); + verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); } @@ -348,4 +319,4 @@ public String getName() { } } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java index a114680a9429..3f00bf145274 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,6 @@ package org.springframework.web.servlet.tags.form; -import static org.easymock.EasyMock.createMock; - import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; @@ -32,14 +30,16 @@ import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.web.context.support.StaticWebApplicationContext; -import org.springframework.web.servlet.support.RequestDataValueProcessorWrapper; import org.springframework.web.servlet.support.JspAwareRequestContext; import org.springframework.web.servlet.support.RequestContext; import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.servlet.support.RequestDataValueProcessor; +import org.springframework.web.servlet.support.RequestDataValueProcessorWrapper; import org.springframework.web.servlet.tags.AbstractTagTests; import org.springframework.web.servlet.tags.RequestContextAwareTag; +import static org.mockito.BDDMockito.*; + /** * @author Rob Harrop * @author Juergen Hoeller @@ -102,7 +102,7 @@ protected final RequestContext getRequestContext() { } protected RequestDataValueProcessor getMockRequestDataValueProcessor() { - RequestDataValueProcessor mockProcessor = createMock(RequestDataValueProcessor.class); + RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class); ServletRequest request = getPageContext().getRequest(); StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.getWebApplicationContext(request); wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index 3f4247033b52..a687e1efc9d9 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java @@ -16,10 +16,6 @@ package org.springframework.web.servlet.tags.form; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - import java.util.Collections; import javax.servlet.jsp.PageContext; @@ -28,6 +24,8 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.servlet.support.RequestDataValueProcessor; +import static org.mockito.BDDMockito.*; + /** * @author Rob Harrop * @author Rick Evans @@ -328,9 +326,8 @@ public void testClearAttributesOnFinally() throws Exception { public void testRequestDataValueProcessorHooks() throws Exception { String action = "/my/form?foo=bar"; RequestDataValueProcessor processor = getMockRequestDataValueProcessor(); - expect(processor.processAction(this.request, action)).andReturn(action); - expect(processor.getExtraHiddenFields(this.request)).andReturn(Collections.singletonMap("key", "value")); - replay(processor); + given(processor.processAction(this.request, action)).willReturn(action); + given(processor.getExtraHiddenFields(this.request)).willReturn(Collections.singletonMap("key", "value")); this.tag.doStartTag(); this.tag.doEndTag(); @@ -341,8 +338,6 @@ public void testRequestDataValueProcessorHooks() throws Exception { assertEquals("", getInputTag(output)); assertFormTagOpened(output); assertFormTagClosed(output); - - verify(processor); } private String getFormTag(String output) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java index 289fcbf064c1..ad0a6cdae6c1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,6 @@ */ package org.springframework.web.servlet.view; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - import java.io.IOException; import java.util.HashMap; import java.util.Iterator; @@ -40,6 +35,8 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.View; +import static org.mockito.BDDMockito.*; + /** * Tests for AbstractView. Not called AbstractViewTests as * would otherwise be excluded by Ant build script wildcard. @@ -49,11 +46,8 @@ public class BaseViewTests extends TestCase { public void testRenderWithoutStaticAttributes() throws Exception { - - WebApplicationContext wac = createMock(WebApplicationContext.class); - wac.getServletContext(); - expectLastCall().andReturn(new MockServletContext()); - replay(wac); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getServletContext()).willReturn(new MockServletContext()); HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); @@ -72,17 +66,14 @@ public void testRenderWithoutStaticAttributes() throws Exception { checkContainsAll(model, tv.model); assertTrue(tv.inited); - verify(wac); } /** * Test attribute passing, NOT CSV parsing. */ public void testRenderWithStaticAttributesNoCollision() throws Exception { - WebApplicationContext wac = createMock(WebApplicationContext.class); - wac.getServletContext(); - expectLastCall().andReturn(new MockServletContext()); - replay(wac); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getServletContext()).willReturn(new MockServletContext()); HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); @@ -104,14 +95,11 @@ public void testRenderWithStaticAttributesNoCollision() throws Exception { checkContainsAll(p, tv.model); assertTrue(tv.inited); - verify(wac); } public void testPathVarsOverrideStaticAttributes() throws Exception { - WebApplicationContext wac = createMock(WebApplicationContext.class); - wac.getServletContext(); - expectLastCall().andReturn(new MockServletContext()); - replay(wac); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getServletContext()).willReturn(new MockServletContext()); HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); @@ -138,14 +126,11 @@ public void testPathVarsOverrideStaticAttributes() throws Exception { assertTrue(tv.model.get("something").equals("else")); assertTrue(tv.inited); - verify(wac); } public void testDynamicModelOverridesStaticAttributesIfCollision() throws Exception { - WebApplicationContext wac = createMock(WebApplicationContext.class); - wac.getServletContext(); - expectLastCall().andReturn(new MockServletContext()); - replay(wac); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getServletContext()).willReturn(new MockServletContext()); HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); @@ -169,14 +154,11 @@ public void testDynamicModelOverridesStaticAttributesIfCollision() throws Except assertTrue(tv.model.get("something").equals("else")); assertTrue(tv.inited); - verify(wac); } public void testDynamicModelOverridesPathVariables() throws Exception { - WebApplicationContext wac = createMock(WebApplicationContext.class); - wac.getServletContext(); - expectLastCall().andReturn(new MockServletContext()); - replay(wac); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getServletContext()).willReturn(new MockServletContext()); TestView tv = new TestView(wac); tv.setApplicationContext(wac); @@ -202,7 +184,6 @@ public void testDynamicModelOverridesPathVariables() throws Exception { assertTrue(tv.model.get("something").equals("else")); assertTrue(tv.inited); - verify(wac); } public void testIgnoresNullAttributes() { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java index 0cb6e6f108a5..fafea1c9d128 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,6 @@ package org.springframework.web.servlet.view; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -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 java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -53,6 +44,9 @@ import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Arjen Poutsma */ @@ -92,25 +86,21 @@ public void getMediaTypeAcceptHeaderWithProduces() throws Exception { public void resolveViewNameWithPathExtension() throws Exception { request.setRequestURI("/test.xls"); - ViewResolver viewResolverMock = createMock(ViewResolver.class); + ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); - View viewMock = createMock("application_xls", View.class); + View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(null); - expect(viewResolverMock.resolveViewName(viewName + ".xls", locale)).andReturn(viewMock); - expect(viewMock.getContentType()).andReturn("application/vnd.ms-excel").anyTimes(); - - replay(viewResolverMock, viewMock); + given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); + given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); + given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); - - verify(viewResolverMock, viewMock); } @Test @@ -123,23 +113,20 @@ public void resolveViewNameWithAcceptHeader() throws Exception { manager.addFileExtensionResolvers(extensionsResolver); viewResolver.setContentNegotiationManager(manager); - ViewResolver viewResolverMock = createMock(ViewResolver.class); + ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); - View viewMock = createMock("application_xls", View.class); + View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(null); - expect(viewResolverMock.resolveViewName(viewName + ".xls", locale)).andReturn(viewMock); - expect(viewMock.getContentType()).andReturn("application/vnd.ms-excel").anyTimes(); - - replay(viewResolverMock, viewMock); + given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); + given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); + given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); - verify(viewResolverMock, viewMock); } @Test @@ -159,26 +146,21 @@ public void resolveViewNameWithRequestParameter() throws Exception { ParameterContentNegotiationStrategy paramStrategy = new ParameterContentNegotiationStrategy(mapping); viewResolver.setContentNegotiationManager(new ContentNegotiationManager(paramStrategy)); - ViewResolver viewResolverMock = createMock(ViewResolver.class); + ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); - viewResolver.afterPropertiesSet(); - View viewMock = createMock("application_xls", View.class); + View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(null); - expect(viewResolverMock.resolveViewName(viewName + ".xls", locale)).andReturn(viewMock); - expect(viewMock.getContentType()).andReturn("application/vnd.ms-excel").anyTimes(); - - replay(viewResolverMock, viewMock); + given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); + given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); + given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); - - verify(viewResolverMock, viewMock); } @Test @@ -189,58 +171,49 @@ public void resolveViewNameWithDefaultContentType() throws Exception { FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(mediaType); viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy)); - ViewResolver viewResolverMock1 = createMock("viewResolver1", ViewResolver.class); - ViewResolver viewResolverMock2 = createMock("viewResolver2", ViewResolver.class); + ViewResolver viewResolverMock1 = mock(ViewResolver.class, "viewResolver1"); + ViewResolver viewResolverMock2 = mock(ViewResolver.class, "viewResolver2"); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2)); - viewResolver.afterPropertiesSet(); - View viewMock1 = createMock("application_xml", View.class); - View viewMock2 = createMock("text_html", View.class); + View viewMock1 = mock(View.class, "application_xml"); + View viewMock2 = mock(View.class, "text_html"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1); - expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2); - expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes(); - expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes(); - - replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2); + given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1); + given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2); + given(viewMock1.getContentType()).willReturn("application/xml"); + given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock1, result); - - verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2); } @Test public void resolveViewNameAcceptHeader() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); - ViewResolver viewResolverMock1 = createMock(ViewResolver.class); - ViewResolver viewResolverMock2 = createMock(ViewResolver.class); + ViewResolver viewResolverMock1 = mock(ViewResolver.class); + ViewResolver viewResolverMock2 = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2)); viewResolver.afterPropertiesSet(); - View viewMock1 = createMock("application_xml", View.class); - View viewMock2 = createMock("text_html", View.class); + View viewMock1 = mock(View.class, "application_xml"); + View viewMock2 = mock(View.class, "text_html"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1); - expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2); - expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes(); - expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes(); - - replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2); + given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1); + given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2); + given(viewMock1.getContentType()).willReturn("application/xml"); + given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock2, result); - - verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2); } // SPR-9160 @@ -251,26 +224,23 @@ public void resolveViewNameAcceptHeaderSortByQuality() throws Exception { viewResolver.setContentNegotiationManager(new ContentNegotiationManager(new HeaderContentNegotiationStrategy())); - ViewResolver htmlViewResolver = createMock(ViewResolver.class); - ViewResolver jsonViewResolver = createMock(ViewResolver.class); + ViewResolver htmlViewResolver = mock(ViewResolver.class); + ViewResolver jsonViewResolver = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(htmlViewResolver, jsonViewResolver)); - View htmlView = createMock("text_html", View.class); - View jsonViewMock = createMock("application_json", View.class); + View htmlView = mock(View.class, "text_html"); + View jsonViewMock = mock(View.class, "application_json"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(htmlViewResolver.resolveViewName(viewName, locale)).andReturn(htmlView); - expect(jsonViewResolver.resolveViewName(viewName, locale)).andReturn(jsonViewMock); - expect(htmlView.getContentType()).andReturn("text/html").anyTimes(); - expect(jsonViewMock.getContentType()).andReturn("application/json").anyTimes(); - replay(htmlViewResolver, jsonViewResolver, htmlView, jsonViewMock); + given(htmlViewResolver.resolveViewName(viewName, locale)).willReturn(htmlView); + given(jsonViewResolver.resolveViewName(viewName, locale)).willReturn(jsonViewMock); + given(htmlView.getContentType()).willReturn("text/html"); + given(jsonViewMock.getContentType()).willReturn("application/json"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", jsonViewMock, result); - - verify(htmlViewResolver, jsonViewResolver, htmlView, jsonViewMock); } // SPR-9807 @@ -279,40 +249,36 @@ public void resolveViewNameAcceptHeaderSortByQuality() throws Exception { public void resolveViewNameAcceptHeaderWithSuffix() throws Exception { request.addHeader("Accept", "application/vnd.example-v2+xml"); - ViewResolver viewResolverMock = createMock(ViewResolver.class); + ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock)); viewResolver.afterPropertiesSet(); - View viewMock = createMock("application_xml", View.class); + View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock); - expect(viewMock.getContentType()).andReturn("application/*+xml").anyTimes(); - - replay(viewResolverMock, viewMock); + given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); + given(viewMock.getContentType()).willReturn("application/*+xml"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); assertEquals(new MediaType("application", "vnd.example-v2+xml"), request.getAttribute(View.SELECTED_CONTENT_TYPE)); - - verify(viewResolverMock, viewMock); } @Test public void resolveViewNameAcceptHeaderDefaultView() throws Exception { request.addHeader("Accept", "application/json"); - ViewResolver viewResolverMock1 = createMock(ViewResolver.class); - ViewResolver viewResolverMock2 = createMock(ViewResolver.class); + ViewResolver viewResolverMock1 = mock(ViewResolver.class); + ViewResolver viewResolverMock2 = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2)); - View viewMock1 = createMock("application_xml", View.class); - View viewMock2 = createMock("text_html", View.class); - View viewMock3 = createMock("application_json", View.class); + View viewMock1 = mock(View.class, "application_xml"); + View viewMock2 = mock(View.class, "text_html"); + View viewMock3 = mock(View.class, "application_json"); List defaultViews = new ArrayList(); defaultViews.add(viewMock3); @@ -323,49 +289,41 @@ public void resolveViewNameAcceptHeaderDefaultView() throws Exception { String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1); - expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2); - expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes(); - expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes(); - expect(viewMock3.getContentType()).andReturn("application/json").anyTimes(); - - replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3); + given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1); + given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2); + given(viewMock1.getContentType()).willReturn("application/xml"); + given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1"); + given(viewMock3.getContentType()).willReturn("application/json"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock3, result); - - verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3); } @Test public void resolveViewNameFilename() throws Exception { request.setRequestURI("/test.html"); - ViewResolver viewResolverMock1 = createMock("viewResolver1", ViewResolver.class); - ViewResolver viewResolverMock2 = createMock("viewResolver2", ViewResolver.class); + ViewResolver viewResolverMock1 = mock(ViewResolver.class, "viewResolver1"); + ViewResolver viewResolverMock2 = mock(ViewResolver.class, "viewResolver2"); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2)); viewResolver.afterPropertiesSet(); - View viewMock1 = createMock("application_xml", View.class); - View viewMock2 = createMock("text_html", View.class); + View viewMock1 = mock(View.class, "application_xml"); + View viewMock2 = mock(View.class, "text_html"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1); - expect(viewResolverMock1.resolveViewName(viewName + ".html", locale)).andReturn(null); - expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(null); - expect(viewResolverMock2.resolveViewName(viewName + ".html", locale)).andReturn(viewMock2); - expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes(); - expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes(); - - replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2); + given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1); + given(viewResolverMock1.resolveViewName(viewName + ".html", locale)).willReturn(null); + given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(null); + given(viewResolverMock2.resolveViewName(viewName + ".html", locale)).willReturn(viewMock2); + given(viewMock1.getContentType()).willReturn("application/xml"); + given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock2, result); - - verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2); } @Test @@ -376,13 +334,13 @@ public void resolveViewNameFilenameDefaultView() throws Exception { PathExtensionContentNegotiationStrategy pathStrategy = new PathExtensionContentNegotiationStrategy(mapping); viewResolver.setContentNegotiationManager(new ContentNegotiationManager(pathStrategy)); - ViewResolver viewResolverMock1 = createMock(ViewResolver.class); - ViewResolver viewResolverMock2 = createMock(ViewResolver.class); + ViewResolver viewResolverMock1 = mock(ViewResolver.class); + ViewResolver viewResolverMock2 = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2)); - View viewMock1 = createMock("application_xml", View.class); - View viewMock2 = createMock("text_html", View.class); - View viewMock3 = createMock("application_json", View.class); + View viewMock1 = mock(View.class, "application_xml"); + View viewMock2 = mock(View.class, "text_html"); + View viewMock3 = mock(View.class, "application_json"); List defaultViews = new ArrayList(); defaultViews.add(viewMock3); @@ -393,45 +351,37 @@ public void resolveViewNameFilenameDefaultView() throws Exception { String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock1.resolveViewName(viewName, locale)).andReturn(viewMock1); - expect(viewResolverMock1.resolveViewName(viewName + ".json", locale)).andReturn(null); - expect(viewResolverMock2.resolveViewName(viewName, locale)).andReturn(viewMock2); - expect(viewResolverMock2.resolveViewName(viewName + ".json", locale)).andReturn(null); - expect(viewMock1.getContentType()).andReturn("application/xml").anyTimes(); - expect(viewMock2.getContentType()).andReturn("text/html;charset=ISO-8859-1").anyTimes(); - expect(viewMock3.getContentType()).andReturn("application/json").anyTimes(); - - replay(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3); + given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1); + given(viewResolverMock1.resolveViewName(viewName + ".json", locale)).willReturn(null); + given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2); + given(viewResolverMock2.resolveViewName(viewName + ".json", locale)).willReturn(null); + given(viewMock1.getContentType()).willReturn("application/xml"); + given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1"); + given(viewMock3.getContentType()).willReturn("application/json"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock3, result); - - verify(viewResolverMock1, viewResolverMock2, viewMock1, viewMock2, viewMock3); } @Test public void resolveViewContentTypeNull() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); - ViewResolver viewResolverMock = createMock(ViewResolver.class); + ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); - View viewMock = createMock("application_xml", View.class); + View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock); - expect(viewMock.getContentType()).andReturn(null).anyTimes(); - - replay(viewResolverMock, viewMock); + given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); + given(viewMock.getContentType()).willReturn(null); View result = viewResolver.resolveViewName(viewName, locale); assertNull("Invalid view", result); - - verify(viewResolverMock, viewMock); } @Test @@ -445,11 +395,11 @@ public void resolveViewNameRedirectView() throws Exception { UrlBasedViewResolver urlViewResolver = new InternalResourceViewResolver(); urlViewResolver.setApplicationContext(webAppContext); - ViewResolver xmlViewResolver = createMock(ViewResolver.class); + ViewResolver xmlViewResolver = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(xmlViewResolver, urlViewResolver)); - View xmlView = createMock("application_xml", View.class); - View jsonView = createMock("application_json", View.class); + View xmlView = mock(View.class, "application_xml"); + View jsonView = mock(View.class, "application_json"); viewResolver.setDefaultViews(Arrays.asList(jsonView)); viewResolver.afterPropertiesSet(); @@ -457,40 +407,32 @@ public void resolveViewNameRedirectView() throws Exception { String viewName = "redirect:anotherTest"; Locale locale = Locale.ENGLISH; - expect(xmlViewResolver.resolveViewName(viewName, locale)).andReturn(xmlView); - expect(jsonView.getContentType()).andReturn("application/json").anyTimes(); - - replay(xmlViewResolver, xmlView, jsonView); + given(xmlViewResolver.resolveViewName(viewName, locale)).willReturn(xmlView); + given(jsonView.getContentType()).willReturn("application/json"); View actualView = viewResolver.resolveViewName(viewName, locale); assertEquals("Invalid view", RedirectView.class, actualView.getClass()); - - verify(xmlViewResolver, xmlView, jsonView); } @Test public void resolveViewNoMatch() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9"); - ViewResolver viewResolverMock = createMock(ViewResolver.class); + ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); - View viewMock = createMock("application_xml", View.class); + View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock); - expect(viewMock.getContentType()).andReturn("application/pdf").anyTimes(); - - replay(viewResolverMock, viewMock); + given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); + given(viewMock.getContentType()).willReturn("application/pdf"); View result = viewResolver.resolveViewName(viewName, locale); assertNull("Invalid view", result); - - verify(viewResolverMock, viewMock); } @Test @@ -498,28 +440,24 @@ public void resolveViewNoMatchUseUnacceptableStatus() throws Exception { viewResolver.setUseNotAcceptableStatusCode(true); request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9"); - ViewResolver viewResolverMock = createMock(ViewResolver.class); + ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); - View viewMock = createMock("application_xml", View.class); + View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; - expect(viewResolverMock.resolveViewName(viewName, locale)).andReturn(viewMock); - expect(viewMock.getContentType()).andReturn("application/pdf").anyTimes(); - - replay(viewResolverMock, viewMock); + given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); + given(viewMock.getContentType()).willReturn("application/pdf"); View result = viewResolver.resolveViewName(viewName, locale); assertNotNull("Invalid view", result); MockHttpServletResponse response = new MockHttpServletResponse(); result.render(null, request, response); assertEquals("Invalid status code set", 406, response.getStatus()); - - verify(viewResolverMock, viewMock); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java index e46aa5449e58..3a9531b7d059 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.web.servlet.view; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - import java.util.HashMap; import java.util.Iterator; import java.util.Set; @@ -36,6 +31,8 @@ import org.springframework.web.servlet.View; import org.springframework.web.util.WebUtils; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller @@ -150,19 +147,9 @@ public void testAlwaysInclude() throws Exception { String url = "forward-to"; - HttpServletRequest request = createMock(HttpServletRequest.class); - request.getAttribute(View.PATH_VARIABLES); - expectLastCall().andReturn(null); - Set keys = model.keySet(); - for (Iterator iter = keys.iterator(); iter.hasNext();) { - String key = iter.next(); - request.setAttribute(key, model.get(key)); - expectLastCall().times(1); - } - - request.getRequestDispatcher(url); - expectLastCall().andReturn(new MockRequestDispatcher(url)); - replay(request); + HttpServletRequest request = mock(HttpServletRequest.class); + given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null); + given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url)); MockHttpServletResponse response = new MockHttpServletResponse(); InternalResourceView v = new InternalResourceView(); @@ -172,7 +159,12 @@ public void testAlwaysInclude() throws Exception { // Can now try multiple tests v.render(model, request, response); assertEquals(url, response.getIncludedUrl()); - verify(request); + + Set keys = model.keySet(); + for (Iterator iter = keys.iterator(); iter.hasNext();) { + String key = iter.next(); + verify(request).setAttribute(key, model.get(key)); + } } public void testIncludeOnAttribute() throws Exception { @@ -183,21 +175,11 @@ public void testIncludeOnAttribute() throws Exception { String url = "forward-to"; - HttpServletRequest request = createMock(HttpServletRequest.class); - request.getAttribute(View.PATH_VARIABLES); - expectLastCall().andReturn(null); - Set keys = model.keySet(); - for (Iterator iter = keys.iterator(); iter.hasNext();) { - String key = iter.next(); - request.setAttribute(key, model.get(key)); - expectLastCall().times(1); - } + HttpServletRequest request = mock(HttpServletRequest.class); + given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null); - request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE); - expectLastCall().andReturn("somepath"); - request.getRequestDispatcher(url); - expectLastCall().andReturn(new MockRequestDispatcher(url)); - replay(request); + given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn("somepath"); + given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url)); MockHttpServletResponse response = new MockHttpServletResponse(); InternalResourceView v = new InternalResourceView(); @@ -206,7 +188,12 @@ public void testIncludeOnAttribute() throws Exception { // Can now try multiple tests v.render(model, request, response); assertEquals(url, response.getIncludedUrl()); - verify(request); + + Set keys = model.keySet(); + for (Iterator iter = keys.iterator(); iter.hasNext();) { + String key = iter.next(); + verify(request).setAttribute(key, model.get(key)); + } } public void testIncludeOnCommitted() throws Exception { @@ -217,21 +204,11 @@ public void testIncludeOnCommitted() throws Exception { String url = "forward-to"; - HttpServletRequest request = createMock(HttpServletRequest.class); - request.getAttribute(View.PATH_VARIABLES); - expectLastCall().andReturn(null); - Set keys = model.keySet(); - for (Iterator iter = keys.iterator(); iter.hasNext();) { - String key = iter.next(); - request.setAttribute(key, model.get(key)); - expectLastCall().times(1); - } + HttpServletRequest request = mock(HttpServletRequest.class); + given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null); - request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE); - expectLastCall().andReturn(null); - request.getRequestDispatcher(url); - expectLastCall().andReturn(new MockRequestDispatcher(url)); - replay(request); + given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn(null); + given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url)); MockHttpServletResponse response = new MockHttpServletResponse(); response.setCommitted(true); @@ -241,7 +218,12 @@ public void testIncludeOnCommitted() throws Exception { // Can now try multiple tests v.render(model, request, response); assertEquals(url, response.getIncludedUrl()); - verify(request); + + Set keys = model.keySet(); + for (Iterator iter = keys.iterator(); iter.hasNext();) { + String key = iter.next(); + verify(request).setAttribute(key, model.get(key)); + } } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java index d3c45fb24931..c3fd2614102b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java @@ -16,14 +16,6 @@ package org.springframework.web.servlet.view; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.createNiceMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -34,13 +26,12 @@ import junit.framework.AssertionFailedError; -import org.easymock.EasyMock; import org.junit.Test; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.http.HttpStatus; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletContext; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.ui.ModelMap; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.support.StaticWebApplicationContext; @@ -53,6 +44,9 @@ import org.springframework.web.servlet.support.SessionFlashMapManager; import org.springframework.web.util.WebUtils; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Tests for redirect view, and query string construction. * Doesn't test URL encoding, although it does check that it's called. @@ -156,7 +150,7 @@ public void updateTargetUrl() throws Exception { wac.setServletContext(new MockServletContext()); wac.refresh(); - RequestDataValueProcessor mockProcessor = createMock(RequestDataValueProcessor.class); + RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class); wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor); RedirectView rv = new RedirectView(); @@ -167,12 +161,11 @@ public void updateTargetUrl() throws Exception { request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); HttpServletResponse response = new MockHttpServletResponse(); - EasyMock.expect(mockProcessor.processUrl(request, "/path")).andReturn("/path?key=123"); - EasyMock.replay(mockProcessor); + given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123"); rv.render(new ModelMap(), request, response); - EasyMock.verify(mockProcessor); + verify(mockProcessor).processUrl(request, "/path"); } @@ -186,7 +179,7 @@ public void updateTargetUrlWithContextLoader() throws Exception { contextLoader.initWebApplicationContext(servletContext); try { - RequestDataValueProcessor mockProcessor = createMock(RequestDataValueProcessor.class); + RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class); wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor); RedirectView rv = new RedirectView(); @@ -195,12 +188,11 @@ public void updateTargetUrlWithContextLoader() throws Exception { MockHttpServletRequest request = createRequest(); HttpServletResponse response = new MockHttpServletResponse(); - EasyMock.expect(mockProcessor.processUrl(request, "/path")).andReturn("/path?key=123"); - EasyMock.replay(mockProcessor); + given(mockProcessor.processUrl(request, "/path")).willReturn("/path?key=123"); rv.render(new ModelMap(), request, response); - EasyMock.verify(mockProcessor); + verify(mockProcessor).processUrl(request, "/path"); } finally { contextLoader.closeWebApplicationContext(servletContext); @@ -363,32 +355,28 @@ protected Map queryProperties(Map model) { rv.setContextRelative(contextRelative); rv.setExposeModelAttributes(exposeModelAttributes); - HttpServletRequest request = createNiceMock("request", HttpServletRequest.class); + HttpServletRequest request = mock(HttpServletRequest.class, "request"); if (exposeModelAttributes) { - expect(request.getCharacterEncoding()).andReturn(WebUtils.DEFAULT_CHARACTER_ENCODING); + given(request.getCharacterEncoding()).willReturn(WebUtils.DEFAULT_CHARACTER_ENCODING); } if (contextRelative) { expectedUrlForEncoding = "/context" + expectedUrlForEncoding; - expect(request.getContextPath()).andReturn("/context"); + given(request.getContextPath()).willReturn("/context"); } - expect(request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE)).andReturn(new FlashMap()); + given(request.getAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE)).willReturn(new FlashMap()); FlashMapManager flashMapManager = new SessionFlashMapManager(); - expect(request.getAttribute(DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE)).andReturn(flashMapManager); + given(request.getAttribute(DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE)).willReturn(flashMapManager); - HttpServletResponse response = createMock("response", HttpServletResponse.class); - expect(response.encodeRedirectURL(expectedUrlForEncoding)).andReturn(expectedUrlForEncoding); + HttpServletResponse response = mock(HttpServletResponse.class, "response"); + given(response.encodeRedirectURL(expectedUrlForEncoding)).willReturn(expectedUrlForEncoding); response.sendRedirect(expectedUrlForEncoding); - replay(request, response); - rv.render(map, request, response); if (exposeModelAttributes) { assertTrue("queryProperties() should have been called.", rv.queryPropertiesCalled); } - - verify(request, response); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerViewTests.java index ff233b9be2fb..0131151f0e91 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,16 +23,10 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; + import javax.servlet.http.HttpServletResponse; -import freemarker.ext.servlet.AllHttpScopesHashModel; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; -import org.easymock.MockControl; -import static org.junit.Assert.*; import org.junit.Test; - import org.springframework.context.ApplicationContextException; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; @@ -46,6 +40,14 @@ import org.springframework.web.servlet.view.InternalResourceView; import org.springframework.web.servlet.view.RedirectView; +import freemarker.ext.servlet.AllHttpScopesHashModel; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 14.03.2004 @@ -56,15 +58,9 @@ public class FreeMarkerViewTests { public void testNoFreeMarkerConfig() throws Exception { FreeMarkerView fv = new FreeMarkerView(); - MockControl wmc = MockControl.createControl(WebApplicationContext.class); - WebApplicationContext wac = (WebApplicationContext) wmc.getMock(); - wac.getBeansOfType(FreeMarkerConfig.class, true, false); - wmc.setReturnValue(new HashMap()); - wac.getParentBeanFactory(); - wmc.setReturnValue(null); - wac.getServletContext(); - wmc.setReturnValue(new MockServletContext()); - wmc.replay(); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(new HashMap()); + given(wac.getServletContext()).willReturn(new MockServletContext()); fv.setUrl("anythingButNull"); try { @@ -76,8 +72,6 @@ public void testNoFreeMarkerConfig() throws Exception { // Check there's a helpful error message assertTrue(ex.getMessage().indexOf("FreeMarkerConfig") != -1); } - - wmc.verify(); } @Test @@ -97,21 +91,15 @@ public void testNoTemplateName() throws Exception { public void testValidTemplateName() throws Exception { FreeMarkerView fv = new FreeMarkerView(); - MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class); - WebApplicationContext wac = (WebApplicationContext) wmc.getMock(); + WebApplicationContext wac = mock(WebApplicationContext.class); MockServletContext sc = new MockServletContext(); - wac.getBeansOfType(FreeMarkerConfig.class, true, false); Map configs = new HashMap(); FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setConfiguration(new TestConfiguration()); configs.put("configurer", configurer); - wmc.setReturnValue(configs); - wac.getParentBeanFactory(); - wmc.setReturnValue(null); - wac.getServletContext(); - wmc.setReturnValue(sc, 2); - wmc.replay(); + given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(configs); + given(wac.getServletContext()).willReturn(sc); fv.setUrl("templateName"); fv.setApplicationContext(wac); @@ -126,7 +114,6 @@ public void testValidTemplateName() throws Exception { model.put("myattr", "myvalue"); fv.render(model, request, response); - wmc.verify(); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, response.getContentType()); } @@ -134,21 +121,15 @@ public void testValidTemplateName() throws Exception { public void testKeepExistingContentType() throws Exception { FreeMarkerView fv = new FreeMarkerView(); - MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class); - WebApplicationContext wac = (WebApplicationContext) wmc.getMock(); + WebApplicationContext wac = mock(WebApplicationContext.class); MockServletContext sc = new MockServletContext(); - wac.getBeansOfType(FreeMarkerConfig.class, true, false); Map configs = new HashMap(); FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); configurer.setConfiguration(new TestConfiguration()); configs.put("configurer", configurer); - wmc.setReturnValue(configs); - wac.getParentBeanFactory(); - wmc.setReturnValue(null); - wac.getServletContext(); - wmc.setReturnValue(sc, 2); - wmc.replay(); + given(wac.getBeansOfType(FreeMarkerConfig.class, true, false)).willReturn(configs); + given(wac.getServletContext()).willReturn(sc); fv.setUrl("templateName"); fv.setApplicationContext(wac); @@ -164,7 +145,6 @@ public void testKeepExistingContentType() throws Exception { model.put("myattr", "myvalue"); fv.render(model, request, response); - wmc.verify(); assertEquals("myContentType", response.getContentType()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsViewTests.java index 5350f1599995..463fe47d2884 100755 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/AbstractJasperReportsViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,15 +32,16 @@ import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JRAbstractBeanDataSourceProvider; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; -import org.easymock.MockControl; -import org.junit.Ignore; +import org.junit.Ignore; import org.springframework.context.ApplicationContextException; import org.springframework.mock.web.test.MockServletContext; import org.springframework.ui.jasperreports.PersonBean; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; +import static org.mockito.BDDMockito.*; + /** * @author Rob Harrop * @author Juergen Hoeller @@ -372,11 +373,8 @@ public void testJRDataSourceOverridesJdbcDataSource() throws Exception { } private DataSource getMockJdbcDataSource() throws SQLException { - MockControl ctl = MockControl.createControl(DataSource.class); - DataSource ds = (DataSource) ctl.getMock(); - ds.getConnection(); - ctl.setThrowable(new SQLException()); - ctl.replay(); + DataSource ds = mock(DataSource.class); + given(ds.getConnection()).willThrow(new SQLException()); return ds; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java index d1cd12d8b48f..5874985aa335 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,6 @@ package org.springframework.web.servlet.view.json; -import static org.easymock.EasyMock.createMock; -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 java.io.IOException; import java.util.Date; import java.util.HashMap; @@ -56,6 +49,9 @@ import com.fasterxml.jackson.databind.ser.SerializerFactory; import com.fasterxml.jackson.databind.ser.Serializers; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Jeremy Grelle * @author Arjen Poutsma @@ -93,7 +89,7 @@ public void isExposePathVars() { public void renderSimpleMap() throws Exception { Map model = new HashMap(); - model.put("bindingResult", createMock("binding_result", BindingResult.class)); + model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", "bar"); view.setUpdateContentLength(true); @@ -133,7 +129,7 @@ public void renderCaching() throws Exception { view.setDisableCaching(false); Map model = new HashMap(); - model.put("bindingResult", createMock("binding_result", BindingResult.class)); + model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", "bar"); view.render(model, request, response); @@ -154,7 +150,7 @@ public void renderSimpleBean() throws Exception { Object bean = new TestBeanSimple(); Map model = new HashMap(); - model.put("bindingResult", createMock("binding_result", BindingResult.class)); + model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", bean); view.setUpdateContentLength(true); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJacksonJsonViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJacksonJsonViewTests.java index da6a9b6418c0..1e2f9eda5eb4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJacksonJsonViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJacksonJsonViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,6 @@ package org.springframework.web.servlet.view.json; -import static org.easymock.EasyMock.createMock; -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 java.io.IOException; import java.util.Date; import java.util.HashMap; @@ -48,6 +41,9 @@ import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Jeremy Grelle * @author Arjen Poutsma @@ -84,7 +80,7 @@ public void isExposePathVars() { public void renderSimpleMap() throws Exception { Map model = new HashMap(); - model.put("bindingResult", createMock("binding_result", BindingResult.class)); + model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", "bar"); view.setUpdateContentLength(true); @@ -108,7 +104,7 @@ public void renderCaching() throws Exception { view.setDisableCaching(false); Map model = new HashMap(); - model.put("bindingResult", createMock("binding_result", BindingResult.class)); + model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", "bar"); view.render(model, request, response); @@ -129,7 +125,7 @@ public void renderSimpleBean() throws Exception { Object bean = new TestBeanSimple(); Map model = new HashMap(); - model.put("bindingResult", createMock("binding_result", BindingResult.class)); + model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", bean); view.setUpdateContentLength(true); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java index ac1a396f6596..dd0f8749d1e3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,6 @@ package org.springframework.web.servlet.view.velocity; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expectLastCall; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -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 java.io.IOException; import java.util.HashMap; import java.util.Locale; @@ -53,6 +44,9 @@ import org.springframework.web.servlet.support.RequestDataValueProcessor; import org.springframework.web.servlet.view.AbstractView; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Rod Johnson * @author Juergen Hoeller @@ -63,12 +57,8 @@ public class VelocityViewTests { @Test public void testNoVelocityConfig() throws Exception { VelocityView vv = new VelocityView(); - WebApplicationContext wac = createMock(WebApplicationContext.class); - wac.getBeansOfType(VelocityConfig.class, true, false); - expectLastCall().andReturn(new HashMap()); - wac.getParentBeanFactory(); - expectLastCall().andReturn(null); - replay(wac); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(new HashMap()); vv.setUrl("anythingButNull"); try { @@ -79,8 +69,6 @@ public void testNoVelocityConfig() throws Exception { // Check there's a helpful error message assertTrue(ex.getMessage().contains("VelocityConfig")); } - - verify(wac); } @Test @@ -131,7 +119,7 @@ private void testValidTemplateName(final Exception mergeTemplateFailureException final String templateName = "test.vm"; - WebApplicationContext wac = createMock(WebApplicationContext.class); + WebApplicationContext wac = mock(WebApplicationContext.class); MockServletContext sc = new MockServletContext(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); @@ -142,17 +130,12 @@ public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; - wac.getBeansOfType(VelocityConfig.class, true, false); - Map configurers = new HashMap(); + Map configurers = new HashMap(); configurers.put("velocityConfigurer", vc); - expectLastCall().andReturn(configurers); - wac.getParentBeanFactory(); - expectLastCall().andReturn(null); - wac.getServletContext(); - expectLastCall().andReturn(sc).times(3); - wac.getBean("requestDataValueProcessor", RequestDataValueProcessor.class); - expectLastCall().andReturn(null); - replay(wac); + given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers); + given(wac.getServletContext()).willReturn(sc); + given(wac.getBean("requestDataValueProcessor", + RequestDataValueProcessor.class)).willReturn(null); HttpServletRequest request = new MockHttpServletRequest(); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); @@ -182,15 +165,13 @@ protected void mergeTemplate(Template template, Context context, HttpServletResp assertNotNull(mergeTemplateFailureException); assertEquals(ex, mergeTemplateFailureException); } - - verify(wac); } @Test public void testKeepExistingContentType() throws Exception { final String templateName = "test.vm"; - WebApplicationContext wac = createMock(WebApplicationContext.class); + WebApplicationContext wac = mock(WebApplicationContext.class); MockServletContext sc = new MockServletContext(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); @@ -201,17 +182,12 @@ public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; - wac.getBeansOfType(VelocityConfig.class, true, false); - Map configurers = new HashMap(); + Map configurers = new HashMap(); configurers.put("velocityConfigurer", vc); - expectLastCall().andReturn(configurers); - wac.getParentBeanFactory(); - expectLastCall().andReturn(null); - wac.getServletContext(); - expectLastCall().andReturn(sc).times(3); - wac.getBean("requestDataValueProcessor", RequestDataValueProcessor.class); - expectLastCall().andReturn(null); - replay(wac); + given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers); + given(wac.getServletContext()).willReturn(sc); + given(wac.getBean("requestDataValueProcessor", + RequestDataValueProcessor.class)).willReturn(null); HttpServletRequest request = new MockHttpServletRequest(); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); @@ -233,7 +209,6 @@ protected void exposeHelpers(Map model, HttpServletRequest reque vv.setApplicationContext(wac); vv.render(new HashMap(), request, expectedResponse); - verify(wac); assertEquals("myContentType", expectedResponse.getContentType()); } @@ -241,11 +216,8 @@ protected void exposeHelpers(Map model, HttpServletRequest reque public void testExposeHelpers() throws Exception { final String templateName = "test.vm"; - WebApplicationContext wac = createMock(WebApplicationContext.class); - wac.getParentBeanFactory(); - expectLastCall().andReturn(null); - wac.getServletContext(); - expectLastCall().andReturn(new MockServletContext()); + WebApplicationContext wac = mock(WebApplicationContext.class); + given(wac.getServletContext()).willReturn(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @@ -254,22 +226,16 @@ public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(templateName, expectedTemplate); } }; - wac.getBeansOfType(VelocityConfig.class, true, false); - Map configurers = new HashMap(); + Map configurers = new HashMap(); configurers.put("velocityConfigurer", vc); - expectLastCall().andReturn(configurers); - replay(wac); + given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers); // let it ask for locale - HttpServletRequest req = createMock(HttpServletRequest.class); - req.getAttribute(View.PATH_VARIABLES); - expectLastCall().andReturn(null); - req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE); - expectLastCall().andReturn(new AcceptHeaderLocaleResolver()); - req.getLocale(); - expectLastCall().andReturn(Locale.CANADA); - replay(req); + HttpServletRequest req = mock(HttpServletRequest.class); + given(req.getAttribute(View.PATH_VARIABLES)).willReturn(null); + given(req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).willReturn(new AcceptHeaderLocaleResolver()); + given(req.getLocale()).willReturn(Locale.CANADA); final HttpServletResponse expectedResponse = new MockHttpServletResponse(); @@ -308,8 +274,6 @@ protected void exposeHelpers(Map model, HttpServletRequest reque vv.render(new HashMap(), req, expectedResponse); - verify(wac); - verify(req); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType()); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xml/MarshallingViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xml/MarshallingViewTests.java index d51fc618bfa4..6b767c7f78e2 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xml/MarshallingViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xml/MarshallingViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,18 +18,19 @@ import java.util.HashMap; import java.util.Map; + import javax.servlet.ServletException; import javax.xml.transform.stream.StreamResult; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; - import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.oxm.Marshaller; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Arjen Poutsma */ @@ -41,7 +42,7 @@ public class MarshallingViewTests { @Before public void createView() throws Exception { - marshallerMock = createMock(Marshaller.class); + marshallerMock = mock(Marshaller.class); view = new MarshallingView(marshallerMock); } @@ -71,14 +72,12 @@ public void renderModelKey() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - expect(marshallerMock.supports(Object.class)).andReturn(true); + given(marshallerMock.supports(Object.class)).willReturn(true); marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class)); - replay(marshallerMock); view.render(model, request, response); assertEquals("Invalid content type", "application/xml", response.getContentType()); assertEquals("Invalid content length", 0, response.getContentLength()); - verify(marshallerMock); } @Test @@ -92,7 +91,6 @@ public void renderInvalidModelKey() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - replay(marshallerMock); try { view.render(model, request, response); fail("ServletException expected"); @@ -101,7 +99,6 @@ public void renderInvalidModelKey() throws Exception { // expected } assertEquals("Invalid content length", 0, response.getContentLength()); - verify(marshallerMock); } @Test @@ -113,7 +110,6 @@ public void renderNullModelValue() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - replay(marshallerMock); try { view.render(model, request, response); fail("ServletException expected"); @@ -122,7 +118,6 @@ public void renderNullModelValue() throws Exception { // expected } assertEquals("Invalid content length", 0, response.getContentLength()); - verify(marshallerMock); } @Test @@ -136,9 +131,8 @@ public void renderModelKeyUnsupported() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - expect(marshallerMock.supports(Object.class)).andReturn(false); + given(marshallerMock.supports(Object.class)).willReturn(false); - replay(marshallerMock); try { view.render(model, request, response); fail("ServletException expected"); @@ -146,7 +140,6 @@ public void renderModelKeyUnsupported() throws Exception { catch (ServletException ex) { // expected } - verify(marshallerMock); } @Test @@ -159,14 +152,12 @@ public void renderNoModelKey() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - expect(marshallerMock.supports(Object.class)).andReturn(true); - marshallerMock.marshal(eq(toBeMarshalled), isA(StreamResult.class)); + given(marshallerMock.supports(Object.class)).willReturn(true); - replay(marshallerMock); view.render(model, request, response); assertEquals("Invalid content type", "application/xml", response.getContentType()); assertEquals("Invalid content length", 0, response.getContentLength()); - verify(marshallerMock); + verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class)); } @Test @@ -179,9 +170,8 @@ public void testRenderUnsupportedModel() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - expect(marshallerMock.supports(Object.class)).andReturn(false); + given(marshallerMock.supports(Object.class)).willReturn(false); - replay(marshallerMock); try { view.render(model, request, response); fail("ServletException expected"); @@ -189,7 +179,6 @@ public void testRenderUnsupportedModel() throws Exception { catch (ServletException ex) { // expected } - verify(marshallerMock); } } diff --git a/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java b/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java index aca10a3fb264..8468024f9947 100644 --- a/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java +++ b/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java @@ -16,14 +16,6 @@ package org.springframework.scheduling.annotation; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.replay; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.greaterThan; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; @@ -43,6 +35,10 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * Integration tests cornering bug SPR-8651, which revealed that @Scheduled methods may * not work well with beans that have already been proxied for other reasons such @@ -81,7 +77,7 @@ public void succeedsWhenSubclassProxyAndScheduledMethodNotPresentOnInterface() t MyRepository repository = ctx.getBean(MyRepository.class); CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class); - assertThat("repository is not a proxy", AopUtils.isAopProxy(repository), is(true)); + assertThat("repository is not a proxy", AopUtils.isAopProxy(repository), equalTo(true)); assertThat("@Scheduled method never called", repository.getInvocationCount(), greaterThan(0)); assertThat("no transactions were committed", txManager.commits, greaterThan(0)); } @@ -142,8 +138,7 @@ public PlatformTransactionManager txManager() { @Bean public PersistenceExceptionTranslator peTranslator() { - PersistenceExceptionTranslator txlator = createMock(PersistenceExceptionTranslator.class); - replay(txlator); + PersistenceExceptionTranslator txlator = mock(PersistenceExceptionTranslator.class); return txlator; } }