From db823ba1e4db667c1da6b77e4511ef84676edc84 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 22:52:27 +0100 Subject: [PATCH 01/28] DefaultListableBeanFactory clears by-type matching cache on runtime register/destroySingleton calls Issue: SPR-10326 --- .../support/DefaultListableBeanFactory.java | 37 ++++++++++++++----- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index bffe7e764f..e88e04f469 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -135,11 +135,11 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto /** Map of bean definition objects, keyed by bean name */ private final Map beanDefinitionMap = new ConcurrentHashMap(64); - /** Map of singleton bean names keyed by bean class */ - private final Map, String[]> singletonBeanNamesByType = new ConcurrentHashMap, String[]>(64); + /** Map of singleton and non-singleton bean names keyed by dependency type */ + private final Map, String[]> allBeanNamesByType = new ConcurrentHashMap, String[]>(64); - /** Map of non-singleton bean names keyed by bean class */ - private final Map, String[]> nonSingletonBeanNamesByType = new ConcurrentHashMap, String[]>(64); + /** Map of singleton-only bean names keyed by dependency type */ + private final Map, String[]> singletonBeanNamesByType = new ConcurrentHashMap, String[]>(64); /** List of bean definition names, in registration order */ private final List beanDefinitionNames = new ArrayList(); @@ -326,8 +326,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto if (!isConfigurationFrozen() || type == null || !allowEagerInit) { return doGetBeanNamesForType(type, includeNonSingletons, allowEagerInit); } - Map, String[]> cache = includeNonSingletons ? - this.nonSingletonBeanNamesByType : this.singletonBeanNamesByType; + Map, String[]> cache = + (includeNonSingletons ? this.allBeanNamesByType : this.singletonBeanNamesByType); String[] resolvedBeanNames = cache.get(type); if (resolvedBeanNames != null) { return resolvedBeanNames; @@ -707,9 +707,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto // (e.g. the default StaticMessageSource in a StaticApplicationContext). destroySingleton(beanName); - // Remove any assumptions about by-type mappings - this.singletonBeanNamesByType.clear(); - this.nonSingletonBeanNamesByType.clear(); + // Remove any assumptions about by-type mappings. + clearByTypeCache(); // Reset all bean definitions that have the given bean as parent (recursively). for (String bdName : this.beanDefinitionNames) { @@ -730,6 +729,26 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto return this.allowBeanDefinitionOverriding; } + @Override + public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException { + super.registerSingleton(beanName, singletonObject); + clearByTypeCache(); + } + + @Override + public void destroySingleton(String beanName) { + super.destroySingleton(beanName); + clearByTypeCache(); + } + + /** + * Remove any assumptions about by-type mappings. + */ + private void clearByTypeCache() { + this.allBeanNamesByType.clear(); + this.singletonBeanNamesByType.clear(); + } + //--------------------------------------------------------------------- // Dependency resolution functionality From 2302b9b48b952f254ca96df71855b716bdbfddfd Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 6 Mar 2013 09:53:12 +0100 Subject: [PATCH 02/28] Added locale-independent "commonMessages" property to AbstractMessageSource Issue: SPR-10291 --- .../support/AbstractMessageSource.java | 31 ++++++++++++++++++- .../ResourceBundleMessageSourceTests.java | 12 +++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/spring-context/src/main/java/org/springframework/context/support/AbstractMessageSource.java b/spring-context/src/main/java/org/springframework/context/support/AbstractMessageSource.java index 768c963d3b..ddf87c9332 100644 --- a/spring-context/src/main/java/org/springframework/context/support/AbstractMessageSource.java +++ b/spring-context/src/main/java/org/springframework/context/support/AbstractMessageSource.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,6 +20,7 @@ import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; +import java.util.Properties; import org.springframework.context.HierarchicalMessageSource; import org.springframework.context.MessageSource; @@ -64,6 +65,8 @@ public abstract class AbstractMessageSource extends MessageSourceSupport impleme private MessageSource parentMessageSource; + private Properties commonMessages; + private boolean useCodeAsDefaultMessage = false; @@ -75,6 +78,23 @@ public abstract class AbstractMessageSource extends MessageSourceSupport impleme return this.parentMessageSource; } + /** + * Specify locale-independent common messages, with the message code as key + * and the full message String (may contain argument placeholders) as value. + *

May also link to an externally defined Properties object, e.g. defined + * through a {@link org.springframework.beans.factory.config.PropertiesFactoryBean}. + */ + public void setCommonMessages(Properties commonMessages) { + this.commonMessages = commonMessages; + } + + /** + * Return a Properties object defining locale-independent common messages, if any. + */ + protected Properties getCommonMessages() { + return this.commonMessages; + } + /** * Set whether to use the message code as default message instead of * throwing a NoSuchMessageException. Useful for development and debugging. @@ -210,6 +230,15 @@ public abstract class AbstractMessageSource extends MessageSourceSupport impleme } } + // Check locale-independent common messages for the given message code. + Properties commonMessages = getCommonMessages(); + if (commonMessages != null) { + String commonMessage = commonMessages.getProperty(code); + if (commonMessage != null) { + return formatMessage(commonMessage, args, locale); + } + } + // Not found -> check parent, if any. return getMessageFromParent(code, argsToUse, locale); } diff --git a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java index c0121a4a2d..3a265516cd 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java @@ -249,6 +249,18 @@ public class ResourceBundleMessageSourceTests extends TestCase { assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); } + public void testReloadableResourceBundleMessageSourceWithCommonMessages() { + ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource(); + Properties commonMessages = new Properties(); + commonMessages.setProperty("warning", "Do not do {0}"); + ms.setCommonMessages(commonMessages); + ms.setBasename("org/springframework/context/support/messages"); + assertEquals("message1", ms.getMessage("code1", null, Locale.ENGLISH)); + assertEquals("nachricht2", ms.getMessage("code2", null, Locale.GERMAN)); + assertEquals("Do not do this", ms.getMessage("warning", new Object[] {"this"}, Locale.ENGLISH)); + assertEquals("Do not do that", ms.getMessage("warning", new Object[] {"that"}, Locale.GERMAN)); + } + public void testReloadableResourceBundleMessageSourceWithWhitespaceInBasename() { ReloadableResourceBundleMessageSource ms = new ReloadableResourceBundleMessageSource(); ms.setBasename(" org/springframework/context/support/messages "); From 05765d752062f37b202e7dfd20593c995dc47df0 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 4 Mar 2013 19:46:15 -0800 Subject: [PATCH 03/28] 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 | 95 +- .../jca/cci/CciTemplateTests.java | 685 ++++++-------- .../jca/cci/EisOperationTests.java | 190 ++-- .../LocalConnectionFactoryBeanTests.java | 32 +- .../JndiJtaTransactionManagerTests.java | 95 +- .../JtaTransactionManagerTests.java | 833 +++++------------- .../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 | 596 ++++++------- .../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 | 45 +- .../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, 2329 insertions(+), 4272 deletions(-) diff --git a/build.gradle b/build.gradle index bf5df93e85..fac5af1ec0 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 e13097c4b6..f2224a4134 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.junit.Test; 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 0c1c50c9c5..6146571fa6 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 d0cee0780e..5096fe88dd 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 bf2c45fc2c..a08b03064a 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 96501f2c14..5bdeb414df 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 9ec42626db..4e3d3ca619 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 7a7257ea2f..cf959b324c 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.SerializablePerson; 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 94f6376ce1..73c2ab592a 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.tests.sample.beans.factory.DummyFactory; 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 class DefaultListableBeanFactoryTests { 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 f06388cc8d..4c6725e01e 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.Before; 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 dc56161776..a41a5c97bb 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.beans.factory.xml.XmlBeanDefinitionReader; 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 f7ab438e76..ae7c2b8451 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.beans.factory.support.DefaultListableBeanFactory; 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 622b7fda5d..af6ec0c484 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 625e8c7085..7b039cc660 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.BeanDefinitionBuilder; 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 ca55ed9a0e..04d7bda02f 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.Trigger; 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 364d541592..b078e3c004 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 c04a54f8e6..3d6f902d34 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 0760507924..c98aea5211 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 879e846b2b..0d9911560e 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 94e6e43f8a..c313c6f339 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 753fb3341a..7959a45b08 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 77101f6cc9..562ab9bf32 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 33bdac26e8..f9aefe64da 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 9a3ced52d7..a8b40b2ac3 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.annotation.EnableLoadTimeWeaving.AspectJWeavi 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 d124bac830..24c1a4da95 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.HashSet; 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.BeanThatBroadcasts; 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 1a0e064b75..128abf301d 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 b8206b21a2..a87d56eb9b 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.junit.Test; 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 c0a78215bd..d10dce2a5a 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 javax.naming.NamingException; 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 0c03c57c69..0191220b1b 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.aop.framework.ProxyFactory; 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 8e03115c1f..68af4a9b06 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.junit.Test; 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 4ad2255d2c..d9d7e60ac6 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.DerivedTestBean; 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 4018802475..ef73a867f1 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 0560184010..93b33b48bc 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 junit.framework.TestCase; 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.ScriptCompilationException; 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 cca1625d3d..7ced7671ce 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 org.springframework.util.ObjectUtils; 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 5a5b72715c..a443bee0bb 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 e1fe7c848e..08c9353bb9 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 junit.framework.TestCase; 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 d561ac7e7e..680bbe65d2 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.Assume; 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 fe10d23596..61810c98ec 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.Before; 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 0c3b9f0e49..3ced43ba0c 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.ext.LexicalHandler; 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 5a34a003ee..355cb94438 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.ContentHandler; 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 ba84eadd76..e074085f6d 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 @@ package org.springframework.util.xml; 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 98016c6113..e6e2121c8d 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.core.test.SpacePerson; 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 86518a5f87..f9963c1123 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.Test; 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 3c4e1bc73a..ffa2d74ddf 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.NativeJdbcExtractor; 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 60a4b4b349..a44686f3a6 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 junit.framework.TestCase; 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 00e229ba9d..694c3c65fa 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 java.util.GregorianCalendar; 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 c17c8bbc02..a8c27275e8 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.HashMap; 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 org.springframework.jdbc.core.SqlParameterValue; 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 80c7a07f2e..73e9b46ff5 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.Before; 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 0b09e04dc3..22498510c7 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.SqlParameter; 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 9779c29d65..0559f34b8c 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.SqlOutParameter; 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 85b6263e47..9d76aeebd4 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.Test; 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 05f289076b..8c5a2024df 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.MapSqlParameterSource; 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 34572961a8..968883fd6a 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.SqlParameterValue; 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 664c2ff24b..6e5779c26a 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 java.sql.Statement; 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 1aefee1e94..45e11b3c25 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 javax.sql.DataSource; 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 feba295516..a243d59ba4 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.LobRetrievalFailureException; 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 8a7cc64546..d0003d4f56 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.mockito.MockitoAnnotations; 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 3d6d4d4d17..4563a2b197 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.TransactionSynchronization; 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 c02dcbf02d..3c29aa3ae8 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.TransactionSynchronization; 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 de22e56058..05295b56dd 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 javax.sql.DataSource; 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 ec33bdeaf1..d4c1be9026 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 221a9e59fb..0a9f8b7df1 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 javax.sql.DataSource; 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 2e5c67d0f2..64f09cc77c 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.EmbeddedDatabase; 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 1ad38f1457..ec2e2b4d0d 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 f325d4891f..e0352b941c 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 javax.sql.DataSource; 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 6f17fc2044..b43b689572 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.core.io.ClassPathResource; 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 4a5c787382..c7260f2bd3 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.core.io.ClassPathResource; 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 10a2248c37..3dc5c36d89 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.dao.InvalidDataAccessApiUsageException; 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 c57e430f67..718f085b29 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.core.SqlParameter; 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 6d2ce8106f..d31f743157 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.SQLExceptionTranslator; 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 6d23a8e828..b1e021d2e3 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.MySQLMaxValueIncrementer; 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 14e4d5bf68..1426ade104 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.DefaultLobHandler; 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 f99ae954dd..d70991e608 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.junit.Test; 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 e118d922ff..944b77c5dc 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.junit.Test; 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 0594fec1cb..27e1d96fb7 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.Before; 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 a8c89b525e..fd7dbf8939 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.jms.listener.endpoint.JmsMessageEndpointManager; 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 cd53ab37a3..77353d24da 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.TransactionCallbackWithoutResult; 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 a1a40d51e4..3f323ec8b1 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 javax.jms.TopicSession; 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 cbf03b7aba..6b9e83581e 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.converter.SimpleMessageConverter; 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 1ac040f3f8..9372201080 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.jndi.JndiTemplate; 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 15eefc873f..570a7abc87 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 javax.jms.ConnectionFactory; 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 8dad2a08e0..2dda59ceb1 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.core.task.TaskExecutor; 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 0781e2916d..1d633b4e5f 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.invocation.InvocationOnMock; 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 c673f51a44..3fa9fe313a 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.mockito.stubbing.Answer; 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 ea98f90206..1a78ba5f79 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.jca.StubResourceAdapter; 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 9cdbf34136..4913da3e90 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.jms.support.converter.SimpleMessageConverter; 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 8ca5ad2e1f..153cf0dd7a 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.invocation.InvocationOnMock; 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 final class SimpleMessageConverter102Tests { 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 b903ff3686..3ea917f017 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.mockito.stubbing.Answer; 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 d2054d5bf2..bbb59cde21 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.junit.Test; 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 0bce702aaa..190d55cf5e 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.junit.Test; 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 2f6a06199d..65ed03ab2b 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.junit.Test; 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 504e247ee9..aba6c9dee7 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 junit.framework.TestCase; 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 2afd8e6f9c..dd44cf3994 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 548e0334d1..9d54247d86 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 javax.naming.NamingException; 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 498005295e..16a7ed030c 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.beans.factory.BeanFactory; 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 6f5ef6d62d..ff9c053d81 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.TransactionCallbackWithoutResult; 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 fd1ae832b3..07fdf5e6b8 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.dao.InvalidDataAccessResourceUsageException; 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 0b61d59160..91972e57b0 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.FileSystemResource; 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 8aa465e0e8..85aa8db363 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.hibernate.SessionFactory; 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 ab82cbcf63..f8b5d81194 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.tests.transaction.MockJtaTransaction; 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 a51fc633e9..0777c3ae11 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.WebAsyncManager; 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 91a7277e78..802c0a2fa4 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.SqlMapExecutor; 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 948c4e7ec2..0eb1a51243 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.jdbc.support.lob.LobHandler; 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 1967c188d5..0174445df2 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.aopalliance.intercept.MethodInvocation; 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 29c882b2b6..de3c4d05fe 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.PersistenceManager; 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 46003776b0..f5fb828e49 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.SQLException; 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 javax.transaction.UserTransaction; 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 org.springframework.transaction.support.TransactionTemplate; 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 4b16a589ca..8f4c921adf 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 javax.jdo.PersistenceManagerFactory; 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 529bdcabf1..d11d147ab1 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 javax.jdo.PersistenceManagerFactory; 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 2736e3b6da..a3b75526d1 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.WebApplicationContext; 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 cefae3bdf2..353ba458fa 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.After; 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 9102cd8645..f84155ecc6 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.TransactionDefinition; 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 0f21f02ea8..0380650be6 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 4377136663..7edab0c0ce 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.IncorrectResultSizeDataAccessException; 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 959fa0efe9..6e4eabe206 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.Before; 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 64828a4319..697cc6389b 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.junit.Test; 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 a343d21537..f81d97dc2e 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.TransactionSynchronizationAdapter 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 5f20a375d4..7ab71bc860 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.TransactionStatus; 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 de6667f543..bbf407b380 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 javax.persistence.spi.PersistenceUnitInfo; 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 4925258a66..acb86b597a 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 javax.persistence.EntityManagerFactory; 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 8dd05c32b3..1859fd3aca 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.WebAsyncManager; 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 f7a26112fc..9833c7146d 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.tests.mock.jndi.ExpectedLookupTemplate; 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 4a783c7d5d..d185546a80 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.EntityManagerHolder; 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 1ffc536304..8178d70452 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.XMLUnit; 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.w3c.dom.NodeList; 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 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { @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 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { 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 43101e62d0..aa3eca0777 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.sax.SAXResult; 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.Attributes; 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 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests { @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 class Jaxb2MarshallerTests extends AbstractMarshallerTests { 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 class Jaxb2MarshallerTests extends AbstractMarshallerTests { } @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 8b4ce76a80..55a3f8d226 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.stream.XMLStreamReader; 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.jaxb.test.Flights; 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 class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests { 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 class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests { 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 7979e4d5c5..ce49ce166d 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.Arrays; 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.sax.SAXResult; 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 class XStreamMarshallerTests { @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 ad97b300b5..22db7be93a 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 @@ package org.springframework.web.struts; 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.ActionForward; 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 class StrutsSupportTests { } }; - 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 class StrutsSupportTests { proxy.setServlet(null); plugin.destroy(); assertTrue(testAction.getServlet() == null); - - verify(moduleConfig); } @Test @@ -270,9 +268,8 @@ public class StrutsSupportTests { } }; - 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 class StrutsSupportTests { } }; - 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 class StrutsSupportTests { 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 56d4c5b40d..b0488791f9 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 class DefaultMvcResultTests { 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 class DefaultMvcResultTests { @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 @@ public class DefaultMvcResultTests { 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 a254398c4e..61240cb402 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 javax.servlet.ServletResponse; 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 class MockFilterChainTests { @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 class MockFilterChainTests { @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 class MockFilterChainTests { @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 class MockFilterChainTests { 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 2038b8ecc0..9a5b2c1243 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 javax.resource.cci.Record; 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.TransactionCallbackWithoutResult; 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); + 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); - expect(connectionFactory.getConnection()).andReturn(connection); + 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); - 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(); + CciLocalTransactionManager tm = new CciLocalTransactionManager(); tm.setConnectionFactory(connectionFactory); TransactionTemplate tt = new TransactionTemplate(tm); @@ -89,7 +76,10 @@ public class CciLocalTransactionTests { } }); - verify(connectionFactory, connection, localTransaction, interaction, record); + verify(localTransaction).begin(); + verify(interaction).close(); + verify(localTransaction).commit(); + verify(connection).close(); } /** @@ -99,34 +89,20 @@ public class CciLocalTransactionTests { */ @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); + 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); - expect(connectionFactory.getConnection()).andReturn(connection); + 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); - 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(); + CciLocalTransactionManager tm = new CciLocalTransactionManager(); tm.setConnectionFactory(connectionFactory); TransactionTemplate tt = new TransactionTemplate(tm); @@ -144,6 +120,9 @@ public class CciLocalTransactionTests { 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 ddbdc80069..f934ebe797 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.InteractionCallback; 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); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + RecordFactory recordFactory = mock(RecordFactory.class); + MappedRecord mappedRecord = mock(MappedRecord.class); - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - 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); + 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); - expect(connectionFactory.getConnection()).andReturn(connection); + given(connectionFactory.getConnection()).willReturn(connection); + given(connection.createInteraction()).willReturn(interaction); + given(interaction.execute(interactionSpec, inputRecord, outputRecord)).willReturn(true); - expect(connection.createInteraction()).andReturn(interaction); - - 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); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); - Record inputRecord = createMock(Record.class); - final Record outputRecord = createMock(Record.class); + Record inputRecord = mock(Record.class); + final Record outputRecord = mock(Record.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connectionFactory.getRecordFactory()).andThrow( - new NotSupportedException("not supported")); - - 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(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 class CciTemplateTests { }); 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); + 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); - Record inputRecord = createMock(Record.class); - final Record outputRecord = createMock(Record.class); + Record inputRecord = mock(Record.class); + final Record outputRecord = mock(Record.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(connection.createInteraction()).andReturn(interaction); - - expect(creator.createRecord(recordFactory)).andReturn(outputRecord); - - expect(interaction.execute(interactionSpec, inputRecord, outputRecord)) - .andReturn(true); - - interaction.close(); - - 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); + 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); - 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); 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); + 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); - 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); - expect(connectionFactory.getConnection()).andReturn(connection); - - 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); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordExtractor extractor = mock(RecordExtractor.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); - expect(connectionFactory.getConnection()).andReturn(connection); - - 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); + 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); - 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); - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); + 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(generator.createRecord(recordFactory)).andReturn(inputRecord); - - expect(connectionFactory.getConnection()).andReturn(connection); - - 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); + 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); - 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); - 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); - - 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); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - expect(connectionFactory.getRecordFactory()).andReturn(recordFactory); - - expect(connectionFactory.getConnection()).andReturn(connection); - - 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); + 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); - 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); - 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); - - expect(extractor.extractData(outputRecord)).andStubReturn(new Object()); - - interaction.close(); - - 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); + 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); - 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); - expect(connectionFactory.getConnection(connectionSpec)).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(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 class CciTemplateTests { 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); + 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 = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(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); + 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); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + ConnectionCallback connectionCallback = mock(ConnectionCallback.class); - expect(connectionFactory.getConnection()).andReturn(connection); - - 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); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + InteractionCallback interactionCallback = mock(InteractionCallback.class); - expect(connectionFactory.getConnection()).andReturn(connection); - - expect(connection.createInteraction()).andReturn(interaction); - - 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); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + Connection connection = mock(Connection.class); + Interaction interaction = mock(Interaction.class); + RecordCreator creator = mock(RecordCreator.class); - Record inputOutputRecord = createMock(Record.class); + Record inputOutputRecord = mock(Record.class); - InteractionSpec interactionSpec = createMock(InteractionSpec.class); + InteractionSpec interactionSpec = mock(InteractionSpec.class); - 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, 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); + 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); - 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(); - - 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); + 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); - 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(); - - 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 4e5a3281d4..e5e2f8a617 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.core.RecordCreator; 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 class EisOperationTests { 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 class EisOperationTests { 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 c19efddd55..617f47f241 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 final class LocalConnectionFactoryBeanTests { @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 04e937b7ec..510b1ccf47 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.TransactionManager; 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.TransactionCallbackWithoutResult; 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 class JndiJtaTransactionManagerTests extends TestCase { 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 @@ public class JndiJtaTransactionManagerTests extends TestCase { 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); JtaTransactionManager ptm = new JtaTransactionManager(); ptm.setUserTransactionName("jndi-ut"); @@ -168,33 +148,16 @@ public class JndiJtaTransactionManagerTests extends TestCase { 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); - 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 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 @@ public class JndiJtaTransactionManagerTests extends TestCase { 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 c13ea6bc41..2c5a557905 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.TransactionManager; 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.TransactionSynchronizationAdapter 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 @@ import org.springframework.transaction.support.TransactionTemplate; 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); - 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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -92,34 +74,19 @@ public class JtaTransactionManagerTests extends TestCase { 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); - 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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -135,22 +102,18 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); - 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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -324,26 +239,16 @@ public class JtaTransactionManagerTests extends TestCase { }); 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); - 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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -364,28 +269,17 @@ public class JtaTransactionManagerTests extends TestCase { } 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); - 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(); + 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 @@ public class JtaTransactionManagerTests extends TestCase { } 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); - 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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); ptm.setGlobalRollbackOnParticipationFailure(false); @@ -440,24 +324,15 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { } 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); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(tx); - utControl.replay(); - tmControl.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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut, tm); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -524,27 +384,16 @@ public class JtaTransactionManagerTests extends TestCase { 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); - 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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -560,18 +409,14 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); - 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(); + final TransactionSynchronization synch = mock(TransactionSynchronization.class); JtaTransactionManager ptm = newJtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -622,24 +456,16 @@ public class JtaTransactionManagerTests extends TestCase { }); 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(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); - 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); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -655,16 +481,13 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { } }); 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 @@ public class JtaTransactionManagerTests extends TestCase { } }); 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { // 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 @@ public class JtaTransactionManagerTests extends TestCase { // 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 @@ public class JtaTransactionManagerTests extends TestCase { }); 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 @@ public class JtaTransactionManagerTests extends TestCase { // 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 @@ public class JtaTransactionManagerTests extends TestCase { 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 @@ public class JtaTransactionManagerTests extends TestCase { 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 @@ public class JtaTransactionManagerTests extends TestCase { } }); - 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 @@ public class JtaTransactionManagerTests extends TestCase { 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 @@ public class JtaTransactionManagerTests extends TestCase { 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 @@ public class JtaTransactionManagerTests extends TestCase { 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 class JtaTransactionManagerTests extends TestCase { // expected } - utControl.verify(); + verify(ut).begin(); } public void testJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnly() throws Exception { @@ -1226,22 +921,10 @@ public class JtaTransactionManagerTests extends TestCase { } 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 class JtaTransactionManagerTests extends TestCase { } } - 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 class JtaTransactionManagerTests extends TestCase { 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 class JtaTransactionManagerTests extends TestCase { 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 class JtaTransactionManagerTests extends TestCase { // 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 class JtaTransactionManagerTests extends TestCase { // 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 @@ public class JtaTransactionManagerTests extends TestCase { 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 class JtaTransactionManagerTests extends TestCase { 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 class JtaTransactionManagerTests extends TestCase { // 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 class JtaTransactionManagerTests extends TestCase { // 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 class JtaTransactionManagerTests extends TestCase { // 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 0a49a21b63..b097bf382c 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 @@ package org.springframework.transaction.interceptor; 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.TransactionSystemException; 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 abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { itb.getName(); checkTransactionStatus(false); - ptmControl.verify(); + // expect no calls + verifyZeroInteractions(ptm); } /** @@ -99,15 +97,10 @@ public abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { itb.getName(); checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(status); } /** @@ -178,15 +171,10 @@ public abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { itb.setName("myName"); checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm, times(2)).commit(status); } /** @@ -209,16 +197,10 @@ public abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { itb.getName(); checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(status); } public void testEnclosingTransactionWithNonTransactionMethodOnAdvisedInside() throws Throwable { @@ -237,15 +219,10 @@ public abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(status); } public void testEnclosingTransactionWithNestedTransactionOnAdvisedInside() throws Throwable { @@ -291,24 +268,13 @@ public abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { checkTransactionStatus(false); - ptmControl.verify(); + verify(ptm).commit(innerStatus); + verify(ptm).commit(outerStatus); } public void testRollbackOnCheckedException() throws Throwable { @@ -401,29 +368,21 @@ public abstract class AbstractTransactionAspectTests extends TestCase { 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); + if (shouldRollback) { + willThrow(tex).given(ptm).rollback(status); + } + else { + willThrow(tex).given(ptm).commit(status); + } } - else { - ptmControl.setVoidCallable(1); - } - ptmControl.replay(); TestBean tb = new TestBean(); ITestBean itb = (ITestBean) advised(tb, ptm, tas); @@ -441,7 +400,14 @@ public abstract class AbstractTransactionAspectTests extends TestCase { } } - ptmControl.verify(); + if (!rollbackException) { + if (shouldRollback) { + verify(ptm).rollback(status); + } + else { + verify(ptm).commit(status); + } + } } /** @@ -454,15 +420,10 @@ public abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { // 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 abstract class AbstractTransactionAspectTests extends TestCase { 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 abstract class AbstractTransactionAspectTests extends TestCase { catch (CannotCreateTransactionException thrown) { assertTrue(thrown == ex); } - ptmControl.verify(); } /** @@ -542,16 +491,12 @@ public abstract class AbstractTransactionAspectTests extends TestCase { // 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 abstract class AbstractTransactionAspectTests extends TestCase { // 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 1dda314dda..268cee7bb7 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 junit.framework.TestCase; 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 class BeanFactoryTransactionTests extends TestCase { 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 class BeanFactoryTransactionTests extends TestCase { 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 5630bd8219..802b7fd028 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.RollbackException; 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.DefaultTransactionDefinition; 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 class WebSphereUowTransactionManagerTests extends TestCase { } 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 class WebSphereUowTransactionManagerTests extends TestCase { 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 ff819d3ede..c0c567c1d3 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.tests.mock.jndi.SimpleNamingContextBuilder; 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 9939aaf034..cb08fa91a1 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 0ea0462a50..1c11bb0a19 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.InputStream; 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.RequestContext; 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.LinkedMultiValueMap; 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 7fd414b627..75de8e4019 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 @@ package org.springframework.http.converter.xml; 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 class MarshallingHttpMessageConverterTests { 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 class MarshallingHttpMessageConverterTests { 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 975d9537a3..d5606f9f3a 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.MalformedURLException; 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.ServiceFactory; 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { assertEquals("myName", RemoteBean.name); assertEquals(1, serviceFactory.serviceCount); - MockServiceFactory.service1Control.verify(); } public void testJaxRpcPortProxyFactoryBeanWithPortInterfaceAndRemoteExceptionAndRefresh() throws Exception { @@ -470,30 +457,25 @@ public class JaxRpcSupportTests extends TestCase { 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 class JaxRpcSupportTests extends TestCase { @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 class JaxRpcSupportTests extends TestCase { @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 class JaxRpcSupportTests extends TestCase { @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 7149dece12..55457d5982 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 java.io.IOException; 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 class DefaultResponseErrorHandlerTests { 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 class DefaultResponseErrorHandlerTests { catch (HttpClientErrorException e) { assertSame(headers, e.getResponseHeaders()); } - - verify(response); } @Test(expected = HttpClientErrorException.class) @@ -96,16 +82,12 @@ public class DefaultResponseErrorHandlerTests { 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 class DefaultResponseErrorHandlerTests { 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 class DefaultResponseErrorHandlerTests { 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 f9c587248e..1ce003da4b 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.client.ClientHttpResponse; 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 class HttpMessageConverterExtractorTests { 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 faca295254..fcfc340770 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.List; 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.client.ClientHttpResponse; 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 class RestTemplateTests { @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 class RestTemplateTests { 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 class RestTemplateTests { 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 class RestTemplateTests { 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 class RestTemplateTests { 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 class RestTemplateTests { 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 class RestTemplateTests { 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(); + 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()); - replayMocks(); 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(); + 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()); - replayMocks(); 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 class RestTemplateTests { 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 class RestTemplateTests { 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 class RestTemplateTests { 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 dc6ea05410..2e5688857f 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 class ServletRequestAttributesTests { @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 class ServletRequestAttributesTests { @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 2590481d3d..dbdf0a5a2b 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 class DeferredResultTests { 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 class DeferredResultTests { assertTrue(result.isSetOrExpired()); - verify(handler); + verify(handler).handleResult("hello"); } @Test @@ -102,9 +91,7 @@ public class DeferredResultTests { 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 class DeferredResultTests { 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 cbd7dfeee2..d378bd8edc 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 class StandardServletAsyncWebRequestTests { @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 506201f5ba..f9ec9666ec 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { @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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { 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 class WebAsyncManagerTests { } 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 936be8d79a..adccdb11eb 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.MockHttpServletRequest; 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 class WebAsyncManagerTimeoutTests { 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 141d68cfae..6091fa6a80 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 junit.framework.TestCase; 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); + given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); + given(request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX)).willReturn(null); - HttpServletResponse response = createMock(HttpServletResponse.class); - response.setCharacterEncoding(ENCODING); - replay(response); - - 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 class CharacterEncodingFilterTests extends TestCase { 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 class CharacterEncodingFilterTests extends TestCase { 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 class CharacterEncodingFilterTests extends TestCase { 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 42c13d2671..297f103e87 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 java.lang.reflect.Method; 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.bind.support.WebRequestDataBinder; 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 @@ public class ModelAttributeMethodProcessorTests { 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 class ModelAttributeMethodProcessorTests { 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 class ModelAttributeMethodProcessorTests { 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 class ModelAttributeMethodProcessorTests { 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 34ca840ce9..bfa4e49d1e 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.HandlerMethodArgumentResolverCompo 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 class ModelFactoryTests { 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 class ModelFactoryTests { 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 class ModelFactoryTests { 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 3cd926d20c..4738e030e8 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.NativeWebRequest; 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 class WebArgumentResolverAdapterTests { @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 @@ public class WebArgumentResolverAdapterTests { } } -} \ 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 169f2477e0..df10bd0d09 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 @@ package org.springframework.web.multipart.support; 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 final class ByteArrayMultipartFileEditorTests extends TestCase { 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 e44f914575..ee739b9831 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.MockPortletRequest; 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 class PortletRequestAttributesTests { @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 class PortletRequestAttributesTests { @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 8fd99d5357..f7192f7acc 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.io.FileNotFoundException; 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 final class PortletUtilsTests { 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 final class PortletUtilsTests { @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 final class PortletUtilsTests { 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 final class PortletUtilsTests { 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 896fef8618..a3c14a0193 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 class TilesViewResolverTests { 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 class TilesViewResolverTests { @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 91bfef1bc6..4ebf4dab30 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.mock.web.test.MockServletContext; 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 class TilesViewTests { response = new MockHttpServletResponse(); - renderer = createMock(Renderer.class); + renderer = mock(Renderer.class); view = new TilesView(); view.setServletContext(servletContext); @@ -80,16 +75,9 @@ public class TilesViewTests { 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 667fb643b4..d5ed530e58 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 org.springframework.web.util.WebUtils; 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 dca233e914..a4f9572dc1 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 class HandlerExecutionChainTests { 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 class HandlerExecutionChainTests { 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 class HandlerExecutionChainTests { } 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 7153c901f9..392cb9b979 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.ExceptionHandlerExc 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 class DelegatingWebMvcConfigurationTests { @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 208225c433..b7628eb630 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.HttpServletRequest; 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.context.support.StaticWebApplicationContext; 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 class ControllerTests extends TestCase { 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(); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + ServletContext context = mock(ServletContext.class); + RequestDispatcher dispatcher = mock(RequestDispatcher.class); - request.getMethod(); - requestControl.setReturnValue("GET", 1); - context.getNamedDispatcher("action"); - contextControl.setReturnValue(dispatcher, 1); + 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 fde7ae7946..42aa80abf3 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.HttpMediaTypeNotSupportedException; 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 class HttpEntityMethodProcessorMockTests { 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 class HttpEntityMethodProcessorMockTests { 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 class HttpEntityMethodProcessorMockTests { 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 class HttpEntityMethodProcessorMockTests { 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 class HttpEntityMethodProcessorMockTests { 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 class HttpEntityMethodProcessorMockTests { 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 class HttpEntityMethodProcessorMockTests { 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 class HttpEntityMethodProcessorMockTests { } -} \ 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 5f9869e1dc..dd5a4570bd 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.MockMultipartFile; 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 class RequestPartMethodArgumentResolverTests { 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 class RequestPartMethodArgumentResolverTests { 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 315040419e..5eb6d49f42 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.context.request.ServletWebRequest; 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 class RequestResponseBodyMethodProcessorMockTests { 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 @@ public class RequestResponseBodyMethodProcessorMockTests { 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 class RequestResponseBodyMethodProcessorMockTests { 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 class RequestResponseBodyMethodProcessorMockTests { 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 class RequestResponseBodyMethodProcessorMockTests { 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 class RequestResponseBodyMethodProcessorMockTests { 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 class RequestResponseBodyMethodProcessorMockTests { 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 class RequestResponseBodyMethodProcessorMockTests { 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 class RequestResponseBodyMethodProcessorMockTests { } } -} \ 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 a114680a94..3f00bf1452 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.mock.web.test.MockPageContext; 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 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests { } 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 3f4247033b..a687e1efc9 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 javax.servlet.jsp.tagext.Tag; 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 class FormTagTests extends AbstractHtmlElementTagTests { 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 class FormTagTests extends AbstractHtmlElementTagTests { 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 289fcbf064..ad0a6cdae6 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.mock.web.test.MockServletContext; 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 @@ import org.springframework.web.servlet.View; 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 class BaseViewTests extends TestCase { 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 class BaseViewTests extends TestCase { 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 class BaseViewTests extends TestCase { 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 class BaseViewTests extends TestCase { 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 class BaseViewTests extends TestCase { 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 0cb6e6f108..fafea1c9d1 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.HandlerMapping; 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 class ContentNegotiatingViewResolverTests { 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 e46aa5449e..3a9531b7d0 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.mock.web.test.MockServletContext; 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 class InternalResourceViewTests extends TestCase { 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 class InternalResourceViewTests extends TestCase { // 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 class InternalResourceViewTests extends TestCase { 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 class InternalResourceViewTests extends TestCase { // 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 class InternalResourceViewTests extends TestCase { 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 class InternalResourceViewTests extends TestCase { // 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 d3c45fb249..c3fd261410 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 javax.servlet.http.HttpServletResponse; 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.RequestDataValueProcessorWrapper; 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 class RedirectViewTests { 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 class RedirectViewTests { 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 class RedirectViewTests { 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 class RedirectViewTests { 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 @@ public class RedirectViewTests { 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 ff233b9be2..0131151f0e 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.io.Writer; 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.AbstractView; 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 class FreeMarkerViewTests { // Check there's a helpful error message assertTrue(ex.getMessage().indexOf("FreeMarkerConfig") != -1); } - - wmc.verify(); } @Test @@ -97,21 +91,15 @@ public class FreeMarkerViewTests { 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 class FreeMarkerViewTests { model.put("myattr", "myvalue"); fv.render(model, request, response); - wmc.verify(); assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, response.getContentType()); } @@ -134,21 +121,15 @@ public class FreeMarkerViewTests { 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 class FreeMarkerViewTests { 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 5350f15999..463fe47d28 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.JRExporterParameter; 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 abstract class AbstractJasperReportsViewTests extends AbstractJasperRepor } 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 d1cd12d8b4..5874985aa3 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.BeanSerializerFactory; 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 class MappingJackson2JsonViewTests { 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 class MappingJackson2JsonViewTests { 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 class MappingJackson2JsonViewTests { 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 da6a9b6418..1e2f9eda5e 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.mock.web.test.MockHttpServletResponse; 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 class MappingJacksonJsonViewTests { 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 class MappingJacksonJsonViewTests { 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 class MappingJacksonJsonViewTests { 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 ac1a396f65..dd0f8749d1 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.i18n.AcceptHeaderLocaleResolver; 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 class VelocityViewTests { // Check there's a helpful error message assertTrue(ex.getMessage().contains("VelocityConfig")); } - - verify(wac); } @Test @@ -131,7 +119,7 @@ public class VelocityViewTests { 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 class VelocityViewTests { 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 @@ public class VelocityViewTests { 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 class VelocityViewTests { 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 @@ public class VelocityViewTests { vv.setApplicationContext(wac); vv.render(new HashMap(), request, expectedResponse); - verify(wac); assertEquals("myContentType", expectedResponse.getContentType()); } @@ -241,11 +216,8 @@ public class VelocityViewTests { 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 class VelocityViewTests { 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 @@ public class VelocityViewTests { 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 d51fc618bf..6b767c7f78 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 @@ package org.springframework.web.servlet.view.xml; 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 class MarshallingViewTests { 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 class MarshallingViewTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - replay(marshallerMock); try { view.render(model, request, response); fail("ServletException expected"); @@ -101,7 +99,6 @@ public class MarshallingViewTests { // expected } assertEquals("Invalid content length", 0, response.getContentLength()); - verify(marshallerMock); } @Test @@ -113,7 +110,6 @@ public class MarshallingViewTests { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); - replay(marshallerMock); try { view.render(model, request, response); fail("ServletException expected"); @@ -122,7 +118,6 @@ public class MarshallingViewTests { // expected } assertEquals("Invalid content length", 0, response.getContentLength()); - verify(marshallerMock); } @Test @@ -136,9 +131,8 @@ public class MarshallingViewTests { 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 class MarshallingViewTests { catch (ServletException ex) { // expected } - verify(marshallerMock); } @Test @@ -159,14 +152,12 @@ public class MarshallingViewTests { 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 class MarshallingViewTests { 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 class MarshallingViewTests { 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 aca10a3fb2..8468024f99 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.PlatformTransactionManager; 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 class ScheduledAndTransactionalAnnotationIntegrationTests { 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 class ScheduledAndTransactionalAnnotationIntegrationTests { @Bean public PersistenceExceptionTranslator peTranslator() { - PersistenceExceptionTranslator txlator = createMock(PersistenceExceptionTranslator.class); - replay(txlator); + PersistenceExceptionTranslator txlator = mock(PersistenceExceptionTranslator.class); return txlator; } } From 7bc5353e07c6a3f6759410e7d3c2acaf82e8ddda Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 6 Mar 2013 11:18:49 -0800 Subject: [PATCH 04/28] Do not sort the mvc:resources location attribute Update ResourcesBeanDefinitionParser to use ensure that location attribute values remain in the order that they are specified. The order was inadvertently changed in commit 3838d159f3 due to the use of StringUtils.commaDelimitedListToSet which sorts items. Issue: SPR-10355 --- .../web/servlet/config/ResourcesBeanDefinitionParser.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java index 97df07e544..6bfdb9c56f 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/ResourcesBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.springframework.web.servlet.config; +import java.util.Arrays; import java.util.Map; import org.w3c.dom.Element; @@ -89,7 +90,7 @@ class ResourcesBeanDefinitionParser implements BeanDefinitionParser { } ManagedList locations = new ManagedList(); - locations.addAll(StringUtils.commaDelimitedListToSet(locationAttr)); + locations.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(locationAttr))); RootBeanDefinition resourceHandlerDef = new RootBeanDefinition(ResourceHttpRequestHandler.class); resourceHandlerDef.setSource(source); From 98074e776262292a9d6fa8d164e6718c5876ed6f Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 11 Jan 2013 01:02:08 +0100 Subject: [PATCH 05/28] Provide support for context hierarchies in the TCF Prior to this commit the Spring TestContext Framework supported creating only flat, non-hierarchical contexts. There was no easy way to create contexts with parent-child relationships. This commit addresses this issue by introducing a new @ContextHierarchy annotation that can be used in conjunction with @ContextConfiguration for declaring hierarchies of application contexts, either within a single test class or within a test class hierarchy. In addition, @DirtiesContext now supports a new 'hierarchyMode' attribute for controlling context cache clearing for context hierarchies. - Introduced a new @ContextHierarchy annotation. - Introduced 'name' attribute in @ContextConfiguration. - Introduced 'name' property in ContextConfigurationAttributes. - TestContext is now aware of @ContextHierarchy in addition to @ContextConfiguration. - Introduced findAnnotationDeclaringClassForTypes() in AnnotationUtils. - Introduced resolveContextHierarchyAttributes() in ContextLoaderUtils. - Introduced buildContextHierarchyMap() in ContextLoaderUtils. - @ContextConfiguration and @ContextHierarchy may not be used as top-level, class-level annotations simultaneously. - Introduced reference to the parent configuration in MergedContextConfiguration and WebMergedContextConfiguration. - Introduced overloaded buildMergedContextConfiguration() methods in ContextLoaderUtils in order to handle context hierarchies separately from conventional, non-hierarchical contexts. - Introduced hashCode() and equals() in ContextConfigurationAttributes. - ContextLoaderUtils ensures uniqueness of @ContextConfiguration elements within a single @ContextHierarchy declaration. - Introduced CacheAwareContextLoaderDelegate that can be used for loading contexts with transparent support for interacting with the context cache -- for example, for retrieving the parent application context in a context hierarchy. - TestContext now delegates to CacheAwareContextLoaderDelegate for loading contexts. - Introduced getParentApplicationContext() in MergedContextConfiguration - The loadContext(MergedContextConfiguration) methods in AbstractGenericContextLoader and AbstractGenericWebContextLoader now set the parent context as appropriate. - Introduced 'hierarchyMode' attribute in @DirtiesContext with a corresponding HierarchyMode enum that defines EXHAUSTIVE and CURRENT_LEVEL cache removal modes. - ContextCache now internally tracks the relationships between contexts that make up a context hierarchy. Furthermore, when a context is removed, if it is part of a context hierarchy all corresponding contexts will be removed from the cache according to the supplied HierarchyMode. - AbstractGenericWebContextLoader will set a loaded context as the ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE in the MockServletContext when context hierarchies are used if the context has no parent or if the context has a parent that is not a WAC. - Where appropriate, updated Javadoc to refer to the ServletTestExecutionListener, which was introduced in 3.2.0. - Updated Javadoc to avoid and/or suppress warnings in spring-test. - Suppressed remaining warnings in code in spring-test. Issue: SPR-5613, SPR-9863 --- .../core/annotation/AnnotationUtils.java | 63 ++- .../core/annotation/AnnotationUtilsTests.java | 131 +++++- spring-test/.springBeans | 1 + .../mock/jndi/SimpleNamingContextBuilder.java | 7 +- .../mock/web/MockServletContext.java | 2 + ...DependencyInjectionSpringContextTests.java | 1 + .../test/annotation/DirtiesContext.java | 75 ++- .../CacheAwareContextLoaderDelegate.java | 112 +++++ .../test/context/ContextCache.java | 258 +++++++--- .../test/context/ContextConfiguration.java | 20 +- .../ContextConfigurationAttributes.java | 138 +++++- .../test/context/ContextHierarchy.java | 54 +++ .../test/context/ContextLoaderUtils.java | 440 +++++++++++++----- .../context/MergedContextConfiguration.java | 101 +++- .../test/context/SmartContextLoader.java | 12 +- .../test/context/TestContext.java | 128 ++--- .../test/context/TestContextManager.java | 9 +- .../test/context/TestExecutionListener.java | 29 +- .../test/context/TestExecutionListeners.java | 31 +- .../support/AbstractGenericContextLoader.java | 16 +- .../DirtiesContextTestExecutionListener.java | 55 ++- .../web/AbstractGenericWebContextLoader.java | 61 ++- .../web/ServletTestExecutionListener.java | 2 + .../web/WebMergedContextConfiguration.java | 58 ++- .../test/context/ContextCacheTests.java | 329 +++++++++++++ .../ContextHierarchyDirtiesContextTests.java | 212 +++++++++ .../test/context/ContextLoaderUtilsTests.java | 398 +++++++++++++++- .../MergedContextConfigurationTests.java | 104 ++++- .../SpringRunnerContextCacheTests.java | 2 +- .../context/TestContextCacheKeyTests.java | 102 ---- ...ierarchyWithMergedConfigLevelOneTests.java | 96 ++++ ...ierarchyWithMergedConfigLevelTwoTests.java | 62 +++ ...rchyWithOverriddenConfigLevelTwoTests.java | 73 +++ ...rtiesContextWithContextHierarchyTests.java | 149 ++++++ ...sWithSingleLevelContextHierarchyTests.java | 63 +++ ...textHierarchyAndMixedConfigTypesTests.java | 79 ++++ ...lassWithTwoLevelContextHierarchyTests.java | 93 ++++ ...reContextConfigurationInSubclassTests.java | 72 +++ ...ContextConfigurationInSuperclassTests.java | 71 +++ ...eWithSingleLevelContextHierarchyTests.java | 72 +++ ...reContextConfigurationInSubclassTests.java | 78 ++++ ...ContextConfigurationInSuperclassTests.java | 79 ++++ ...textHierarchyAndMixedConfigTypesTests.java | 62 +++ ...oWithSingleLevelContextHierarchyTests.java | 78 ++++ .../web/ControllerIntegrationTests.java | 102 ++++ .../web/DispatcherWacRootWacEarTests.java | 88 ++++ .../context/hierarchies/web/EarTests.java | 65 +++ .../hierarchies/web/RootWacEarTests.java | 76 +++ ...sedSpringJUnit4ClassRunnerAppCtxTests.java | 26 +- .../context/junit4/spr8849/Spr8849Tests.java | 1 + ...TransactionalTestNGSpringContextTests.java | 7 +- ...hyAndMixedConfigTypesTests-ChildConfig.xml | 9 + ...rarchyAndMixedConfigTypesTests-context.xml | 9 + .../DispatcherWacRootWacEarTests-context.xml | 7 + src/dist/changelog.txt | 2 + 55 files changed, 3919 insertions(+), 551 deletions(-) create mode 100644 spring-test/src/main/java/org/springframework/test/context/CacheAwareContextLoaderDelegate.java create mode 100644 spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/ContextCacheTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java delete mode 100644 spring-test/src/test/java/org/springframework/test/context/TestContextCacheKeyTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java create mode 100644 spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java create mode 100644 spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests-ChildConfig.xml create mode 100644 spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests-context.xml create mode 100644 spring-test/src/test/resources/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests-context.xml diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java index a1701c9db1..e177856e82 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java @@ -20,6 +20,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; +import java.util.List; import java.util.Map; import java.util.WeakHashMap; @@ -240,14 +241,58 @@ public abstract class AnnotationUtils { * if not found * @see Class#isAnnotationPresent(Class) * @see Class#getDeclaredAnnotations() + * @see #findAnnotationDeclaringClassForTypes(List, Class) + * @see #isAnnotationDeclaredLocally(Class, Class) */ public static Class findAnnotationDeclaringClass(Class annotationType, Class clazz) { Assert.notNull(annotationType, "Annotation type must not be null"); if (clazz == null || clazz.equals(Object.class)) { return null; } - return (isAnnotationDeclaredLocally(annotationType, clazz)) ? clazz : - findAnnotationDeclaringClass(annotationType, clazz.getSuperclass()); + return (isAnnotationDeclaredLocally(annotationType, clazz)) ? clazz : findAnnotationDeclaringClass( + annotationType, clazz.getSuperclass()); + } + + /** + * Find the first {@link Class} in the inheritance hierarchy of the specified + * {@code clazz} (including the specified {@code clazz} itself) which declares + * at least one of the specified {@code annotationTypes}, or {@code null} if + * none of the specified annotation types could be found. + *

If the supplied {@code clazz} is {@code null}, {@code null} will be + * returned. + *

If the supplied {@code clazz} is an interface, only the interface itself + * will be checked; the inheritance hierarchy for interfaces will not be traversed. + *

The standard {@link Class} API does not provide a mechanism for determining + * which class in an inheritance hierarchy actually declares one of several + * candidate {@linkplain Annotation annotations}, so we need to handle this + * explicitly. + * @param annotationTypes the list of Class objects corresponding to the + * annotation types + * @param clazz the Class object corresponding to the class on which to check + * for the annotations, or {@code null} + * @return the first {@link Class} in the inheritance hierarchy of the specified + * {@code clazz} which declares an annotation of at least one of the specified + * {@code annotationTypes}, or {@code null} if not found + * @see Class#isAnnotationPresent(Class) + * @see Class#getDeclaredAnnotations() + * @see #findAnnotationDeclaringClass(Class, Class) + * @see #isAnnotationDeclaredLocally(Class, Class) + * @since 3.2.2 + */ + public static Class findAnnotationDeclaringClassForTypes(List> annotationTypes, + Class clazz) { + Assert.notEmpty(annotationTypes, "The list of annotation types must not be empty"); + if (clazz == null || clazz.equals(Object.class)) { + return null; + } + + for (Class annotationType : annotationTypes) { + if (isAnnotationDeclaredLocally(annotationType, clazz)) { + return clazz; + } + } + + return findAnnotationDeclaringClassForTypes(annotationTypes, clazz.getSuperclass()); } /** @@ -348,8 +393,8 @@ public abstract class AnnotationUtils { * and corresponding attribute values as values * @since 3.1.1 */ - public static AnnotationAttributes getAnnotationAttributes( - Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { + public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean classValuesAsString, + boolean nestedAnnotationsAsMap) { AnnotationAttributes attrs = new AnnotationAttributes(); Method[] methods = annotation.annotationType().getDeclaredMethods(); @@ -371,15 +416,15 @@ public abstract class AnnotationUtils { } } if (nestedAnnotationsAsMap && value instanceof Annotation) { - attrs.put(method.getName(), getAnnotationAttributes( - (Annotation)value, classValuesAsString, nestedAnnotationsAsMap)); + attrs.put(method.getName(), + getAnnotationAttributes((Annotation) value, classValuesAsString, nestedAnnotationsAsMap)); } else if (nestedAnnotationsAsMap && value instanceof Annotation[]) { - Annotation[] realAnnotations = (Annotation[])value; + Annotation[] realAnnotations = (Annotation[]) value; AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[realAnnotations.length]; for (int i = 0; i < realAnnotations.length; i++) { - mappedAnnotations[i] = getAnnotationAttributes( - realAnnotations[i], classValuesAsString, nestedAnnotationsAsMap); + mappedAnnotations[i] = getAnnotationAttributes(realAnnotations[i], classValuesAsString, + nestedAnnotationsAsMap); } attrs.put(method.getName(), mappedAnnotations); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java index 0c5d88f334..9f7e76b0c9 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,26 @@ package org.springframework.core.annotation; +import static org.junit.Assert.*; +import static org.springframework.core.annotation.AnnotationUtils.*; + +import java.lang.annotation.Annotation; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.List; + import org.junit.Test; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; -import static org.junit.Assert.*; - -import static org.springframework.core.annotation.AnnotationUtils.*; - /** + * Unit tests for {@link AnnotationUtils}. + * * @author Rod Johnson * @author Juergen Hoeller * @author Sam Brannen @@ -102,23 +107,91 @@ public class AnnotationUtilsTests { assertNull(findAnnotationDeclaringClass(Transactional.class, NonAnnotatedClass.class)); // inherited class-level annotation; note: @Transactional is inherited - assertEquals(InheritedAnnotationInterface.class, findAnnotationDeclaringClass(Transactional.class, - InheritedAnnotationInterface.class)); + assertEquals(InheritedAnnotationInterface.class, + findAnnotationDeclaringClass(Transactional.class, InheritedAnnotationInterface.class)); assertNull(findAnnotationDeclaringClass(Transactional.class, SubInheritedAnnotationInterface.class)); - assertEquals(InheritedAnnotationClass.class, findAnnotationDeclaringClass(Transactional.class, - InheritedAnnotationClass.class)); - assertEquals(InheritedAnnotationClass.class, findAnnotationDeclaringClass(Transactional.class, - SubInheritedAnnotationClass.class)); + assertEquals(InheritedAnnotationClass.class, + findAnnotationDeclaringClass(Transactional.class, InheritedAnnotationClass.class)); + assertEquals(InheritedAnnotationClass.class, + findAnnotationDeclaringClass(Transactional.class, SubInheritedAnnotationClass.class)); // non-inherited class-level annotation; note: @Order is not inherited, - // but findAnnotationDeclaringClass() should still find it. - assertEquals(NonInheritedAnnotationInterface.class, findAnnotationDeclaringClass(Order.class, - NonInheritedAnnotationInterface.class)); + // but findAnnotationDeclaringClass() should still find it on classes. + assertEquals(NonInheritedAnnotationInterface.class, + findAnnotationDeclaringClass(Order.class, NonInheritedAnnotationInterface.class)); assertNull(findAnnotationDeclaringClass(Order.class, SubNonInheritedAnnotationInterface.class)); - assertEquals(NonInheritedAnnotationClass.class, findAnnotationDeclaringClass(Order.class, - NonInheritedAnnotationClass.class)); - assertEquals(NonInheritedAnnotationClass.class, findAnnotationDeclaringClass(Order.class, - SubNonInheritedAnnotationClass.class)); + assertEquals(NonInheritedAnnotationClass.class, + findAnnotationDeclaringClass(Order.class, NonInheritedAnnotationClass.class)); + assertEquals(NonInheritedAnnotationClass.class, + findAnnotationDeclaringClass(Order.class, SubNonInheritedAnnotationClass.class)); + } + + @Test + public void findAnnotationDeclaringClassForTypesWithSingleCandidateType() { + + // no class-level annotation + List> transactionalCandidateList = Arrays.> asList(Transactional.class); + assertNull(findAnnotationDeclaringClassForTypes(transactionalCandidateList, NonAnnotatedInterface.class)); + assertNull(findAnnotationDeclaringClassForTypes(transactionalCandidateList, NonAnnotatedClass.class)); + + // inherited class-level annotation; note: @Transactional is inherited + assertEquals(InheritedAnnotationInterface.class, + findAnnotationDeclaringClassForTypes(transactionalCandidateList, InheritedAnnotationInterface.class)); + assertNull(findAnnotationDeclaringClassForTypes(transactionalCandidateList, + SubInheritedAnnotationInterface.class)); + assertEquals(InheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(transactionalCandidateList, InheritedAnnotationClass.class)); + assertEquals(InheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(transactionalCandidateList, SubInheritedAnnotationClass.class)); + + // non-inherited class-level annotation; note: @Order is not inherited, + // but findAnnotationDeclaringClassForTypes() should still find it on classes. + List> orderCandidateList = Arrays.> asList(Order.class); + assertEquals(NonInheritedAnnotationInterface.class, + findAnnotationDeclaringClassForTypes(orderCandidateList, NonInheritedAnnotationInterface.class)); + assertNull(findAnnotationDeclaringClassForTypes(orderCandidateList, SubNonInheritedAnnotationInterface.class)); + assertEquals(NonInheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(orderCandidateList, NonInheritedAnnotationClass.class)); + assertEquals(NonInheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(orderCandidateList, SubNonInheritedAnnotationClass.class)); + } + + @Test + public void findAnnotationDeclaringClassForTypesWithMultipleCandidateTypes() { + + List> candidates = Arrays.> asList(Transactional.class, + Order.class); + + // no class-level annotation + assertNull(findAnnotationDeclaringClassForTypes(candidates, NonAnnotatedInterface.class)); + assertNull(findAnnotationDeclaringClassForTypes(candidates, NonAnnotatedClass.class)); + + // inherited class-level annotation; note: @Transactional is inherited + assertEquals(InheritedAnnotationInterface.class, + findAnnotationDeclaringClassForTypes(candidates, InheritedAnnotationInterface.class)); + assertNull(findAnnotationDeclaringClassForTypes(candidates, SubInheritedAnnotationInterface.class)); + assertEquals(InheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(candidates, InheritedAnnotationClass.class)); + assertEquals(InheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(candidates, SubInheritedAnnotationClass.class)); + + // non-inherited class-level annotation; note: @Order is not inherited, + // but findAnnotationDeclaringClassForTypes() should still find it on classes. + assertEquals(NonInheritedAnnotationInterface.class, + findAnnotationDeclaringClassForTypes(candidates, NonInheritedAnnotationInterface.class)); + assertNull(findAnnotationDeclaringClassForTypes(candidates, SubNonInheritedAnnotationInterface.class)); + assertEquals(NonInheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(candidates, NonInheritedAnnotationClass.class)); + assertEquals(NonInheritedAnnotationClass.class, + findAnnotationDeclaringClassForTypes(candidates, SubNonInheritedAnnotationClass.class)); + + // class hierarchy mixed with @Transactional and @Order declarations + assertEquals(TransactionalClass.class, + findAnnotationDeclaringClassForTypes(candidates, TransactionalClass.class)); + assertEquals(TransactionalAndOrderedClass.class, + findAnnotationDeclaringClassForTypes(candidates, TransactionalAndOrderedClass.class)); + assertEquals(TransactionalAndOrderedClass.class, + findAnnotationDeclaringClassForTypes(candidates, SubTransactionalAndOrderedClass.class)); } @Test @@ -216,18 +289,18 @@ public class AnnotationUtilsTests { } - @Component(value="meta1") + @Component(value = "meta1") @Retention(RetentionPolicy.RUNTIME) @interface Meta1 { } - @Component(value="meta2") + @Component(value = "meta2") @Retention(RetentionPolicy.RUNTIME) @interface Meta2 { } @Meta1 - @Component(value="local") + @Component(value = "local") @Meta2 static class HasLocalAndMetaComponentAnnotation { } @@ -332,6 +405,16 @@ public class AnnotationUtilsTests { public static class SubNonInheritedAnnotationClass extends NonInheritedAnnotationClass { } + @Transactional + public static class TransactionalClass { + } + + @Order + public static class TransactionalAndOrderedClass { + } + + public static class SubTransactionalAndOrderedClass extends TransactionalAndOrderedClass { + } public static interface InterfaceWithAnnotatedMethod { @@ -353,10 +436,12 @@ public class AnnotationUtilsTests { } } - public abstract static class AbstractDoesNotImplementInterfaceWithAnnotatedMethod implements InterfaceWithAnnotatedMethod { + public abstract static class AbstractDoesNotImplementInterfaceWithAnnotatedMethod implements + InterfaceWithAnnotatedMethod { } - public static class SubOfAbstractImplementsInterfaceWithAnnotatedMethod extends AbstractDoesNotImplementInterfaceWithAnnotatedMethod { + public static class SubOfAbstractImplementsInterfaceWithAnnotatedMethod extends + AbstractDoesNotImplementInterfaceWithAnnotatedMethod { @Override public void foo() { diff --git a/spring-test/.springBeans b/spring-test/.springBeans index 656622651c..aa53e0e658 100644 --- a/spring-test/.springBeans +++ b/spring-test/.springBeans @@ -10,6 +10,7 @@ src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests-context.xml src/test/java/org/springframework/test/context/junit4/aci/xml/MultipleInitializersXmlConfigTests-context.xml src/test/resources/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests-context.xml + src/test/resources/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests-context.xml diff --git a/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java b/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java index 449c45faca..5d2f70d519 100644 --- a/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java +++ b/spring-test/src/main/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java @@ -40,9 +40,9 @@ import org.springframework.util.ClassUtils; * *

There are various choices for DataSource implementations: *

    - *
  • SingleConnectionDataSource (using the same Connection for all getConnection calls); - *
  • DriverManagerDataSource (creating a new Connection on each getConnection call); - *
  • Apache's Jakarta Commons DBCP offers BasicDataSource (a real pool). + *
  • {@code SingleConnectionDataSource} (using the same Connection for all getConnection calls) + *
  • {@code DriverManagerDataSource} (creating a new Connection on each getConnection call) + *
  • Apache's Jakarta Commons DBCP offers {@code org.apache.commons.dbcp.BasicDataSource} (a real pool) *
* *

Typical usage in bootstrap code: @@ -77,7 +77,6 @@ import org.springframework.util.ClassUtils; * @see SimpleNamingContext * @see org.springframework.jdbc.datasource.SingleConnectionDataSource * @see org.springframework.jdbc.datasource.DriverManagerDataSource - * @see org.apache.commons.dbcp.BasicDataSource */ public class SimpleNamingContextBuilder implements InitialContextFactoryBuilder { diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java b/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java index 40fbabd1a1..76b65c3904 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java @@ -163,6 +163,7 @@ public class MockServletContext implements ServletContext { * @param resourceLoader the ResourceLoader to use (or null for the default) * @see #registerNamedDispatcher */ + @SuppressWarnings("javadoc") public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) { this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : ""); @@ -344,6 +345,7 @@ public class MockServletContext implements ServletContext { *

Defaults to {@linkplain #COMMON_DEFAULT_SERVLET_NAME "default"}. * @see #setDefaultServletName */ + @SuppressWarnings("javadoc") public String getDefaultServletName() { return this.defaultServletName; } diff --git a/spring-test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java b/spring-test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java index 0ef706abe1..6229a8d384 100644 --- a/spring-test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java +++ b/spring-test/src/main/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java @@ -197,6 +197,7 @@ public abstract class AbstractDependencyInjectionSpringContextTests extends Abst * test instance has not been configured * @see #populateProtectedVariables() */ + @SuppressWarnings("javadoc") protected void injectDependencies() throws Exception { Assert.state(getApplicationContext() != null, "injectDependencies() called without first configuring an ApplicationContext"); diff --git a/spring-test/src/main/java/org/springframework/test/annotation/DirtiesContext.java b/spring-test/src/main/java/org/springframework/test/annotation/DirtiesContext.java index 53a9b877e6..aa6ed21137 100644 --- a/spring-test/src/main/java/org/springframework/test/annotation/DirtiesContext.java +++ b/spring-test/src/main/java/org/springframework/test/annotation/DirtiesContext.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. @@ -36,13 +36,13 @@ import java.lang.annotation.Target; * mode set to {@link ClassMode#AFTER_CLASS AFTER_CLASS} * *

- * Use this annotation if a test has modified the context (for example, by - * replacing a bean definition). Subsequent tests will be supplied a new - * context. + * Use this annotation if a test has modified the context — for example, by + * replacing a bean definition or changing the state of a singleton bean. + * Subsequent tests will be supplied a new context. *

*

- * {@code @DirtiesContext} may be used as a class-level and - * method-level annotation within the same class. In such scenarios, the + * {@code @DirtiesContext} may be used as a class-level and method-level + * annotation within the same class. In such scenarios, the * {@code ApplicationContext} will be marked as dirty after any * such annotated method as well as after the entire class. If the * {@link ClassMode} is set to {@link ClassMode#AFTER_EACH_TEST_METHOD @@ -53,16 +53,19 @@ import java.lang.annotation.Target; * @author Sam Brannen * @author Rod Johnson * @since 2.0 + * @see org.springframework.test.context.ContextConfiguration */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) public @interface DirtiesContext { /** - * Defines modes which determine how {@code @DirtiesContext} - * is interpreted when used to annotate a test class. + * Defines modes which determine how {@code @DirtiesContext} is + * interpreted when used to annotate a test class. + * + * @since 3.0 */ static enum ClassMode { @@ -76,18 +79,64 @@ public @interface DirtiesContext { * The associated {@code ApplicationContext} will be marked as * dirty after each test method in the class. */ - AFTER_EACH_TEST_METHOD + AFTER_EACH_TEST_METHOD; + } + + /** + * Defines modes which determine how the context cache is cleared + * when {@code @DirtiesContext} is used in a test whose context is + * configured as part of a hierarchy via + * {@link org.springframework.test.context.ContextHierarchy @ContextHierarchy}. + * + * @since 3.2.2 + */ + static enum HierarchyMode { + + /** + * The context cache will be cleared using an exhaustive algorithm + * that includes not only the {@linkplain HierarchyMode#CURRENT_LEVEL current level} + * but also all other context hierarchies that share an ancestor context + * common to the current test. + * + *

All {@code ApplicationContexts} that reside in a subhierarchy of + * the common ancestor context will be removed from the context cache and + * closed. + */ + EXHAUSTIVE, + + /** + * The {@code ApplicationContext} for the current level in the + * context hierarchy and all contexts in subhierarchies of the current + * level will be removed from the context cache and closed. + * + *

The current level refers to the {@code ApplicationContext} + * at the lowest level in the context hierarchy that is visible from the + * current test. + */ + CURRENT_LEVEL; } /** * The mode to use when a test class is annotated with - * {@code @DirtiesContext}. + * {@code @DirtiesContext}. *

Defaults to {@link ClassMode#AFTER_CLASS AFTER_CLASS}. *

Note: Setting the class mode on an annotated test method has no meaning, - * since the mere presence of the {@code @DirtiesContext} - * annotation on a test method is sufficient. + * since the mere presence of the {@code @DirtiesContext} annotation on a + * test method is sufficient. + * + * @since 3.0 */ ClassMode classMode() default ClassMode.AFTER_CLASS; + /** + * The context cache clearing mode to use when a context is + * configured as part of a hierarchy via + * {@link org.springframework.test.context.ContextHierarchy @ContextHierarchy}. + *

Defaults to {@link HierarchyMode#EXHAUSTIVE EXHAUSTIVE}. + * + * @since 3.2.2 + */ + HierarchyMode hierarchyMode() default HierarchyMode.EXHAUSTIVE; + } diff --git a/spring-test/src/main/java/org/springframework/test/context/CacheAwareContextLoaderDelegate.java b/spring-test/src/main/java/org/springframework/test/context/CacheAwareContextLoaderDelegate.java new file mode 100644 index 0000000000..f7375def03 --- /dev/null +++ b/spring-test/src/main/java/org/springframework/test/context/CacheAwareContextLoaderDelegate.java @@ -0,0 +1,112 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.util.Assert; + +/** + * {@code CacheAwareContextLoaderDelegate} loads application contexts from + * {@link MergedContextConfiguration} by delegating to the + * {@link ContextLoader} configured in the {@code MergedContextConfiguration} + * and interacting transparently with the {@link ContextCache} behind the scenes. + * + *

Note: {@code CacheAwareContextLoaderDelegate} does not implement the + * {@link ContextLoader} or {@link SmartContextLoader} interface. + * + * @author Sam Brannen + * @since 3.2.2 + */ +public class CacheAwareContextLoaderDelegate { + + private static final Log logger = LogFactory.getLog(CacheAwareContextLoaderDelegate.class); + + private final ContextCache contextCache; + + + CacheAwareContextLoaderDelegate(ContextCache contextCache) { + Assert.notNull(contextCache, "ContextCache must not be null"); + this.contextCache = contextCache; + } + + /** + * Load the {@code ApplicationContext} for the supplied merged context + * configuration. Supports both the {@link SmartContextLoader} and + * {@link ContextLoader} SPIs. + * @throws Exception if an error occurs while loading the application context + */ + private ApplicationContext loadContextInternal(MergedContextConfiguration mergedContextConfiguration) + throws Exception { + ContextLoader contextLoader = mergedContextConfiguration.getContextLoader(); + Assert.notNull(contextLoader, "Cannot load an ApplicationContext with a NULL 'contextLoader'. " + + "Consider annotating your test class with @ContextConfiguration or @ContextHierarchy."); + + ApplicationContext applicationContext; + + if (contextLoader instanceof SmartContextLoader) { + SmartContextLoader smartContextLoader = (SmartContextLoader) contextLoader; + applicationContext = smartContextLoader.loadContext(mergedContextConfiguration); + } + else { + String[] locations = mergedContextConfiguration.getLocations(); + Assert.notNull(locations, "Cannot load an ApplicationContext with a NULL 'locations' array. " + + "Consider annotating your test class with @ContextConfiguration or @ContextHierarchy."); + applicationContext = contextLoader.loadContext(locations); + } + + return applicationContext; + } + + /** + * Load the {@link ApplicationContext application context} for the supplied + * merged context configuration. + * + *

If the context is present in the cache it will simply be returned; + * otherwise, it will be loaded, stored in the cache, and returned. + * @return the application context + * @throws IllegalStateException if an error occurs while retrieving or + * loading the application context + */ + public ApplicationContext loadContext(MergedContextConfiguration mergedContextConfiguration) { + synchronized (contextCache) { + ApplicationContext context = contextCache.get(mergedContextConfiguration); + if (context == null) { + try { + context = loadContextInternal(mergedContextConfiguration); + if (logger.isDebugEnabled()) { + logger.debug(String.format("Storing ApplicationContext in cache under key [%s].", + mergedContextConfiguration)); + } + contextCache.put(mergedContextConfiguration, context); + } + catch (Exception ex) { + throw new IllegalStateException("Failed to load ApplicationContext", ex); + } + } + else { + if (logger.isDebugEnabled()) { + logger.debug(String.format("Retrieved ApplicationContext from cache with key [%s].", + mergedContextConfiguration)); + } + } + return context; + } + } + +} diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextCache.java b/spring-test/src/main/java/org/springframework/test/context/ContextCache.java index 32851cf5ed..3a5a5b1adb 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextCache.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextCache.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,24 +16,30 @@ package org.springframework.test.context; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.style.ToStringCreator; +import org.springframework.test.annotation.DirtiesContext.HierarchyMode; import org.springframework.util.Assert; /** * Cache for Spring {@link ApplicationContext ApplicationContexts} in a test environment. * - *

Maintains a cache of {@link ApplicationContext contexts} keyed by - * {@link MergedContextConfiguration} instances. This has significant performance - * benefits if initializing the context would take time. While initializing a - * Spring context itself is very quick, some beans in a context, such as a - * {@code LocalSessionFactoryBean} for working with Hibernate, may take some time - * to initialize. Hence it often makes sense to perform that initialization only - * once per test suite. + *

Maintains a cache of {@code ApplicationContexts} keyed by + * {@link MergedContextConfiguration} instances. + * + *

This has significant performance benefits if initializing the context would take time. + * While initializing a Spring context itself is very quick, some beans in a context, such + * as a {@code LocalSessionFactoryBean} for working with Hibernate, may take some time to + * initialize. Hence it often makes sense to perform that initialization only once per + * test suite. * * @author Sam Brannen * @author Juergen Hoeller @@ -41,11 +47,22 @@ import org.springframework.util.Assert; */ class ContextCache { + private final Object monitor = new Object(); + /** - * Map of context keys to Spring ApplicationContext instances. + * Map of context keys to Spring {@code ApplicationContext} instances. */ - private final Map contextMap = - new ConcurrentHashMap(64); + private final Map contextMap = new ConcurrentHashMap( + 64); + + /** + * Map of parent keys to sets of children keys, representing a top-down tree + * of context hierarchies. This information is used for determining which subtrees + * need to be recursively removed and closed when removing a context that is a parent + * of other contexts. + */ + private final Map> hierarchyMap = new ConcurrentHashMap>( + 64); private int hitCount; @@ -53,15 +70,18 @@ class ContextCache { /** - * Clears all contexts from the cache. + * Clears all contexts from the cache and clears context hierarchy information as + * well. */ void clear() { - this.contextMap.clear(); + synchronized (monitor) { + this.contextMap.clear(); + this.hierarchyMap.clear(); + } } /** - * Clears hit and miss count statistics for the cache (i.e., resets counters - * to zero). + * Clears hit and miss count statistics for the cache (i.e., resets counters to zero). */ void clearStatistics() { this.hitCount = 0; @@ -70,124 +90,210 @@ class ContextCache { /** * Return whether there is a cached context for the given key. + * * @param key the context key (never {@code null}) */ boolean contains(MergedContextConfiguration key) { Assert.notNull(key, "Key must not be null"); - return this.contextMap.containsKey(key); + synchronized (monitor) { + return this.contextMap.containsKey(key); + } } /** - * Obtain a cached ApplicationContext for the given key. - *

The {@link #getHitCount() hit} and {@link #getMissCount() miss} - * counts will be updated accordingly. + * Obtain a cached {@code ApplicationContext} for the given key. + * + *

The {@link #getHitCount() hit} and {@link #getMissCount() miss} counts will be + * updated accordingly. + * * @param key the context key (never {@code null}) - * @return the corresponding ApplicationContext instance, - * or {@code null} if not found in the cache. + * @return the corresponding {@code ApplicationContext} instance, or {@code null} if + * not found in the cache. * @see #remove */ ApplicationContext get(MergedContextConfiguration key) { Assert.notNull(key, "Key must not be null"); - ApplicationContext context = this.contextMap.get(key); - if (context == null) { - incrementMissCount(); + synchronized (monitor) { + ApplicationContext context = this.contextMap.get(key); + if (context == null) { + incrementMissCount(); + } + else { + incrementHitCount(); + } + return context; } - else { - incrementHitCount(); - } - return context; } /** - * Increment the hit count by one. A hit is an access to the - * cache, which returned a non-null context for a queried key. + * Increment the hit count by one. A hit is an access to the cache, which + * returned a non-null context for a queried key. */ private void incrementHitCount() { this.hitCount++; } /** - * Increment the miss count by one. A miss is an access to the - * cache, which returned a {@code null} context for a queried key. + * Increment the miss count by one. A miss is an access to the cache, which + * returned a {@code null} context for a queried key. */ private void incrementMissCount() { this.missCount++; } /** - * Get the overall hit count for this cache. A hit is an access - * to the cache, which returned a non-null context for a queried key. + * Get the overall hit count for this cache. A hit is an access to the cache, + * which returned a non-null context for a queried key. */ int getHitCount() { return this.hitCount; } /** - * Get the overall miss count for this cache. A miss is an - * access to the cache, which returned a {@code null} context for a - * queried key. + * Get the overall miss count for this cache. A miss is an access to the + * cache, which returned a {@code null} context for a queried key. */ int getMissCount() { return this.missCount; } /** - * Explicitly add an ApplicationContext instance to the cache under the given key. + * Explicitly add an {@code ApplicationContext} instance to the cache under the given + * key. + * * @param key the context key (never {@code null}) - * @param context the ApplicationContext instance (never {@code null}) + * @param context the {@code ApplicationContext} instance (never {@code null}) */ void put(MergedContextConfiguration key, ApplicationContext context) { Assert.notNull(key, "Key must not be null"); Assert.notNull(context, "ApplicationContext must not be null"); - this.contextMap.put(key, context); - } - /** - * Remove the context with the given key. - * @param key the context key (never {@code null}) - * @return the corresponding ApplicationContext instance, or {@code null} - * if not found in the cache. - * @see #setDirty - */ - ApplicationContext remove(MergedContextConfiguration key) { - return this.contextMap.remove(key); - } + synchronized (monitor) { + this.contextMap.put(key, context); - /** - * Mark the context with the given key as dirty, effectively - * {@link #remove removing} the context from the cache and explicitly - * {@link ConfigurableApplicationContext#close() closing} it if it is an - * instance of {@link ConfigurableApplicationContext}. - *

Generally speaking, you would only call this method if you change the - * state of a singleton bean, potentially affecting future interaction with - * the context. - * @param key the context key (never {@code null}) - * @see #remove - */ - void setDirty(MergedContextConfiguration key) { - Assert.notNull(key, "Key must not be null"); - ApplicationContext context = remove(key); - if (context instanceof ConfigurableApplicationContext) { - ((ConfigurableApplicationContext) context).close(); + MergedContextConfiguration child = key; + MergedContextConfiguration parent = child.getParent(); + while (parent != null) { + Set list = hierarchyMap.get(parent); + if (list == null) { + list = new HashSet(); + hierarchyMap.put(parent, list); + } + list.add(child); + child = parent; + parent = child.getParent(); + } } } /** - * Determine the number of contexts currently stored in the cache. If the - * cache contains more than Integer.MAX_VALUE elements, returns - * Integer.MAX_VALUE. + * Remove the context with the given key from the cache and explicitly + * {@linkplain ConfigurableApplicationContext#close() close} it if it is an + * instance of {@link ConfigurableApplicationContext}. + * + *

Generally speaking, you would only call this method if you change the + * state of a singleton bean, potentially affecting future interaction with + * the context. + * + *

In addition, the semantics of the supplied {@code HierarchyMode} will + * be honored. See the Javadoc for {@link HierarchyMode} for details. + * + * @param key the context key; never {@code null} + * @param hierarchyMode the hierarchy mode; may be {@code null} if the context + * is not part of a hierarchy */ - int size() { - return this.contextMap.size(); + void remove(MergedContextConfiguration key, HierarchyMode hierarchyMode) { + Assert.notNull(key, "Key must not be null"); + + // startKey is the level at which to begin clearing the cache, depending + // on the configured hierarchy mode. + MergedContextConfiguration startKey = key; + if (hierarchyMode == HierarchyMode.EXHAUSTIVE) { + while (startKey.getParent() != null) { + startKey = startKey.getParent(); + } + } + + synchronized (monitor) { + final List removedContexts = new ArrayList(); + + remove(removedContexts, startKey); + + // Remove all remaining references to any removed contexts from the + // hierarchy map. + for (MergedContextConfiguration currentKey : removedContexts) { + for (Set children : hierarchyMap.values()) { + children.remove(currentKey); + } + } + + // Remove empty entries from the hierarchy map. + for (MergedContextConfiguration currentKey : hierarchyMap.keySet()) { + if (hierarchyMap.get(currentKey).isEmpty()) { + hierarchyMap.remove(currentKey); + } + } + } + } + + private void remove(List removedContexts, MergedContextConfiguration key) { + Assert.notNull(key, "Key must not be null"); + + synchronized (monitor) { + Set children = hierarchyMap.get(key); + if (children != null) { + for (MergedContextConfiguration child : children) { + // Recurse through lower levels + remove(removedContexts, child); + } + // Remove the set of children for the current context from the + // hierarchy map. + hierarchyMap.remove(key); + } + + // Physically remove and close leaf nodes first (i.e., on the way back up the + // stack as opposed to prior to the recursive call). + ApplicationContext context = contextMap.remove(key); + if (context instanceof ConfigurableApplicationContext) { + ((ConfigurableApplicationContext) context).close(); + } + removedContexts.add(key); + } } /** - * Generates a text string, which contains the {@link #size() size} as well - * as the {@link #hitCount hit} and {@link #missCount miss} counts. + * Determine the number of contexts currently stored in the cache. If the cache + * contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. */ + int size() { + synchronized (monitor) { + return this.contextMap.size(); + } + } + + /** + * Determine the number of parent contexts currently tracked within the cache. + */ + int getParentContextCount() { + synchronized (monitor) { + return this.hierarchyMap.size(); + } + } + + /** + * Generates a text string, which contains the {@linkplain #size() size} as well + * as the {@linkplain #getHitCount() hit}, {@linkplain #getMissCount() miss}, and + * {@linkplain #getParentContextCount() parent context} counts. + */ + @Override public String toString() { - return new ToStringCreator(this).append("size", size()).append("hitCount", getHitCount()). - append("missCount", getMissCount()).toString(); + return new ToStringCreator(this)// + .append("size", size())// + .append("hitCount", getHitCount())// + .append("missCount", getMissCount())// + .append("parentContextCount", getParentContextCount())// + .toString(); } } diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java index a23aed849c..b86032a7d2 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.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. @@ -66,11 +66,12 @@ import org.springframework.context.ConfigurableApplicationContext; * * @author Sam Brannen * @since 2.5 + * @see ContextHierarchy + * @see ActiveProfiles * @see ContextLoader * @see SmartContextLoader * @see ContextConfigurationAttributes * @see MergedContextConfiguration - * @see ActiveProfiles * @see org.springframework.context.ApplicationContext */ @Documented @@ -283,4 +284,19 @@ public @interface ContextConfiguration { */ Class loader() default ContextLoader.class; + /** + * The name of the context hierarchy level represented by this configuration. + * + *

If not specified the name will be inferred based on the numerical level within all + * declared contexts within the hierarchy. + * + *

This attribute is only applicable when used within a test class hierarchy that is + * configured using {@link ContextHierarchy @ContextHierarchy}, in which case the name + * can be used for merging or overriding this configuration with configuration of the + * same name in hierarchy levels defined in superclasses. + * + * @since 3.2.2 + */ + String name() default ""; + } diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextConfigurationAttributes.java b/spring-test/src/main/java/org/springframework/test/context/ContextConfigurationAttributes.java index 5a481c190d..035483a71e 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextConfigurationAttributes.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextConfigurationAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.test.context; +import java.util.Arrays; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -24,6 +26,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.style.ToStringCreator; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; /** * {@code ContextConfigurationAttributes} encapsulates the context @@ -54,6 +57,8 @@ public class ContextConfigurationAttributes { private final boolean inheritInitializers; + private final String name; + /** * Resolve resource locations from the {@link ContextConfiguration#locations() locations} @@ -75,7 +80,8 @@ public class ContextConfigurationAttributes { ObjectUtils.nullSafeToString(valueLocations), ObjectUtils.nullSafeToString(locations)); logger.error(msg); throw new IllegalStateException(msg); - } else if (!ObjectUtils.isEmpty(valueLocations)) { + } + else if (!ObjectUtils.isEmpty(valueLocations)) { locations = valueLocations; } @@ -92,7 +98,7 @@ public class ContextConfigurationAttributes { public ContextConfigurationAttributes(Class declaringClass, ContextConfiguration contextConfiguration) { this(declaringClass, resolveLocations(declaringClass, contextConfiguration), contextConfiguration.classes(), contextConfiguration.inheritLocations(), contextConfiguration.initializers(), - contextConfiguration.inheritInitializers(), contextConfiguration.loader()); + contextConfiguration.inheritInitializers(), contextConfiguration.name(), contextConfiguration.loader()); } /** @@ -109,13 +115,13 @@ public class ContextConfigurationAttributes { * @throws IllegalArgumentException if the {@code declaringClass} or {@code contextLoaderClass} is * {@code null}, or if the {@code locations} and {@code classes} are both non-empty * @deprecated as of Spring 3.2, use - * {@link #ContextConfigurationAttributes(Class, String[], Class[], boolean, Class[], boolean, Class)} + * {@link #ContextConfigurationAttributes(Class, String[], Class[], boolean, Class[], boolean, String, Class)} * instead */ @Deprecated public ContextConfigurationAttributes(Class declaringClass, String[] locations, Class[] classes, boolean inheritLocations, Class contextLoaderClass) { - this(declaringClass, locations, classes, inheritLocations, null, true, contextLoaderClass); + this(declaringClass, locations, classes, inheritLocations, null, true, null, contextLoaderClass); } /** @@ -138,6 +144,31 @@ public class ContextConfigurationAttributes { boolean inheritLocations, Class>[] initializers, boolean inheritInitializers, Class contextLoaderClass) { + this(declaringClass, locations, classes, inheritLocations, initializers, inheritInitializers, null, + contextLoaderClass); + } + + /** + * Construct a new {@link ContextConfigurationAttributes} instance for the + * {@linkplain Class test class} that declared the + * {@link ContextConfiguration @ContextConfiguration} annotation and its + * corresponding attributes. + * + * @param declaringClass the test class that declared {@code @ContextConfiguration} + * @param locations the resource locations declared via {@code @ContextConfiguration} + * @param classes the annotated classes declared via {@code @ContextConfiguration} + * @param inheritLocations the {@code inheritLocations} flag declared via {@code @ContextConfiguration} + * @param initializers the context initializers declared via {@code @ContextConfiguration} + * @param inheritInitializers the {@code inheritInitializers} flag declared via {@code @ContextConfiguration} + * @param name the name of level in the context hierarchy, or {@code null} if not applicable + * @param contextLoaderClass the {@code ContextLoader} class declared via {@code @ContextConfiguration} + * @throws IllegalArgumentException if the {@code declaringClass} or {@code contextLoaderClass} is + * {@code null}, or if the {@code locations} and {@code classes} are both non-empty + */ + public ContextConfigurationAttributes(Class declaringClass, String[] locations, Class[] classes, + boolean inheritLocations, + Class>[] initializers, + boolean inheritInitializers, String name, Class contextLoaderClass) { Assert.notNull(declaringClass, "declaringClass must not be null"); Assert.notNull(contextLoaderClass, "contextLoaderClass must not be null"); @@ -158,6 +189,7 @@ public class ContextConfigurationAttributes { this.inheritLocations = inheritLocations; this.initializers = initializers; this.inheritInitializers = inheritInitializers; + this.name = StringUtils.hasText(name) ? name : null; this.contextLoaderClass = contextLoaderClass; } @@ -305,6 +337,101 @@ public class ContextConfigurationAttributes { return contextLoaderClass; } + /** + * Get the name of the context hierarchy level that was declared via + * {@link ContextConfiguration @ContextConfiguration}. + * + * @return the name of the context hierarchy level or {@code null} if not applicable + * @see ContextConfiguration#name() + * @since 3.2.2 + */ + public String getName() { + return this.name; + } + + /** + * Generate a unique hash code for all properties of this + * {@code ContextConfigurationAttributes} instance excluding the + * {@linkplain #getName() name}. + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + declaringClass.hashCode(); + result = prime * result + Arrays.hashCode(locations); + result = prime * result + Arrays.hashCode(classes); + result = prime * result + (inheritLocations ? 1231 : 1237); + result = prime * result + Arrays.hashCode(initializers); + result = prime * result + (inheritInitializers ? 1231 : 1237); + result = prime * result + contextLoaderClass.hashCode(); + return result; + } + + /** + * Determine if the supplied object is equal to this + * {@code ContextConfigurationAttributes} instance by comparing both object's + * {@linkplain #getDeclaringClass() declaring class}, + * {@linkplain #getLocations() locations}, + * {@linkplain #getClasses() annotated classes}, + * {@linkplain #isInheritLocations() inheritLocations flag}, + * {@linkplain #getInitializers() context initializer classes}, + * {@linkplain #isInheritInitializers() inheritInitializers flag}, and the + * {@link #getContextLoaderClass() ContextLoader class}. + */ + @Override + public boolean equals(Object obj) { + + if (this == obj) { + return true; + } + if (!(obj instanceof ContextConfigurationAttributes)) { + return false; + } + + final ContextConfigurationAttributes that = (ContextConfigurationAttributes) obj; + + if (this.declaringClass == null) { + if (that.declaringClass != null) { + return false; + } + } + else if (!this.declaringClass.equals(that.declaringClass)) { + return false; + } + + if (!Arrays.equals(this.locations, that.locations)) { + return false; + } + + if (!Arrays.equals(this.classes, that.classes)) { + return false; + } + + if (this.inheritLocations != that.inheritLocations) { + return false; + } + + if (!Arrays.equals(this.initializers, that.initializers)) { + return false; + } + + if (this.inheritInitializers != that.inheritInitializers) { + return false; + } + + if (this.contextLoaderClass == null) { + if (that.contextLoaderClass != null) { + return false; + } + } + else if (!this.contextLoaderClass.equals(that.contextLoaderClass)) { + return false; + } + + return true; + } + /** * Provide a String representation of the context configuration attributes * and declaring class. @@ -318,6 +445,7 @@ public class ContextConfigurationAttributes { .append("inheritLocations", inheritLocations)// .append("initializers", ObjectUtils.nullSafeToString(initializers))// .append("inheritInitializers", inheritInitializers)// + .append("name", name)// .append("contextLoaderClass", contextLoaderClass.getName())// .toString(); } diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java b/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java new file mode 100644 index 0000000000..b7846b7a0d --- /dev/null +++ b/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java @@ -0,0 +1,54 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * {@code @ContextHierarchy} is a class-level annotation that is used to define + * a hierarchy of {@link org.springframework.context.ApplicationContext + * ApplicationContexts} for integration tests. + * + * @author Sam Brannen + * @since 3.2.2 + * @see ContextConfiguration + * @see org.springframework.context.ApplicationContext + */ +@Documented +@Inherited +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface ContextHierarchy { + + /** + * A list of {@link ContextConfiguration @ContextConfiguration} instances, + * each of which defines a level in the context hierarchy. + * + *

If you need to merge or override the configuration for a given level + * of the context hierarchy within a test class hierarchy, you must explicitly + * name that level by supplying the same value to the {@link ContextConfiguration#name + * name} attribute in {@code @ContextConfiguration} at each level in the + * class hierarchy. + */ + ContextConfiguration[] value(); + +} diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java b/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java index 8016c5d7c7..a43897eb0b 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java @@ -16,20 +16,24 @@ package org.springframework.test.context; -import static org.springframework.beans.BeanUtils.*; -import static org.springframework.core.annotation.AnnotationUtils.*; +import static org.springframework.beans.BeanUtils.instantiateClass; +import static org.springframework.core.annotation.AnnotationUtils.findAnnotationDeclaringClass; +import static org.springframework.core.annotation.AnnotationUtils.findAnnotationDeclaringClassForTypes; +import static org.springframework.core.annotation.AnnotationUtils.isAnnotationDeclaredLocally; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.annotation.AnnotationUtils; @@ -52,10 +56,13 @@ import org.springframework.util.StringUtils; * @see ContextConfigurationAttributes * @see ActiveProfiles * @see ApplicationContextInitializer + * @see ContextHierarchy * @see MergedContextConfiguration */ abstract class ContextLoaderUtils { + static final String GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX = "ContextHierarchyLevel#"; + private static final Log logger = LogFactory.getLog(ContextLoaderUtils.class); private static final String DEFAULT_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.support.DelegatingSmartContextLoader"; @@ -70,30 +77,29 @@ abstract class ContextLoaderUtils { } /** - * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the - * supplied list of {@link ContextConfigurationAttributes} and then - * instantiate and return that {@code ContextLoader}. + * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the supplied + * list of {@link ContextConfigurationAttributes} and then instantiate and return that + * {@code ContextLoader}. * - *

If the supplied {@code defaultContextLoaderClassName} is - * {@code null} or empty, depending on the absence or presence - * of {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration} - * either {@value #DEFAULT_CONTEXT_LOADER_CLASS_NAME} - * or {@value #DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME} will be used as the - * default context loader class name. For details on the class resolution - * process, see {@link #resolveContextLoaderClass}. + *

If the supplied {@code defaultContextLoaderClassName} is {@code null} or + * empty, depending on the absence or presence of + * {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration} either + * {@code "org.springframework.test.context.support.DelegatingSmartContextLoader"} or + * {@code "org.springframework.test.context.web.WebDelegatingSmartContextLoader"} will + * be used as the default context loader class name. For details on the class + * resolution process, see {@link #resolveContextLoaderClass}. * - * @param testClass the test class for which the {@code ContextLoader} - * should be resolved; must not be {@code null} - * @param configAttributesList the list of configuration attributes to process; - * must not be {@code null} or empty; must be ordered bottom-up + * @param testClass the test class for which the {@code ContextLoader} should be + * resolved; must not be {@code null} + * @param configAttributesList the list of configuration attributes to process; must + * not be {@code null} or empty; must be ordered bottom-up * (i.e., as if we were traversing up the class hierarchy) - * @param defaultContextLoaderClassName the name of the default - * {@code ContextLoader} class to use; may be {@code null} or empty - * @return the resolved {@code ContextLoader} for the supplied - * {@code testClass} (never {@code null}) + * @param defaultContextLoaderClassName the name of the default {@code ContextLoader} + * class to use; may be {@code null} or empty + * @return the resolved {@code ContextLoader} for the supplied {@code testClass} + * (never {@code null}) * @see #resolveContextLoaderClass */ - @SuppressWarnings("javadoc") static ContextLoader resolveContextLoader(Class testClass, List configAttributesList, String defaultContextLoaderClassName) { Assert.notNull(testClass, "Class must not be null"); @@ -113,36 +119,35 @@ abstract class ContextLoaderUtils { } /** - * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the - * supplied list of {@link ContextConfigurationAttributes}. + * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the supplied + * list of {@link ContextConfigurationAttributes}. * - *

Beginning with the first level in the context configuration attributes - * hierarchy: + *

Beginning with the first level in the context configuration attributes hierarchy: * *

    *
  1. If the {@link ContextConfigurationAttributes#getContextLoaderClass() * contextLoaderClass} property of {@link ContextConfigurationAttributes} is * configured with an explicit class, that class will be returned.
  2. - *
  3. If an explicit {@code ContextLoader} class is not specified at the - * current level in the hierarchy, traverse to the next level in the hierarchy - * and return to step #1.
  4. - *
  5. If no explicit {@code ContextLoader} class is found after traversing - * the hierarchy, an attempt will be made to load and return the class - * with the supplied {@code defaultContextLoaderClassName}.
  6. + *
  7. If an explicit {@code ContextLoader} class is not specified at the current + * level in the hierarchy, traverse to the next level in the hierarchy and return to + * step #1.
  8. + *
  9. If no explicit {@code ContextLoader} class is found after traversing the + * hierarchy, an attempt will be made to load and return the class with the supplied + * {@code defaultContextLoaderClassName}.
  10. *
* - * @param testClass the class for which to resolve the {@code ContextLoader} - * class; must not be {@code null}; only used for logging purposes - * @param configAttributesList the list of configuration attributes to process; - * must not be {@code null} or empty; must be ordered bottom-up + * @param testClass the class for which to resolve the {@code ContextLoader} class; + * must not be {@code null}; only used for logging purposes + * @param configAttributesList the list of configuration attributes to process; must + * not be {@code null} or empty; must be ordered bottom-up * (i.e., as if we were traversing up the class hierarchy) - * @param defaultContextLoaderClassName the name of the default - * {@code ContextLoader} class to use; must not be {@code null} or empty + * @param defaultContextLoaderClassName the name of the default {@code ContextLoader} + * class to use; must not be {@code null} or empty * @return the {@code ContextLoader} class to use for the supplied test class * @throws IllegalArgumentException if {@code @ContextConfiguration} is not * present on the supplied test class - * @throws IllegalStateException if the default {@code ContextLoader} class - * could not be loaded + * @throws IllegalStateException if the default {@code ContextLoader} class could not + * be loaded */ @SuppressWarnings("unchecked") static Class resolveContextLoaderClass(Class testClass, @@ -184,22 +189,201 @@ abstract class ContextLoaderUtils { } /** - * Resolve the list of {@link ContextConfigurationAttributes configuration - * attributes} for the supplied {@link Class class} and its superclasses. + * Convenience method for creating a {@link ContextConfigurationAttributes} instance + * from the supplied {@link ContextConfiguration} and declaring class and then adding + * the attributes to the supplied list. + */ + private static void convertContextConfigToConfigAttributesAndAddToList(ContextConfiguration contextConfiguration, + Class declaringClass, final List attributesList) { + if (logger.isTraceEnabled()) { + logger.trace(String.format("Retrieved @ContextConfiguration [%s] for declaring class [%s].", + contextConfiguration, declaringClass.getName())); + } + + ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(declaringClass, + contextConfiguration); + if (logger.isTraceEnabled()) { + logger.trace("Resolved context configuration attributes: " + attributes); + } + attributesList.add(attributes); + } + + /** + * Resolve the list of lists of {@linkplain ContextConfigurationAttributes context + * configuration attributes} for the supplied {@linkplain Class test class} and its + * superclasses, taking into account context hierarchies declared via + * {@link ContextHierarchy @ContextHierarchy} and + * {@link ContextConfiguration @ContextConfiguration}. * - *

Note that the {@link ContextConfiguration#inheritLocations - * inheritLocations} and {@link ContextConfiguration#inheritInitializers() - * inheritInitializers} flags of {@link ContextConfiguration - * @ContextConfiguration} will not be taken into - * consideration. If these flags need to be honored, that must be handled - * manually when traversing the list returned by this method. + *

The outer list represents a top-down ordering of context configuration + * attributes, where each element in the list represents the context configuration + * declared on a given test class in the class hierarchy. Each nested list + * contains the context configuration attributes declared either via a single + * instance of {@code @ContextConfiguration} on the particular class or via + * multiple instances of {@code @ContextConfiguration} declared within a + * single {@code @ContextHierarchy} instance on the particular class. + * Furthermore, each nested list maintains the order in which + * {@code @ContextConfiguration} instances are declared. + * + *

Note that the {@link ContextConfiguration#inheritLocations inheritLocations} and + * {@link ContextConfiguration#inheritInitializers() inheritInitializers} flags of + * {@link ContextConfiguration @ContextConfiguration} will not + * be taken into consideration. If these flags need to be honored, that must be + * handled manually when traversing the nested lists returned by this method. + * + * @param testClass the class for which to resolve the context hierarchy attributes + * (must not be {@code null}) + * @return the list of lists of configuration attributes for the specified class; + * never {@code null} + * @throws IllegalArgumentException if the supplied class is {@code null}; if + * neither {@code @ContextConfiguration} nor {@code @ContextHierarchy} is + * present on the supplied class; if a given class in the class hierarchy + * declares both {@code @ContextConfiguration} and {@code @ContextHierarchy} as + * top-level annotations; or if individual {@code @ContextConfiguration} + * elements within a {@code @ContextHierarchy} declaration on a given class + * in the class hierarchy do not define unique context configuration. + * + * @since 3.2.2 + * @see #buildContextHierarchyMap(Class) + * @see #resolveContextConfigurationAttributes(Class) + */ + static List> resolveContextHierarchyAttributes(Class testClass) { + Assert.notNull(testClass, "Class must not be null"); + + final Class contextConfigType = ContextConfiguration.class; + final Class contextHierarchyType = ContextHierarchy.class; + final List> annotationTypes = Arrays.asList(contextConfigType, contextHierarchyType); + + final List> hierarchyAttributes = new ArrayList>(); + + Class declaringClass = findAnnotationDeclaringClassForTypes(annotationTypes, testClass); + Assert.notNull(declaringClass, String.format( + "Could not find an 'annotation declaring class' for annotation type [%s] or [%s] and test class [%s]", + contextConfigType.getName(), contextHierarchyType.getName(), testClass.getName())); + + while (declaringClass != null) { + + boolean contextConfigDeclaredLocally = isAnnotationDeclaredLocally(contextConfigType, declaringClass); + boolean contextHierarchyDeclaredLocally = isAnnotationDeclaredLocally(contextHierarchyType, declaringClass); + + if (contextConfigDeclaredLocally && contextHierarchyDeclaredLocally) { + String msg = String.format("Test class [%s] has been configured with both @ContextConfiguration " + + "and @ContextHierarchy as class-level annotations. Only one of these annotations may " + + "be declared as a top-level annotation per test class.", declaringClass.getName()); + logger.error(msg); + throw new IllegalStateException(msg); + } + + final List configAttributesList = new ArrayList(); + + if (contextConfigDeclaredLocally) { + ContextConfiguration contextConfiguration = declaringClass.getAnnotation(contextConfigType); + convertContextConfigToConfigAttributesAndAddToList(contextConfiguration, declaringClass, + configAttributesList); + } + else if (contextHierarchyDeclaredLocally) { + ContextHierarchy contextHierarchy = declaringClass.getAnnotation(contextHierarchyType); + for (ContextConfiguration contextConfiguration : contextHierarchy.value()) { + convertContextConfigToConfigAttributesAndAddToList(contextConfiguration, declaringClass, + configAttributesList); + } + + // Check for uniqueness + Set configAttributesSet = new HashSet( + configAttributesList); + if (configAttributesSet.size() != configAttributesList.size()) { + String msg = String.format("The @ContextConfiguration elements configured via " + + "@ContextHierarchy in test class [%s] must define unique contexts to load.", + declaringClass.getName()); + logger.error(msg); + throw new IllegalStateException(msg); + } + } + else { + // This should theoretically actually never happen... + String msg = String.format("Test class [%s] has been configured with neither @ContextConfiguration " + + "nor @ContextHierarchy as a class-level annotation.", declaringClass.getName()); + logger.error(msg); + throw new IllegalStateException(msg); + } + + hierarchyAttributes.add(0, configAttributesList); + + declaringClass = findAnnotationDeclaringClassForTypes(annotationTypes, declaringClass.getSuperclass()); + } + + return hierarchyAttributes; + } + + /** + * Build a context hierarchy map for the supplied {@linkplain Class + * test class} and its superclasses, taking into account context hierarchies + * declared via {@link ContextHierarchy @ContextHierarchy} and + * {@link ContextConfiguration @ContextConfiguration}. + * + *

Each value in the map represents the consolidated list of {@linkplain + * ContextConfigurationAttributes context configuration attributes} for a + * given level in the context hierarchy (potentially across the test class + * hierarchy), keyed by the {@link ContextConfiguration#name() name} of the + * context hierarchy level. + * + *

If a given level in the context hierarchy does not have an explicit + * name (i.e., configured via {@link ContextConfiguration#name}), a name will + * be generated for that hierarchy level by appending the numerical level to + * the {@link #GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX}. + * + * @param testClass the class for which to resolve the context hierarchy map + * (must not be {@code null}) + * @return a map of context configuration attributes for the context hierarchy, + * keyed by context hierarchy level name; never {@code null} + * + * @since 3.2.2 + * @see #resolveContextHierarchyAttributes(Class) + */ + static Map> buildContextHierarchyMap(Class testClass) { + final Map> map = new LinkedHashMap>(); + int hierarchyLevel = 1; + + for (List configAttributesList : resolveContextHierarchyAttributes(testClass)) { + for (ContextConfigurationAttributes configAttributes : configAttributesList) { + String name = configAttributes.getName(); + + // Assign a generated name? + if (!StringUtils.hasText(name)) { + name = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + hierarchyLevel; + } + + // Encountered a new context hierarchy level? + if (!map.containsKey(name)) { + hierarchyLevel++; + map.put(name, new ArrayList()); + } + + map.get(name).add(configAttributes); + } + } + + return map; + } + + /** + * Resolve the list of {@linkplain ContextConfigurationAttributes context + * configuration attributes} for the supplied {@linkplain Class test class} and its + * superclasses. + * + *

Note that the {@link ContextConfiguration#inheritLocations inheritLocations} and + * {@link ContextConfiguration#inheritInitializers() inheritInitializers} flags of + * {@link ContextConfiguration @ContextConfiguration} will not + * be taken into consideration. If these flags need to be honored, that must be + * handled manually when traversing the list returned by this method. * * @param testClass the class for which to resolve the configuration attributes (must * not be {@code null}) - * @return the list of configuration attributes for the specified class, ordered bottom-up - * (i.e., as if we were traversing up the class hierarchy); never {@code null} - * @throws IllegalArgumentException if the supplied class is {@code null} or - * if {@code @ContextConfiguration} is not present on the supplied class + * @return the list of configuration attributes for the specified class, ordered + * bottom-up (i.e., as if we were traversing up the class hierarchy); + * never {@code null} + * @throws IllegalArgumentException if the supplied class is {@code null} or if + * {@code @ContextConfiguration} is not present on the supplied class */ static List resolveContextConfigurationAttributes(Class testClass) { Assert.notNull(testClass, "Class must not be null"); @@ -214,19 +398,7 @@ abstract class ContextLoaderUtils { while (declaringClass != null) { ContextConfiguration contextConfiguration = declaringClass.getAnnotation(annotationType); - if (logger.isTraceEnabled()) { - logger.trace(String.format("Retrieved @ContextConfiguration [%s] for declaring class [%s].", - contextConfiguration, declaringClass.getName())); - } - - ContextConfigurationAttributes attributes = new ContextConfigurationAttributes(declaringClass, - contextConfiguration); - if (logger.isTraceEnabled()) { - logger.trace("Resolved context configuration attributes: " + attributes); - } - - attributesList.add(attributes); - + convertContextConfigToConfigAttributesAndAddToList(contextConfiguration, declaringClass, attributesList); declaringClass = findAnnotationDeclaringClass(annotationType, declaringClass.getSuperclass()); } @@ -234,22 +406,21 @@ abstract class ContextLoaderUtils { } /** - * Resolve the list of merged {@code ApplicationContextInitializer} classes - * for the supplied list of {@code ContextConfigurationAttributes}. + * Resolve the list of merged {@code ApplicationContextInitializer} classes for the + * supplied list of {@code ContextConfigurationAttributes}. * *

Note that the {@link ContextConfiguration#inheritInitializers inheritInitializers} * flag of {@link ContextConfiguration @ContextConfiguration} will be taken into - * consideration. Specifically, if the {@code inheritInitializers} flag is - * set to {@code true} for a given level in the class hierarchy represented by - * the provided configuration attributes, context initializer classes defined - * at the given level will be merged with those defined in higher levels - * of the class hierarchy. + * consideration. Specifically, if the {@code inheritInitializers} flag is set to + * {@code true} for a given level in the class hierarchy represented by the provided + * configuration attributes, context initializer classes defined at the given level + * will be merged with those defined in higher levels of the class hierarchy. * - * @param configAttributesList the list of configuration attributes to process; - * must not be {@code null} or empty; must be ordered bottom-up + * @param configAttributesList the list of configuration attributes to process; must + * not be {@code null} or empty; must be ordered bottom-up * (i.e., as if we were traversing up the class hierarchy) - * @return the set of merged context initializer classes, including those - * from superclasses if appropriate (never {@code null}) + * @return the set of merged context initializer classes, including those from + * superclasses if appropriate (never {@code null}) * @since 3.2 */ static Set>> resolveInitializerClasses( @@ -278,16 +449,15 @@ abstract class ContextLoaderUtils { /** * Resolve active bean definition profiles for the supplied {@link Class}. * - *

Note that the {@link ActiveProfiles#inheritProfiles inheritProfiles} - * flag of {@link ActiveProfiles @ActiveProfiles} will be taken into - * consideration. Specifically, if the {@code inheritProfiles} flag is - * set to {@code true}, profiles defined in the test class will be - * merged with those defined in superclasses. + *

Note that the {@link ActiveProfiles#inheritProfiles inheritProfiles} flag of + * {@link ActiveProfiles @ActiveProfiles} will be taken into consideration. + * Specifically, if the {@code inheritProfiles} flag is set to {@code true}, profiles + * defined in the test class will be merged with those defined in superclasses. * - * @param testClass the class for which to resolve the active profiles (must - * not be {@code null}) - * @return the set of active profiles for the specified class, including - * active profiles from superclasses if appropriate (never {@code null}) + * @param testClass the class for which to resolve the active profiles (must not be + * {@code null}) + * @return the set of active profiles for the specified class, including active + * profiles from superclasses if appropriate (never {@code null}) * @see ActiveProfiles * @see org.springframework.context.annotation.Profile */ @@ -342,14 +512,72 @@ abstract class ContextLoaderUtils { } /** - * Build the {@link MergedContextConfiguration merged context configuration} - * for the supplied {@link Class testClass} and - * {@code defaultContextLoaderClassName}. + * Build the {@link MergedContextConfiguration merged context configuration} for + * the supplied {@link Class testClass} and {@code defaultContextLoaderClassName}, + * taking into account context hierarchies declared via + * {@link ContextHierarchy @ContextHierarchy} and + * {@link ContextConfiguration @ContextConfiguration}. * * @param testClass the test class for which the {@code MergedContextConfiguration} * should be built (must not be {@code null}) - * @param defaultContextLoaderClassName the name of the default - * {@code ContextLoader} class to use (may be {@code null}) + * @param defaultContextLoaderClassName the name of the default {@code ContextLoader} + * class to use (may be {@code null}) + * @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to + * be passed to the {@code MergedContextConfiguration} constructor + * @return the merged context configuration + * @see #buildContextHierarchyMap(Class) + * @see #buildMergedContextConfiguration(Class, List, String, MergedContextConfiguration, CacheAwareContextLoaderDelegate) + */ + @SuppressWarnings("javadoc") + static MergedContextConfiguration buildMergedContextConfiguration(Class testClass, + String defaultContextLoaderClassName, CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate) { + + if (testClass.isAnnotationPresent(ContextHierarchy.class)) { + Map> hierarchyMap = buildContextHierarchyMap(testClass); + + MergedContextConfiguration parentConfig = null; + MergedContextConfiguration mergedConfig = null; + + for (List list : hierarchyMap.values()) { + List reversedList = new ArrayList(list); + Collections.reverse(reversedList); + + // Don't use the supplied testClass; instead ensure that we are + // building the MCC for the actual test class that declared the + // configuration for the current level in the context hierarchy. + Assert.notEmpty(reversedList, "ContextConfigurationAttributes list must not be empty"); + Class declaringClass = reversedList.get(0).getDeclaringClass(); + + mergedConfig = buildMergedContextConfiguration(declaringClass, reversedList, + defaultContextLoaderClassName, parentConfig, cacheAwareContextLoaderDelegate); + parentConfig = mergedConfig; + } + + // Return the last level in the context hierarchy + return mergedConfig; + } + else { + return buildMergedContextConfiguration(testClass, resolveContextConfigurationAttributes(testClass), + defaultContextLoaderClassName, null, cacheAwareContextLoaderDelegate); + } + } + + /** + * Build the {@link MergedContextConfiguration merged context configuration} for the + * supplied {@link Class testClass}, context configuration attributes, + * {@code defaultContextLoaderClassName}, and parent context configuration. + * + * @param testClass the test class for which the {@code MergedContextConfiguration} + * should be built (must not be {@code null}) + * @param configAttributesList the list of context configuration attributes for the + * specified test class, ordered bottom-up (i.e., as if we were + * traversing up the class hierarchy); never {@code null} or empty + * @param defaultContextLoaderClassName the name of the default {@code ContextLoader} + * class to use (may be {@code null}) + * @param parentConfig the merged context configuration for the parent application + * context in a context hierarchy, or {@code null} if there is no parent + * @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to + * be passed to the {@code MergedContextConfiguration} constructor * @return the merged context configuration * @see #resolveContextLoader * @see #resolveContextConfigurationAttributes @@ -358,10 +586,11 @@ abstract class ContextLoaderUtils { * @see #resolveActiveProfiles * @see MergedContextConfiguration */ - static MergedContextConfiguration buildMergedContextConfiguration(Class testClass, - String defaultContextLoaderClassName) { + private static MergedContextConfiguration buildMergedContextConfiguration(final Class testClass, + final List configAttributesList, + final String defaultContextLoaderClassName, MergedContextConfiguration parentConfig, + CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate) { - final List configAttributesList = resolveContextConfigurationAttributes(testClass); final ContextLoader contextLoader = resolveContextLoader(testClass, configAttributesList, defaultContextLoaderClassName); final List locationsList = new ArrayList(); @@ -397,22 +626,21 @@ abstract class ContextLoaderUtils { String[] activeProfiles = resolveActiveProfiles(testClass); MergedContextConfiguration mergedConfig = buildWebMergedContextConfiguration(testClass, locations, classes, - initializerClasses, activeProfiles, contextLoader); + initializerClasses, activeProfiles, contextLoader, cacheAwareContextLoaderDelegate, parentConfig); if (mergedConfig == null) { mergedConfig = new MergedContextConfiguration(testClass, locations, classes, initializerClasses, - activeProfiles, contextLoader); + activeProfiles, contextLoader, cacheAwareContextLoaderDelegate, parentConfig); } return mergedConfig; } /** - * Load the {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration} + * Load the {@link org.springframework.test.context.web.WebAppConfiguration} * class, using reflection in order to avoid package cycles. * - * @return the {@code @WebAppConfiguration} class or {@code null} if it - * cannot be loaded + * @return the {@code @WebAppConfiguration} class or {@code null} if it cannot be loaded * @since 3.2 */ @SuppressWarnings("unchecked") @@ -431,12 +659,10 @@ abstract class ContextLoaderUtils { } /** - * Attempt to build a {@link org.springframework.test.context.web.WebMergedContextConfiguration - * WebMergedContextConfiguration} from the supplied arguments, using reflection - * in order to avoid package cycles. + * Attempt to build a {@link org.springframework.test.context.web.WebMergedContextConfiguration} + * from the supplied arguments, using reflection in order to avoid package cycles. * - * @return the {@code WebMergedContextConfiguration} or {@code null} if - * it could not be built + * @return the {@code WebMergedContextConfiguration} or {@code null} if it could not be built * @since 3.2 */ @SuppressWarnings("unchecked") @@ -445,7 +671,8 @@ abstract class ContextLoaderUtils { String[] locations, Class[] classes, Set>> initializerClasses, - String[] activeProfiles, ContextLoader contextLoader) { + String[] activeProfiles, ContextLoader contextLoader, + CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate, MergedContextConfiguration parentConfig) { Class webAppConfigClass = loadWebAppConfigurationClass(); @@ -459,11 +686,12 @@ abstract class ContextLoaderUtils { Constructor constructor = ClassUtils.getConstructorIfAvailable( webMergedConfigClass, Class.class, String[].class, Class[].class, Set.class, String[].class, - String.class, ContextLoader.class); + String.class, ContextLoader.class, CacheAwareContextLoaderDelegate.class, + MergedContextConfiguration.class); if (constructor != null) { return instantiateClass(constructor, testClass, locations, classes, initializerClasses, - activeProfiles, resourceBasePath, contextLoader); + activeProfiles, resourceBasePath, contextLoader, cacheAwareContextLoaderDelegate, parentConfig); } } catch (Throwable t) { diff --git a/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java index b4c1f683a2..befe85c7cb 100644 --- a/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/MergedContextConfiguration.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,9 +23,11 @@ import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; +import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.style.ToStringCreator; +import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; @@ -72,6 +74,8 @@ public class MergedContextConfiguration implements Serializable { private final Set>> contextInitializerClasses; private final String[] activeProfiles; private final ContextLoader contextLoader; + private final CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate; + private final MergedContextConfiguration parent; private static String[] processLocations(String[] locations) { @@ -149,6 +153,7 @@ public class MergedContextConfiguration implements Serializable { * @param contextInitializerClasses the merged context initializer classes * @param activeProfiles the merged active bean definition profiles * @param contextLoader the resolved {@code ContextLoader} + * @see #MergedContextConfiguration(Class, String[], Class[], Set, String[], ContextLoader, CacheAwareContextLoaderDelegate, MergedContextConfiguration) */ public MergedContextConfiguration( Class testClass, @@ -156,12 +161,48 @@ public class MergedContextConfiguration implements Serializable { Class[] classes, Set>> contextInitializerClasses, String[] activeProfiles, ContextLoader contextLoader) { + this(testClass, locations, classes, contextInitializerClasses, activeProfiles, contextLoader, null, null); + } + + /** + * Create a new {@code MergedContextConfiguration} instance for the + * supplied test class, resource locations, annotated classes, context + * initializers, active profiles, {@code ContextLoader}, and parent + * configuration. + * + *

If a {@code null} value is supplied for {@code locations}, + * {@code classes}, or {@code activeProfiles} an empty array will + * be stored instead. If a {@code null} value is supplied for the + * {@code contextInitializerClasses} an empty set will be stored instead. + * Furthermore, active profiles will be sorted, and duplicate profiles will + * be removed. + * + * @param testClass the test class for which the configuration was merged + * @param locations the merged resource locations + * @param classes the merged annotated classes + * @param contextInitializerClasses the merged context initializer classes + * @param activeProfiles the merged active bean definition profiles + * @param contextLoader the resolved {@code ContextLoader} + * @param cacheAwareContextLoaderDelegate a cache-aware context loader + * delegate with which to retrieve the parent context + * @param parent the parent configuration or {@code null} if there is no parent + * @since 3.2.2 + */ + public MergedContextConfiguration( + Class testClass, + String[] locations, + Class[] classes, + Set>> contextInitializerClasses, + String[] activeProfiles, ContextLoader contextLoader, + CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate, MergedContextConfiguration parent) { this.testClass = testClass; this.locations = processLocations(locations); this.classes = processClasses(classes); this.contextInitializerClasses = processContextInitializerClasses(contextInitializerClasses); this.activeProfiles = processActiveProfiles(activeProfiles); this.contextLoader = contextLoader; + this.cacheAwareContextLoaderDelegate = cacheAwareContextLoaderDelegate; + this.parent = parent; } /** @@ -207,6 +248,39 @@ public class MergedContextConfiguration implements Serializable { return contextLoader; } + /** + * Get the {@link MergedContextConfiguration} for the parent application context in a + * context hierarchy. + * + * @return the parent configuration or {@code null} if there is no parent + * @see #getParentApplicationContext() + * @since 3.2.2 + */ + public MergedContextConfiguration getParent() { + return this.parent; + } + + /** + * Get the parent {@link ApplicationContext} for the context defined by this + * {@code MergedContextConfiguration} from the context cache. + *

+ * If the parent context has not yet been loaded, it will be loaded, stored in the + * cache, and then returned. + * + * @return the parent {@code ApplicationContext} or {@code null} if there is no parent + * @see #getParent() + * @since 3.2.2 + */ + public ApplicationContext getParentApplicationContext() { + if (parent == null) { + return null; + } + + Assert.state(cacheAwareContextLoaderDelegate != null, + "Cannot retrieve a parent application context without access to the CacheAwareContextLoaderDelegate."); + return cacheAwareContextLoaderDelegate.loadContext(parent); + } + /** * Generate a unique hash code for all properties of this * {@code MergedContextConfiguration} excluding the @@ -220,6 +294,7 @@ public class MergedContextConfiguration implements Serializable { result = prime * result + Arrays.hashCode(classes); result = prime * result + contextInitializerClasses.hashCode(); result = prime * result + Arrays.hashCode(activeProfiles); + result = prime * result + (parent == null ? 0 : parent.hashCode()); result = prime * result + nullSafeToString(contextLoader).hashCode(); return result; } @@ -229,8 +304,9 @@ public class MergedContextConfiguration implements Serializable { * instance by comparing both object's {@linkplain #getLocations() locations}, * {@linkplain #getClasses() annotated classes}, * {@linkplain #getContextInitializerClasses() context initializer classes}, - * {@linkplain #getActiveProfiles() active profiles}, and the fully qualified - * names of their {@link #getContextLoader() ContextLoaders}. + * {@linkplain #getActiveProfiles() active profiles}, + * {@linkplain #getParent() parents}, and the fully qualified names of their + * {@link #getContextLoader() ContextLoaders}. */ @Override public boolean equals(Object obj) { @@ -247,15 +323,28 @@ public class MergedContextConfiguration implements Serializable { if (!Arrays.equals(this.locations, that.locations)) { return false; } + if (!Arrays.equals(this.classes, that.classes)) { return false; } + if (!this.contextInitializerClasses.equals(that.contextInitializerClasses)) { return false; } + if (!Arrays.equals(this.activeProfiles, that.activeProfiles)) { return false; } + + if (this.parent == null) { + if (that.parent != null) { + return false; + } + } + else if (!this.parent.equals(that.parent)) { + return false; + } + if (!nullSafeToString(this.contextLoader).equals(nullSafeToString(that.contextLoader))) { return false; } @@ -267,8 +356,9 @@ public class MergedContextConfiguration implements Serializable { * Provide a String representation of the {@linkplain #getTestClass() test class}, * {@linkplain #getLocations() locations}, {@linkplain #getClasses() annotated classes}, * {@linkplain #getContextInitializerClasses() context initializer classes}, - * {@linkplain #getActiveProfiles() active profiles}, and the name of the - * {@link #getContextLoader() ContextLoader}. + * {@linkplain #getActiveProfiles() active profiles}, the name of the + * {@link #getContextLoader() ContextLoader}, and the + * {@linkplain #getParent() parent configuration}. */ @Override public String toString() { @@ -279,6 +369,7 @@ public class MergedContextConfiguration implements Serializable { .append("contextInitializerClasses", ObjectUtils.nullSafeToString(contextInitializerClasses))// .append("activeProfiles", ObjectUtils.nullSafeToString(activeProfiles))// .append("contextLoader", nullSafeToString(contextLoader))// + .append("parent", parent)// .toString(); } diff --git a/spring-test/src/main/java/org/springframework/test/context/SmartContextLoader.java b/spring-test/src/main/java/org/springframework/test/context/SmartContextLoader.java index 8d069c85e9..d0495ca010 100644 --- a/spring-test/src/main/java/org/springframework/test/context/SmartContextLoader.java +++ b/spring-test/src/main/java/org/springframework/test/context/SmartContextLoader.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. @@ -29,8 +29,7 @@ import org.springframework.context.ApplicationContext; * context that it loads (see {@link MergedContextConfiguration#getActiveProfiles()} * and {@link #loadContext(MergedContextConfiguration)}). * - *

See the Javadoc for - * {@link ContextConfiguration @ContextConfiguration} + *

See the Javadoc for {@link ContextConfiguration @ContextConfiguration} * for a definition of annotated class. * *

Clients of a {@code SmartContextLoader} should call @@ -48,8 +47,8 @@ import org.springframework.context.ApplicationContext; *

Even though {@code SmartContextLoader} extends {@code ContextLoader}, * clients should favor {@code SmartContextLoader}-specific methods over those * defined in {@code ContextLoader}, particularly because a - * {@code SmartContextLoader} may choose not to support methods defined in - * the {@code ContextLoader} SPI. + * {@code SmartContextLoader} may choose not to support methods defined in the + * {@code ContextLoader} SPI. * *

Concrete implementations must provide a {@code public} no-args constructor. * @@ -59,6 +58,9 @@ import org.springframework.context.ApplicationContext; *

  • {@link org.springframework.test.context.support.AnnotationConfigContextLoader AnnotationConfigContextLoader}
  • *
  • {@link org.springframework.test.context.support.GenericXmlContextLoader GenericXmlContextLoader}
  • *
  • {@link org.springframework.test.context.support.GenericPropertiesContextLoader GenericPropertiesContextLoader}
  • + *
  • {@link org.springframework.test.context.web.WebDelegatingSmartContextLoader WebDelegatingSmartContextLoader}
  • + *
  • {@link org.springframework.test.context.web.AnnotationConfigWebContextLoader AnnotationConfigWebContextLoader}
  • + *
  • {@link org.springframework.test.context.web.GenericXmlWebContextLoader GenericXmlWebContextLoader}
  • * * * @author Sam Brannen diff --git a/spring-test/src/main/java/org/springframework/test/context/TestContext.java b/spring-test/src/main/java/org/springframework/test/context/TestContext.java index 27100be94c..d2719b50a0 100644 --- a/spring-test/src/main/java/org/springframework/test/context/TestContext.java +++ b/spring-test/src/main/java/org/springframework/test/context/TestContext.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,9 +20,11 @@ import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.context.ApplicationContext; import org.springframework.core.AttributeAccessorSupport; import org.springframework.core.style.ToStringCreator; +import org.springframework.test.annotation.DirtiesContext.HierarchyMode; import org.springframework.util.Assert; /** @@ -41,6 +43,8 @@ public class TestContext extends AttributeAccessorSupport { private final ContextCache contextCache; + private final CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate; + private final MergedContextConfiguration mergedContextConfiguration; private final Class testClass; @@ -61,16 +65,17 @@ public class TestContext extends AttributeAccessorSupport { } /** - * Construct a new test context for the supplied {@link Class test class} - * and {@link ContextCache context cache} and parse the corresponding - * {@link ContextConfiguration @ContextConfiguration} annotation, if - * present. + * Construct a new test context for the supplied {@linkplain Class test class} + * and {@linkplain ContextCache context cache} and parse the corresponding + * {@link ContextConfiguration @ContextConfiguration} or + * {@link ContextHierarchy @ContextHierarchy} annotation, if present. *

    If the supplied class name for the default {@code ContextLoader} * is {@code null} or empty and no concrete {@code ContextLoader} - * class is explicitly supplied via the {@code @ContextConfiguration} - * annotation, a + * class is explicitly supplied via {@code @ContextConfiguration}, a * {@link org.springframework.test.context.support.DelegatingSmartContextLoader - * DelegatingSmartContextLoader} will be used instead. + * DelegatingSmartContextLoader} or + * {@link org.springframework.test.context.web.WebDelegatingSmartContextLoader + * WebDelegatingSmartContextLoader} will be used instead. * @param testClass the test class for which the test context should be * constructed (must not be {@code null}) * @param contextCache the context cache from which the constructed test @@ -83,54 +88,27 @@ public class TestContext extends AttributeAccessorSupport { Assert.notNull(testClass, "Test class must not be null"); Assert.notNull(contextCache, "ContextCache must not be null"); - MergedContextConfiguration mergedContextConfiguration; - ContextConfiguration contextConfiguration = testClass.getAnnotation(ContextConfiguration.class); + this.testClass = testClass; + this.contextCache = contextCache; + this.cacheAwareContextLoaderDelegate = new CacheAwareContextLoaderDelegate(contextCache); - if (contextConfiguration == null) { + MergedContextConfiguration mergedContextConfiguration; + + if (testClass.isAnnotationPresent(ContextConfiguration.class) + || testClass.isAnnotationPresent(ContextHierarchy.class)) { + mergedContextConfiguration = ContextLoaderUtils.buildMergedContextConfiguration(testClass, + defaultContextLoaderClassName, cacheAwareContextLoaderDelegate); + } + else { if (logger.isInfoEnabled()) { - logger.info(String.format("@ContextConfiguration not found for class [%s]", testClass)); + logger.info(String.format( + "Neither @ContextConfiguration nor @ContextHierarchy found for test class [%s]", + testClass.getName())); } mergedContextConfiguration = new MergedContextConfiguration(testClass, null, null, null, null); } - else { - if (logger.isTraceEnabled()) { - logger.trace(String.format("Retrieved @ContextConfiguration [%s] for class [%s]", contextConfiguration, - testClass)); - } - mergedContextConfiguration = ContextLoaderUtils.buildMergedContextConfiguration(testClass, - defaultContextLoaderClassName); - } - this.contextCache = contextCache; this.mergedContextConfiguration = mergedContextConfiguration; - this.testClass = testClass; - } - - /** - * Load an {@code ApplicationContext} for this test context using the - * configured {@code ContextLoader} and merged context configuration. Supports - * both the {@link SmartContextLoader} and {@link ContextLoader} SPIs. - * @throws Exception if an error occurs while loading the application context - */ - private ApplicationContext loadApplicationContext() throws Exception { - ContextLoader contextLoader = mergedContextConfiguration.getContextLoader(); - Assert.notNull(contextLoader, "Cannot load an ApplicationContext with a NULL 'contextLoader'. " - + "Consider annotating your test class with @ContextConfiguration."); - - ApplicationContext applicationContext; - - if (contextLoader instanceof SmartContextLoader) { - SmartContextLoader smartContextLoader = (SmartContextLoader) contextLoader; - applicationContext = smartContextLoader.loadContext(mergedContextConfiguration); - } - else { - String[] locations = mergedContextConfiguration.getLocations(); - Assert.notNull(locations, "Cannot load an ApplicationContext with a NULL 'locations' array. " - + "Consider annotating your test class with @ContextConfiguration."); - applicationContext = contextLoader.loadContext(locations); - } - - return applicationContext; } /** @@ -141,31 +119,7 @@ public class TestContext extends AttributeAccessorSupport { * application context */ public ApplicationContext getApplicationContext() { - synchronized (contextCache) { - ApplicationContext context = contextCache.get(mergedContextConfiguration); - if (context == null) { - try { - context = loadApplicationContext(); - if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Storing ApplicationContext for test class [%s] in cache under key [%s].", testClass, - mergedContextConfiguration)); - } - contextCache.put(mergedContextConfiguration, context); - } - catch (Exception ex) { - throw new IllegalStateException("Failed to load ApplicationContext", ex); - } - } - else { - if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Retrieved ApplicationContext for test class [%s] from cache with key [%s].", testClass, - mergedContextConfiguration)); - } - } - return context; - } + return cacheAwareContextLoaderDelegate.loadContext(mergedContextConfiguration); } /** @@ -209,15 +163,27 @@ public class TestContext extends AttributeAccessorSupport { } /** - * Call this method to signal that the {@link ApplicationContext application - * context} associated with this test context is dirty and should - * be reloaded. Do this if a test has modified the context (for example, by - * replacing a bean definition). + * Call this method to signal that the {@linkplain ApplicationContext application + * context} associated with this test context is dirty and should be + * discarded. Do this if a test has modified the context — for example, + * by replacing a bean definition or modifying the state of a singleton bean. + * @deprecated As of Spring 3.2.2, use {@link #markApplicationContextDirty(HierarchyMode)} instead. */ + @Deprecated public void markApplicationContextDirty() { - synchronized (contextCache) { - contextCache.setDirty(mergedContextConfiguration); - } + markApplicationContextDirty((HierarchyMode) null); + } + + /** + * Call this method to signal that the {@linkplain ApplicationContext application + * context} associated with this test context is dirty and should be + * discarded. Do this if a test has modified the context — for example, + * by replacing a bean definition or modifying the state of a singleton bean. + * @param hierarchyMode the context cache clearing mode to be applied if the + * context is part of a hierarchy (may be {@code null}) + */ + public void markApplicationContextDirty(HierarchyMode hierarchyMode) { + contextCache.remove(mergedContextConfiguration, hierarchyMode); } /** diff --git a/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java b/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java index c67f0c72d7..aabdf33dfb 100644 --- a/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java +++ b/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java @@ -104,15 +104,14 @@ public class TestContextManager { } /** - * Constructs a new {@code TestContextManager} for the specified {@link Class test class} - * and automatically {@link #registerTestExecutionListeners registers} the + * Constructs a new {@code TestContextManager} for the specified {@linkplain Class + * test class} and automatically {@link #registerTestExecutionListeners registers} the * {@link TestExecutionListener TestExecutionListeners} configured for the test class * via the {@link TestExecutionListeners @TestExecutionListeners} annotation. * @param testClass the test class to be managed - * @param defaultContextLoaderClassName the name of the default - * {@code ContextLoader} class to use (may be {@code null}) + * @param defaultContextLoaderClassName the name of the default {@code ContextLoader} + * class to use (may be {@code null}) * @see #registerTestExecutionListeners(TestExecutionListener...) - * @see #retrieveTestExecutionListeners(Class) */ public TestContextManager(Class testClass, String defaultContextLoaderClassName) { this.testContext = new TestContext(testClass, contextCache, defaultContextLoaderClassName); diff --git a/spring-test/src/main/java/org/springframework/test/context/TestExecutionListener.java b/spring-test/src/main/java/org/springframework/test/context/TestExecutionListener.java index 0f2ceb73a4..a052523fc9 100644 --- a/spring-test/src/main/java/org/springframework/test/context/TestExecutionListener.java +++ b/spring-test/src/main/java/org/springframework/test/context/TestExecutionListener.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,29 +17,24 @@ package org.springframework.test.context; /** + * {@code TestExecutionListener} defines a listener API for reacting to + * test execution events published by the {@link TestContextManager} with which + * the listener is registered. *

    - * {@code TestExecutionListener} defines a listener API for - * reacting to test execution events published by the {@link TestContextManager} - * with which the listener is registered. - *

    - *

    - * Concrete implementations must provide a {@code public} no-args - * constructor, so that listeners can be instantiated transparently by tools and - * configuration mechanisms. - *

    + * Concrete implementations must provide a {@code public} no-args constructor, + * so that listeners can be instantiated transparently by tools and configuration + * mechanisms. *

    * Spring provides the following out-of-the-box implementations: - *

    *
      - *
    • - * {@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener + *
    • {@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener * DependencyInjectionTestExecutionListener}
    • - *
    • - * {@link org.springframework.test.context.support.DirtiesContextTestExecutionListener + *
    • {@link org.springframework.test.context.support.DirtiesContextTestExecutionListener * DirtiesContextTestExecutionListener}
    • - *
    • - * {@link org.springframework.test.context.transaction.TransactionalTestExecutionListener + *
    • {@link org.springframework.test.context.transaction.TransactionalTestExecutionListener * TransactionalTestExecutionListener}
    • + *
    • {@link org.springframework.test.context.web.ServletTestExecutionListener + * ServletTestExecutionListener}
    • *
    * * @author Sam Brannen diff --git a/spring-test/src/main/java/org/springframework/test/context/TestExecutionListeners.java b/spring-test/src/main/java/org/springframework/test/context/TestExecutionListeners.java index 50cfa74474..388f66b5c8 100644 --- a/spring-test/src/main/java/org/springframework/test/context/TestExecutionListeners.java +++ b/spring-test/src/main/java/org/springframework/test/context/TestExecutionListeners.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. @@ -26,9 +26,10 @@ import java.lang.annotation.Target; /** * {@code TestExecutionListeners} defines class-level metadata for * configuring which {@link TestExecutionListener TestExecutionListeners} should - * be registered with a {@link TestContextManager}. Typically, - * {@code @TestExecutionListeners} will be used in conjunction with - * {@link ContextConfiguration @ContextConfiguration}. + * be registered with a {@link TestContextManager}. + * + *

    Typically, {@code @TestExecutionListeners} will be used in conjunction with + * {@link ContextConfiguration @ContextConfiguration}. * * @author Sam Brannen * @since 2.5 @@ -43,11 +44,10 @@ import java.lang.annotation.Target; public @interface TestExecutionListeners { /** - *

    * The {@link TestExecutionListener TestExecutionListeners} to register with * a {@link TestContextManager}. - *

    * + * @see org.springframework.test.context.web.ServletTestExecutionListener * @see org.springframework.test.context.support.DependencyInjectionTestExecutionListener * @see org.springframework.test.context.support.DirtiesContextTestExecutionListener * @see org.springframework.test.context.transaction.TransactionalTestExecutionListener @@ -60,10 +60,8 @@ public @interface TestExecutionListeners { Class[] value() default {}; /** - *

    * Whether or not {@link #value() TestExecutionListeners} from superclasses * should be inherited. - *

    *

    * The default value is {@code true}, which means that an annotated * class will inherit the listeners defined by an annotated @@ -77,11 +75,12 @@ public @interface TestExecutionListeners { * {@code DependencyInjectionTestExecutionListener}, * {@code DirtiesContextTestExecutionListener}, and * {@code TransactionalTestExecutionListener}, in that order. - *

    * *
    -	 * @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
    -	 *    DirtiesContextTestExecutionListener.class })
    +	 * @TestExecutionListeners({
    +	 *    DependencyInjectionTestExecutionListener.class,
    +	 *    DirtiesContextTestExecutionListener.class
    +	 * })
     	 * public abstract class AbstractBaseTest {
     	 * 	// ...
     	 * }
    @@ -89,14 +88,12 @@ public @interface TestExecutionListeners {
     	 * @TestExecutionListeners(TransactionalTestExecutionListener.class)
     	 * public class TransactionalTest extends AbstractBaseTest {
     	 * 	// ...
    -	 * }
    -	 * 
    + * } * *

    - * If {@code inheritListeners} is set to {@code false}, the - * listeners for the annotated class will shadow and effectively - * replace any listeners defined by a superclass. - *

    + * If {@code inheritListeners} is set to {@code false}, the listeners for the + * annotated class will shadow and effectively replace any listeners + * defined by a superclass. */ boolean inheritListeners() default true; diff --git a/spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericContextLoader.java b/spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericContextLoader.java index c4b9b4dca7..bd84068ac7 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericContextLoader.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericContextLoader.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,13 @@ package org.springframework.test.context.support; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.support.BeanDefinitionReader; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; @@ -66,6 +69,12 @@ public abstract class AbstractGenericContextLoader extends AbstractContextLoader * *
      *
    • Creates a {@link GenericApplicationContext} instance.
    • + *
    • If the supplied {@code MergedContextConfiguration} references a + * {@linkplain MergedContextConfiguration#getParent() parent configuration}, + * the corresponding {@link MergedContextConfiguration#getParentApplicationContext() + * ApplicationContext} will be retrieved and + * {@linkplain GenericApplicationContext#setParent(ApplicationContext) set as the parent} + * for the context created by this method.
    • *
    • Calls {@link #prepareContext(GenericApplicationContext)} for backwards * compatibility with the {@link org.springframework.test.context.ContextLoader * ContextLoader} SPI.
    • @@ -97,6 +106,11 @@ public abstract class AbstractGenericContextLoader extends AbstractContextLoader } GenericApplicationContext context = new GenericApplicationContext(); + + ApplicationContext parent = mergedConfig.getParentApplicationContext(); + if (parent != null) { + context.setParent(parent); + } prepareContext(context); prepareContext(context, mergedConfig); customizeBeanFactory(context.getDefaultListableBeanFactory()); diff --git a/spring-test/src/main/java/org/springframework/test/context/support/DirtiesContextTestExecutionListener.java b/spring-test/src/main/java/org/springframework/test/context/support/DirtiesContextTestExecutionListener.java index 7c78474189..f865d532da 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/DirtiesContextTestExecutionListener.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/DirtiesContextTestExecutionListener.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,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.context.ApplicationContext; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.annotation.DirtiesContext.HierarchyMode; import org.springframework.test.context.TestContext; import org.springframework.util.Assert; @@ -43,26 +44,47 @@ public class DirtiesContextTestExecutionListener extends AbstractTestExecutionLi /** - * Marks the {@link ApplicationContext application context} of the supplied - * {@link TestContext test context} as - * {@link TestContext#markApplicationContextDirty() dirty}, and sets the + * Marks the {@linkplain ApplicationContext application context} of the supplied + * {@linkplain TestContext test context} as + * {@linkplain TestContext#markApplicationContextDirty() dirty}, and sets the * {@link DependencyInjectionTestExecutionListener#REINJECT_DEPENDENCIES_ATTRIBUTE * REINJECT_DEPENDENCIES_ATTRIBUTE} in the test context to {@code true}. + * @param testContext the test context whose application context should + * marked as dirty + * @deprecated as of Spring 3.2.2, use {@link #dirtyContext(TestContext, HierarchyMode)} instead. */ + @Deprecated protected void dirtyContext(TestContext testContext) { testContext.markApplicationContextDirty(); testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, Boolean.TRUE); } /** - * If the current test method of the supplied {@link TestContext test + * Marks the {@linkplain ApplicationContext application context} of the supplied + * {@linkplain TestContext test context} as {@linkplain + * TestContext#markApplicationContextDirty(HierarchyMode) dirty} and sets the + * {@link DependencyInjectionTestExecutionListener#REINJECT_DEPENDENCIES_ATTRIBUTE + * REINJECT_DEPENDENCIES_ATTRIBUTE} in the test context to {@code true}. + * @param testContext the test context whose application context should + * marked as dirty + * @param hierarchyMode the context cache clearing mode to be applied if the + * context is part of a hierarchy; may be {@code null} + * @since 3.2.2 + */ + protected void dirtyContext(TestContext testContext, HierarchyMode hierarchyMode) { + testContext.markApplicationContextDirty(hierarchyMode); + testContext.setAttribute(DependencyInjectionTestExecutionListener.REINJECT_DEPENDENCIES_ATTRIBUTE, Boolean.TRUE); + } + + /** + * If the current test method of the supplied {@linkplain TestContext test * context} is annotated with {@link DirtiesContext @DirtiesContext}, * or if the test class is annotated with {@link DirtiesContext - * @DirtiesContext} and the {@link DirtiesContext#classMode() class + * @DirtiesContext} and the {@linkplain DirtiesContext#classMode() class * mode} is set to {@link ClassMode#AFTER_EACH_TEST_METHOD - * AFTER_EACH_TEST_METHOD}, the {@link ApplicationContext application + * AFTER_EACH_TEST_METHOD}, the {@linkplain ApplicationContext application * context} of the test context will be - * {@link TestContext#markApplicationContextDirty() marked as dirty} and the + * {@linkplain TestContext#markApplicationContextDirty() marked as dirty} and the * {@link DependencyInjectionTestExecutionListener#REINJECT_DEPENDENCIES_ATTRIBUTE * REINJECT_DEPENDENCIES_ATTRIBUTE} in the test context will be set to * {@code true}. @@ -88,15 +110,17 @@ public class DirtiesContextTestExecutionListener extends AbstractTestExecutionLi } if (methodDirtiesContext || (classDirtiesContext && classMode == ClassMode.AFTER_EACH_TEST_METHOD)) { - dirtyContext(testContext); + HierarchyMode hierarchyMode = methodDirtiesContext ? testMethod.getAnnotation(annotationType).hierarchyMode() + : classDirtiesContextAnnotation.hierarchyMode(); + dirtyContext(testContext, hierarchyMode); } } /** - * If the test class of the supplied {@link TestContext test context} is + * If the test class of the supplied {@linkplain TestContext test context} is * annotated with {@link DirtiesContext @DirtiesContext}, the - * {@link ApplicationContext application context} of the test context will - * be {@link TestContext#markApplicationContextDirty() marked as dirty} , + * {@linkplain ApplicationContext application context} of the test context will + * be {@linkplain TestContext#markApplicationContextDirty() marked as dirty} , * and the * {@link DependencyInjectionTestExecutionListener#REINJECT_DEPENDENCIES_ATTRIBUTE * REINJECT_DEPENDENCIES_ATTRIBUTE} in the test context will be set to @@ -107,12 +131,15 @@ public class DirtiesContextTestExecutionListener extends AbstractTestExecutionLi Class testClass = testContext.getTestClass(); Assert.notNull(testClass, "The test class of the supplied TestContext must not be null"); - boolean dirtiesContext = testClass.isAnnotationPresent(DirtiesContext.class); + final Class annotationType = DirtiesContext.class; + + boolean dirtiesContext = testClass.isAnnotationPresent(annotationType); if (logger.isDebugEnabled()) { logger.debug("After test class: context [" + testContext + "], dirtiesContext [" + dirtiesContext + "]."); } if (dirtiesContext) { - dirtyContext(testContext); + HierarchyMode hierarchyMode = testClass.getAnnotation(annotationType).hierarchyMode(); + dirtyContext(testContext, hierarchyMode); } } diff --git a/spring-test/src/main/java/org/springframework/test/context/web/AbstractGenericWebContextLoader.java b/spring-test/src/main/java/org/springframework/test/context/web/AbstractGenericWebContextLoader.java index f344ae2eee..75c363dd18 100644 --- a/spring-test/src/main/java/org/springframework/test/context/web/AbstractGenericWebContextLoader.java +++ b/spring-test/src/main/java/org/springframework/test/context/web/AbstractGenericWebContextLoader.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. @@ -31,6 +31,7 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.MergedContextConfiguration; import org.springframework.test.context.support.AbstractContextLoader; +import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext; @@ -71,6 +72,12 @@ public abstract class AbstractGenericWebContextLoader extends AbstractContextLoa * *
        *
      • Creates a {@link GenericWebApplicationContext} instance.
      • + *
      • If the supplied {@code MergedContextConfiguration} references a + * {@linkplain MergedContextConfiguration#getParent() parent configuration}, + * the corresponding {@link MergedContextConfiguration#getParentApplicationContext() + * ApplicationContext} will be retrieved and + * {@linkplain GenericWebApplicationContext#setParent(ApplicationContext) set as the parent} + * for the context created by this method.
      • *
      • Delegates to {@link #configureWebResources} to create the * {@link MockServletContext} and set it in the {@code WebApplicationContext}.
      • *
      • Calls {@link #prepareContext} to allow for customizing the context @@ -107,6 +114,11 @@ public abstract class AbstractGenericWebContextLoader extends AbstractContextLoa } GenericWebApplicationContext context = new GenericWebApplicationContext(); + + ApplicationContext parent = mergedConfig.getParentApplicationContext(); + if (parent != null) { + context.setParent(parent); + } configureWebResources(context, webMergedConfig); prepareContext(context, webMergedConfig); customizeBeanFactory(context.getDefaultListableBeanFactory(), webMergedConfig); @@ -119,9 +131,20 @@ public abstract class AbstractGenericWebContextLoader extends AbstractContextLoa } /** - * Configures web resources for the supplied web application context. + * Configures web resources for the supplied web application context (WAC). * - *

        Implementation details: + *

        Implementation Details

        + * + *

        If the supplied WAC has no parent or its parent is not a WAC, the + * supplied WAC will be configured as the Root WAC (see "Root WAC + * Configuration" below). + * + *

        Otherwise the context hierarchy of the supplied WAC will be traversed + * to find the top-most WAC (i.e., the root); and the {@link ServletContext} + * of the Root WAC will be set as the {@code ServletContext} for the supplied + * WAC. + * + *

        Root WAC Configuration

        * *
          *
        • The resource base path is retrieved from the supplied @@ -146,13 +169,33 @@ public abstract class AbstractGenericWebContextLoader extends AbstractContextLoa protected void configureWebResources(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) { - String resourceBasePath = webMergedConfig.getResourceBasePath(); - ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() - : new FileSystemResourceLoader(); + ApplicationContext parent = context.getParent(); - ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader); - servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); - context.setServletContext(servletContext); + // if the WAC has no parent or the parent is not a WAC, set the WAC as + // the Root WAC: + if (parent == null || (!(parent instanceof WebApplicationContext))) { + String resourceBasePath = webMergedConfig.getResourceBasePath(); + ResourceLoader resourceLoader = resourceBasePath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX) ? new DefaultResourceLoader() + : new FileSystemResourceLoader(); + + ServletContext servletContext = new MockServletContext(resourceBasePath, resourceLoader); + servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); + context.setServletContext(servletContext); + } + else { + ServletContext servletContext = null; + + // find the Root WAC + while (parent != null) { + if (parent instanceof WebApplicationContext && !(parent.getParent() instanceof WebApplicationContext)) { + servletContext = ((WebApplicationContext) parent).getServletContext(); + break; + } + parent = parent.getParent(); + } + Assert.state(servletContext != null, "Failed to find Root WebApplicationContext in the context hierarchy"); + context.setServletContext(servletContext); + } } /** diff --git a/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java b/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java index b87c987dac..7858d9201f 100644 --- a/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java +++ b/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java @@ -69,6 +69,7 @@ public class ServletTestExecutionListener extends AbstractTestExecutionListener * @see TestExecutionListener#prepareTestInstance(TestContext) * @see #setUpRequestContextIfNecessary(TestContext) */ + @SuppressWarnings("javadoc") public void prepareTestInstance(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); } @@ -80,6 +81,7 @@ public class ServletTestExecutionListener extends AbstractTestExecutionListener * @see TestExecutionListener#beforeTestMethod(TestContext) * @see #setUpRequestContextIfNecessary(TestContext) */ + @SuppressWarnings("javadoc") public void beforeTestMethod(TestContext testContext) throws Exception { setUpRequestContextIfNecessary(testContext); } diff --git a/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java index 8e0e0494ad..58e8b38607 100644 --- a/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.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,6 +21,7 @@ import java.util.Set; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.style.ToStringCreator; +import org.springframework.test.context.CacheAwareContextLoaderDelegate; import org.springframework.test.context.ContextLoader; import org.springframework.test.context.MergedContextConfiguration; import org.springframework.util.ObjectUtils; @@ -77,7 +78,11 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration { * @param activeProfiles the merged active bean definition profiles * @param resourceBasePath the resource path to the root directory of the web application * @param contextLoader the resolved {@code ContextLoader} + * @see #WebMergedContextConfiguration(Class, String[], Class[], Set, String[], String, ContextLoader, CacheAwareContextLoaderDelegate, MergedContextConfiguration) + * @deprecated as of Spring 3.2.2, use + * {@link #WebMergedContextConfiguration(Class, String[], Class[], Set, String[], String, ContextLoader, CacheAwareContextLoaderDelegate, MergedContextConfiguration)} instead. */ + @Deprecated public WebMergedContextConfiguration( Class testClass, String[] locations, @@ -85,7 +90,45 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration { Set>> contextInitializerClasses, String[] activeProfiles, String resourceBasePath, ContextLoader contextLoader) { - super(testClass, locations, classes, contextInitializerClasses, activeProfiles, contextLoader); + this(testClass, locations, classes, contextInitializerClasses, activeProfiles, resourceBasePath, contextLoader, + null, null); + } + + /** + * Create a new {@code WebMergedContextConfiguration} instance for the + * supplied test class, resource locations, annotated classes, context + * initializers, active profiles, resource base path, and {@code ContextLoader}. + * + *

          If a {@code null} value is supplied for {@code locations}, + * {@code classes}, or {@code activeProfiles} an empty array will + * be stored instead. If a {@code null} value is supplied for the + * {@code contextInitializerClasses} an empty set will be stored instead. + * If an empty value is supplied for the {@code resourceBasePath} + * an empty string will be used. Furthermore, active profiles will be sorted, + * and duplicate profiles will be removed. + * + * @param testClass the test class for which the configuration was merged + * @param locations the merged resource locations + * @param classes the merged annotated classes + * @param contextInitializerClasses the merged context initializer classes + * @param activeProfiles the merged active bean definition profiles + * @param resourceBasePath the resource path to the root directory of the web application + * @param contextLoader the resolved {@code ContextLoader} + * @param cacheAwareContextLoaderDelegate a cache-aware context loader + * delegate with which to retrieve the parent context + * @param parent the parent configuration or {@code null} if there is no parent + * @since 3.2.2 + */ + public WebMergedContextConfiguration( + Class testClass, + String[] locations, + Class[] classes, + Set>> contextInitializerClasses, + String[] activeProfiles, String resourceBasePath, ContextLoader contextLoader, + CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate, MergedContextConfiguration parent) { + + super(testClass, locations, classes, contextInitializerClasses, activeProfiles, contextLoader, + cacheAwareContextLoaderDelegate, parent); this.resourceBasePath = !StringUtils.hasText(resourceBasePath) ? "" : resourceBasePath; } @@ -118,8 +161,9 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration { * {@linkplain #getClasses() annotated classes}, * {@linkplain #getContextInitializerClasses() context initializer classes}, * {@linkplain #getActiveProfiles() active profiles}, - * {@linkplain #getResourceBasePath() resource base path}, and the fully - * qualified names of their {@link #getContextLoader() ContextLoaders}. + * {@linkplain #getResourceBasePath() resource base path}, + * {@linkplain #getParent() parents}, and the fully qualified names of their + * {@link #getContextLoader() ContextLoaders}. */ @Override public boolean equals(Object obj) { @@ -141,8 +185,9 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration { * {@linkplain #getLocations() locations}, {@linkplain #getClasses() annotated classes}, * {@linkplain #getContextInitializerClasses() context initializer classes}, * {@linkplain #getActiveProfiles() active profiles}, - * {@linkplain #getResourceBasePath() resource base path}, and the name of the - * {@link #getContextLoader() ContextLoader}. + * {@linkplain #getResourceBasePath() resource base path}, the name of the + * {@link #getContextLoader() ContextLoader}, and the + * {@linkplain #getParent() parent configuration}. */ @Override public String toString() { @@ -154,6 +199,7 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration { .append("activeProfiles", ObjectUtils.nullSafeToString(getActiveProfiles()))// .append("resourceBasePath", getResourceBasePath())// .append("contextLoader", nullSafeToString(getContextLoader()))// + .append("parent", getParent())// .toString(); } diff --git a/spring-test/src/test/java/org/springframework/test/context/ContextCacheTests.java b/spring-test/src/test/java/org/springframework/test/context/ContextCacheTests.java new file mode 100644 index 0000000000..eb1c39a908 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/ContextCacheTests.java @@ -0,0 +1,329 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.annotation.DirtiesContext.HierarchyMode; +import org.springframework.test.context.support.AnnotationConfigContextLoader; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.junit.Assert.*; +import static org.springframework.test.context.SpringRunnerContextCacheTests.*; + +/** + * Integration tests for verifying proper behavior of the {@link ContextCache} in + * conjunction with cache keys used in {@link TestContext}. + * + * @author Sam Brannen + * @since 3.1 + * @see SpringRunnerContextCacheTests + */ +public class ContextCacheTests { + + private ContextCache contextCache = new ContextCache(); + + + @Before + public void initialCacheState() { + assertContextCacheStatistics(contextCache, "initial state", 0, 0, 0); + assertParentContextCount(0); + } + + private void assertParentContextCount(int expected) { + assertEquals("parent context count", expected, contextCache.getParentContextCount()); + } + + private MergedContextConfiguration getMergedContextConfiguration(TestContext testContext) { + return (MergedContextConfiguration) ReflectionTestUtils.getField(testContext, "mergedContextConfiguration"); + } + + private ApplicationContext loadContext(Class testClass) { + TestContext testContext = new TestContext(testClass, contextCache); + return testContext.getApplicationContext(); + } + + private void loadCtxAndAssertStats(Class testClass, int expectedSize, int expectedHitCount, int expectedMissCount) { + assertNotNull(loadContext(testClass)); + assertContextCacheStatistics(contextCache, testClass.getName(), expectedSize, expectedHitCount, + expectedMissCount); + } + + @Test + public void verifyCacheKeyIsBasedOnContextLoader() { + loadCtxAndAssertStats(AnnotationConfigContextLoaderTestCase.class, 1, 0, 1); + loadCtxAndAssertStats(AnnotationConfigContextLoaderTestCase.class, 1, 1, 1); + loadCtxAndAssertStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 1, 2); + loadCtxAndAssertStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 2, 2); + loadCtxAndAssertStats(AnnotationConfigContextLoaderTestCase.class, 2, 3, 2); + loadCtxAndAssertStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 4, 2); + } + + @Test + public void verifyCacheKeyIsBasedOnActiveProfiles() { + loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 0, 1); + loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 1, 1); + // Profiles {foo, bar} should hash to the same as {bar,foo} + loadCtxAndAssertStats(BarFooProfilesTestCase.class, 1, 2, 1); + loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 3, 1); + loadCtxAndAssertStats(FooBarProfilesTestCase.class, 1, 4, 1); + loadCtxAndAssertStats(BarFooProfilesTestCase.class, 1, 5, 1); + } + + @Test + public void verifyCacheBehaviorForContextHierarchies() { + int size = 0; + int hits = 0; + int misses = 0; + + // Level 1 + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel1TestCase.class, ++size, hits, ++misses); + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel1TestCase.class, size, ++hits, misses); + + // Level 2 + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel2TestCase.class, ++size /* L2 */, ++hits /* L1 */, + ++misses /* L2 */); + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel2TestCase.class, size, ++hits /* L2 */, misses); + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel2TestCase.class, size, ++hits /* L2 */, misses); + + // Level 3-A + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3aTestCase.class, ++size /* L3A */, ++hits /* L2 */, + ++misses /* L3A */); + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3aTestCase.class, size, ++hits /* L3A */, misses); + + // Level 3-B + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3bTestCase.class, ++size /* L3B */, ++hits /* L2 */, + ++misses /* L3B */); + loadCtxAndAssertStats(ClassHierarchyContextHierarchyLevel3bTestCase.class, size, ++hits /* L3B */, misses); + } + + @Test + public void removeContextHierarchyCacheLevel1() { + + // Load Level 3-A + TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); + testContext3a.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); + assertParentContextCount(2); + + // Load Level 3-B + TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); + testContext3b.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); + assertParentContextCount(2); + + // Remove Level 1 + // Should also remove Levels 2, 3-A, and 3-B, leaving nothing. + contextCache.remove(getMergedContextConfiguration(testContext3a).getParent().getParent(), + HierarchyMode.CURRENT_LEVEL); + assertContextCacheStatistics(contextCache, "removed level 1", 0, 1, 4); + assertParentContextCount(0); + } + + @Test + public void removeContextHierarchyCacheLevel1WithExhaustiveMode() { + + // Load Level 3-A + TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); + testContext3a.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); + assertParentContextCount(2); + + // Load Level 3-B + TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); + testContext3b.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); + assertParentContextCount(2); + + // Remove Level 1 + // Should also remove Levels 2, 3-A, and 3-B, leaving nothing. + contextCache.remove(getMergedContextConfiguration(testContext3a).getParent().getParent(), + HierarchyMode.EXHAUSTIVE); + assertContextCacheStatistics(contextCache, "removed level 1", 0, 1, 4); + assertParentContextCount(0); + } + + @Test + public void removeContextHierarchyCacheLevel2() { + + // Load Level 3-A + TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); + testContext3a.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); + assertParentContextCount(2); + + // Load Level 3-B + TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); + testContext3b.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); + assertParentContextCount(2); + + // Remove Level 2 + // Should also remove Levels 3-A and 3-B, leaving only Level 1 as a context in the + // cache but also removing the Level 1 hierarchy since all children have been + // removed. + contextCache.remove(getMergedContextConfiguration(testContext3a).getParent(), HierarchyMode.CURRENT_LEVEL); + assertContextCacheStatistics(contextCache, "removed level 2", 1, 1, 4); + assertParentContextCount(0); + } + + @Test + public void removeContextHierarchyCacheLevel2WithExhaustiveMode() { + + // Load Level 3-A + TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); + testContext3a.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); + assertParentContextCount(2); + + // Load Level 3-B + TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); + testContext3b.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); + assertParentContextCount(2); + + // Remove Level 2 + // Should wipe the cache + contextCache.remove(getMergedContextConfiguration(testContext3a).getParent(), HierarchyMode.EXHAUSTIVE); + assertContextCacheStatistics(contextCache, "removed level 2", 0, 1, 4); + assertParentContextCount(0); + } + + @Test + public void removeContextHierarchyCacheLevel3Then2() { + + // Load Level 3-A + TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); + testContext3a.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); + assertParentContextCount(2); + + // Load Level 3-B + TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); + testContext3b.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); + assertParentContextCount(2); + + // Remove Level 3-A + contextCache.remove(getMergedContextConfiguration(testContext3a), HierarchyMode.CURRENT_LEVEL); + assertContextCacheStatistics(contextCache, "removed level 3-A", 3, 1, 4); + assertParentContextCount(2); + + // Remove Level 2 + // Should also remove Level 3-B, leaving only Level 1. + contextCache.remove(getMergedContextConfiguration(testContext3b).getParent(), HierarchyMode.CURRENT_LEVEL); + assertContextCacheStatistics(contextCache, "removed level 2", 1, 1, 4); + assertParentContextCount(0); + } + + @Test + public void removeContextHierarchyCacheLevel3Then2WithExhaustiveMode() { + + // Load Level 3-A + TestContext testContext3a = new TestContext(ClassHierarchyContextHierarchyLevel3aTestCase.class, contextCache); + testContext3a.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A", 3, 0, 3); + assertParentContextCount(2); + + // Load Level 3-B + TestContext testContext3b = new TestContext(ClassHierarchyContextHierarchyLevel3bTestCase.class, contextCache); + testContext3b.getApplicationContext(); + assertContextCacheStatistics(contextCache, "level 3, A and B", 4, 1, 4); + assertParentContextCount(2); + + // Remove Level 3-A + // Should wipe the cache. + contextCache.remove(getMergedContextConfiguration(testContext3a), HierarchyMode.EXHAUSTIVE); + assertContextCacheStatistics(contextCache, "removed level 3-A", 0, 1, 4); + assertParentContextCount(0); + + // Remove Level 2 + // Should not actually do anything since the cache was cleared in the + // previous step. So the stats should remain the same. + contextCache.remove(getMergedContextConfiguration(testContext3b).getParent(), HierarchyMode.EXHAUSTIVE); + assertContextCacheStatistics(contextCache, "removed level 2", 0, 1, 4); + assertParentContextCount(0); + } + + + @Configuration + static class Config { + } + + @ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class) + private static class AnnotationConfigContextLoaderTestCase { + } + + @ContextConfiguration(classes = Config.class, loader = CustomAnnotationConfigContextLoader.class) + private static class CustomAnnotationConfigContextLoaderTestCase { + } + + private static class CustomAnnotationConfigContextLoader extends AnnotationConfigContextLoader { + } + + @ActiveProfiles({ "foo", "bar" }) + @ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class) + private static class FooBarProfilesTestCase { + } + + @ActiveProfiles({ "bar", "foo" }) + @ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class) + private static class BarFooProfilesTestCase { + } + + @ContextHierarchy({ @ContextConfiguration }) + private static class ClassHierarchyContextHierarchyLevel1TestCase { + + @Configuration + static class Level1Config { + + } + } + + @ContextHierarchy({ @ContextConfiguration }) + private static class ClassHierarchyContextHierarchyLevel2TestCase extends + ClassHierarchyContextHierarchyLevel1TestCase { + + @Configuration + static class Level2Config { + + } + } + + @ContextHierarchy({ @ContextConfiguration }) + private static class ClassHierarchyContextHierarchyLevel3aTestCase extends + ClassHierarchyContextHierarchyLevel2TestCase { + + @Configuration + static class Level3aConfig { + + } + } + + @ContextHierarchy({ @ContextConfiguration }) + private static class ClassHierarchyContextHierarchyLevel3bTestCase extends + ClassHierarchyContextHierarchyLevel2TestCase { + + @Configuration + static class Level3bConfig { + + } + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java new file mode 100644 index 0000000000..3026e3a0a9 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/ContextHierarchyDirtiesContextTests.java @@ -0,0 +1,212 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context; + +import org.junit.After; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.HierarchyMode; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +/** + * Integration tests that verify proper behavior of {@link DirtiesContext @DirtiesContext} + * in conjunction with context hierarchies configured via {@link ContextHierarchy @ContextHierarchy}. + * + * @author Sam Brannen + * @author Tadaya Tsuyukubo + * @since 3.2.2 + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class ContextHierarchyDirtiesContextTests { + + private static ApplicationContext context; + + + @After + public void cleanUp() { + ContextHierarchyDirtiesContextTests.context = null; + } + + @Test + public void classLevelDirtiesContextWithCurrentLevelHierarchyMode() { + runTestAndVerifyHierarchies(ClassLevelDirtiesContextWithCurrentLevelModeTestCase.class, true, true, false); + } + + @Test + public void classLevelDirtiesContextWithExhaustiveHierarchyMode() { + runTestAndVerifyHierarchies(ClassLevelDirtiesContextWithExhaustiveModeTestCase.class, false, false, false); + } + + @Test + public void methodLevelDirtiesContextWithCurrentLevelHierarchyMode() { + runTestAndVerifyHierarchies(MethodLevelDirtiesContextWithCurrentLevelModeTestCase.class, true, true, false); + } + + @Test + public void methodLevelDirtiesContextWithExhaustiveHierarchyMode() { + runTestAndVerifyHierarchies(MethodLevelDirtiesContextWithExhaustiveModeTestCase.class, false, false, false); + } + + private void runTestAndVerifyHierarchies(Class testClass, boolean isFooContextActive, + boolean isBarContextActive, boolean isBazContextActive) { + + JUnitCore jUnitCore = new JUnitCore(); + Result result = jUnitCore.run(testClass); + assertTrue("all tests passed", result.wasSuccessful()); + + assertThat(ContextHierarchyDirtiesContextTests.context, notNullValue()); + + ConfigurableApplicationContext bazContext = (ConfigurableApplicationContext) ContextHierarchyDirtiesContextTests.context; + assertEquals("baz", bazContext.getBean("bean", String.class)); + assertThat("bazContext#isActive()", bazContext.isActive(), is(isBazContextActive)); + + ConfigurableApplicationContext barContext = (ConfigurableApplicationContext) bazContext.getParent(); + assertThat(barContext, notNullValue()); + assertEquals("bar", barContext.getBean("bean", String.class)); + assertThat("barContext#isActive()", barContext.isActive(), is(isBarContextActive)); + + ConfigurableApplicationContext fooContext = (ConfigurableApplicationContext) barContext.getParent(); + assertThat(fooContext, notNullValue()); + assertEquals("foo", fooContext.getBean("bean", String.class)); + assertThat("fooContext#isActive()", fooContext.isActive(), is(isFooContextActive)); + } + + + // ------------------------------------------------------------------------- + + @RunWith(SpringJUnit4ClassRunner.class) + @ContextHierarchy(@ContextConfiguration(name = "foo")) + static abstract class FooTestCase implements ApplicationContextAware { + + @Configuration + static class Config { + + @Bean + public String bean() { + return "foo"; + } + } + + + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + ContextHierarchyDirtiesContextTests.context = applicationContext; + } + } + + @ContextHierarchy(@ContextConfiguration(name = "bar")) + static abstract class BarTestCase extends FooTestCase { + + @Configuration + static class Config { + + @Bean + public String bean() { + return "bar"; + } + } + } + + @ContextHierarchy(@ContextConfiguration(name = "baz")) + static abstract class BazTestCase extends BarTestCase { + + @Configuration + static class Config { + + @Bean + public String bean() { + return "baz"; + } + } + } + + // ------------------------------------------------------------------------- + + /** + * {@link DirtiesContext} is declared at the class level, without specifying + * the {@link DirtiesContext.HierarchyMode}. + *

          After running this test class, the context cache should be exhaustively + * cleared beginning from the current context hierarchy, upwards to the highest + * parent context, and then back down through all subhierarchies of the parent + * context. + */ + @DirtiesContext + public static class ClassLevelDirtiesContextWithExhaustiveModeTestCase extends BazTestCase { + + @Test + public void test() { + } + } + + /** + * {@link DirtiesContext} is declared at the class level, specifying the + * {@link DirtiesContext.HierarchyMode#CURRENT_LEVEL CURRENT_LEVEL} hierarchy mode. + *

          After running this test class, the context cache should be cleared + * beginning from the current context hierarchy and down through all subhierarchies. + */ + @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL) + public static class ClassLevelDirtiesContextWithCurrentLevelModeTestCase extends BazTestCase { + + @Test + public void test() { + } + } + + /** + * {@link DirtiesContext} is declared at the method level, without specifying + * the {@link DirtiesContext.HierarchyMode}. + *

          After running this test class, the context cache should be exhaustively + * cleared beginning from the current context hierarchy, upwards to the highest + * parent context, and then back down through all subhierarchies of the parent + * context. + */ + public static class MethodLevelDirtiesContextWithExhaustiveModeTestCase extends BazTestCase { + + @Test + @DirtiesContext + public void test() { + } + } + + /** + * {@link DirtiesContext} is declared at the method level, specifying the + * {@link DirtiesContext.HierarchyMode#CURRENT_LEVEL CURRENT_LEVEL} hierarchy mode. + *

          After running this test class, the context cache should be cleared + * beginning from the current context hierarchy and down through all subhierarchies. + */ + public static class MethodLevelDirtiesContextWithCurrentLevelModeTestCase extends BazTestCase { + + @Test + @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL) + public void test() { + } + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/ContextLoaderUtilsTests.java b/spring-test/src/test/java/org/springframework/test/context/ContextLoaderUtilsTests.java index fdfa4eb4ac..ecedda4ddf 100644 --- a/spring-test/src/test/java/org/springframework/test/context/ContextLoaderUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/ContextLoaderUtilsTests.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,16 @@ package org.springframework.test.context; +import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.springframework.test.context.ContextLoaderUtils.*; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.Set; import org.junit.Test; @@ -105,6 +108,233 @@ public class ContextLoaderUtilsTests { assertEquals(expectedInitializerClasses, mergedConfig.getContextInitializerClasses()); } + private void debugConfigAttributes(List configAttributesList) { + // for (ContextConfigurationAttributes configAttributes : configAttributesList) { + // System.err.println(configAttributes); + // } + } + + @Test(expected = IllegalStateException.class) + public void resolveContextHierarchyAttributesForSingleTestClassWithContextConfigurationAndContextHierarchy() { + resolveContextHierarchyAttributes(SingleTestClassWithContextConfigurationAndContextHierarchy.class); + } + + @Test + public void resolveContextHierarchyAttributesForSingleTestClassWithImplicitSingleLevelContextHierarchy() { + List> hierarchyAttributes = resolveContextHierarchyAttributes(BareAnnotations.class); + assertEquals(1, hierarchyAttributes.size()); + List configAttributesList = hierarchyAttributes.get(0); + assertEquals(1, configAttributesList.size()); + debugConfigAttributes(configAttributesList); + } + + @Test + public void resolveContextHierarchyAttributesForSingleTestClassWithSingleLevelContextHierarchy() { + List> hierarchyAttributes = resolveContextHierarchyAttributes(SingleTestClassWithSingleLevelContextHierarchy.class); + assertEquals(1, hierarchyAttributes.size()); + List configAttributesList = hierarchyAttributes.get(0); + assertEquals(1, configAttributesList.size()); + debugConfigAttributes(configAttributesList); + } + + @Test + public void resolveContextHierarchyAttributesForSingleTestClassWithTripleLevelContextHierarchy() { + List> hierarchyAttributes = resolveContextHierarchyAttributes(SingleTestClassWithTripleLevelContextHierarchy.class); + assertEquals(1, hierarchyAttributes.size()); + List configAttributesList = hierarchyAttributes.get(0); + assertEquals(3, configAttributesList.size()); + debugConfigAttributes(configAttributesList); + } + + @Test + public void resolveContextHierarchyAttributesForTestClassHierarchyWithSingleLevelContextHierarchies() { + List> hierarchyAttributes = resolveContextHierarchyAttributes(TestClass3WithSingleLevelContextHierarchy.class); + assertEquals(3, hierarchyAttributes.size()); + + List configAttributesListClassLevel1 = hierarchyAttributes.get(0); + debugConfigAttributes(configAttributesListClassLevel1); + assertEquals(1, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("one.xml")); + + List configAttributesListClassLevel2 = hierarchyAttributes.get(1); + debugConfigAttributes(configAttributesListClassLevel2); + assertEquals(1, configAttributesListClassLevel2.size()); + assertArrayEquals(new String[] { "two-A.xml", "two-B.xml" }, + configAttributesListClassLevel2.get(0).getLocations()); + + List configAttributesListClassLevel3 = hierarchyAttributes.get(2); + debugConfigAttributes(configAttributesListClassLevel3); + assertEquals(1, configAttributesListClassLevel3.size()); + assertThat(configAttributesListClassLevel3.get(0).getLocations()[0], equalTo("three.xml")); + } + + @Test + public void resolveContextHierarchyAttributesForTestClassHierarchyWithBareContextConfigurationInSubclass() { + List> hierarchyAttributes = resolveContextHierarchyAttributes(TestClass2WithBareContextConfigurationInSubclass.class); + assertEquals(2, hierarchyAttributes.size()); + + List configAttributesListClassLevel1 = hierarchyAttributes.get(0); + debugConfigAttributes(configAttributesListClassLevel1); + assertEquals(1, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("one.xml")); + + List configAttributesListClassLevel2 = hierarchyAttributes.get(1); + debugConfigAttributes(configAttributesListClassLevel2); + assertEquals(1, configAttributesListClassLevel2.size()); + assertThat(configAttributesListClassLevel2.get(0).getLocations()[0], equalTo("two.xml")); + } + + @Test + public void resolveContextHierarchyAttributesForTestClassHierarchyWithBareContextConfigurationInSuperclass() { + List> hierarchyAttributes = resolveContextHierarchyAttributes(TestClass2WithBareContextConfigurationInSuperclass.class); + assertEquals(2, hierarchyAttributes.size()); + + List configAttributesListClassLevel1 = hierarchyAttributes.get(0); + debugConfigAttributes(configAttributesListClassLevel1); + assertEquals(1, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("one.xml")); + + List configAttributesListClassLevel2 = hierarchyAttributes.get(1); + debugConfigAttributes(configAttributesListClassLevel2); + assertEquals(1, configAttributesListClassLevel2.size()); + assertThat(configAttributesListClassLevel2.get(0).getLocations()[0], equalTo("two.xml")); + } + + @Test + public void resolveContextHierarchyAttributesForTestClassHierarchyWithMultiLevelContextHierarchies() { + List> hierarchyAttributes = resolveContextHierarchyAttributes(TestClass3WithMultiLevelContextHierarchy.class); + assertEquals(3, hierarchyAttributes.size()); + + List configAttributesListClassLevel1 = hierarchyAttributes.get(0); + debugConfigAttributes(configAttributesListClassLevel1); + assertEquals(2, configAttributesListClassLevel1.size()); + assertThat(configAttributesListClassLevel1.get(0).getLocations()[0], equalTo("1-A.xml")); + assertThat(configAttributesListClassLevel1.get(1).getLocations()[0], equalTo("1-B.xml")); + + List configAttributesListClassLevel2 = hierarchyAttributes.get(1); + debugConfigAttributes(configAttributesListClassLevel2); + assertEquals(2, configAttributesListClassLevel2.size()); + assertThat(configAttributesListClassLevel2.get(0).getLocations()[0], equalTo("2-A.xml")); + assertThat(configAttributesListClassLevel2.get(1).getLocations()[0], equalTo("2-B.xml")); + + List configAttributesListClassLevel3 = hierarchyAttributes.get(2); + debugConfigAttributes(configAttributesListClassLevel3); + assertEquals(3, configAttributesListClassLevel3.size()); + assertThat(configAttributesListClassLevel3.get(0).getLocations()[0], equalTo("3-A.xml")); + assertThat(configAttributesListClassLevel3.get(1).getLocations()[0], equalTo("3-B.xml")); + assertThat(configAttributesListClassLevel3.get(2).getLocations()[0], equalTo("3-C.xml")); + } + + private void assertContextConfigEntriesAreNotUnique(Class testClass) { + try { + resolveContextHierarchyAttributes(testClass); + fail("Should throw an IllegalStateException"); + } + catch (IllegalStateException e) { + String msg = String.format( + "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] must define unique contexts to load.", + testClass.getName()); + assertEquals(msg, e.getMessage()); + } + } + + @Test + public void resolveContextHierarchyAttributesForSingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig() { + assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig.class); + } + + @Test + public void resolveContextHierarchyAttributesForSingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig() { + assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig.class); + } + + @Test + public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchies() { + Map> map = buildContextHierarchyMap(TestClass3WithMultiLevelContextHierarchy.class); + + assertThat(map.size(), is(3)); + assertThat(map.keySet(), hasItems("alpha", "beta", "gamma")); + + List alphaConfig = map.get("alpha"); + assertThat(alphaConfig.size(), is(3)); + assertThat(alphaConfig.get(0).getLocations()[0], is("1-A.xml")); + assertThat(alphaConfig.get(1).getLocations()[0], is("2-A.xml")); + assertThat(alphaConfig.get(2).getLocations()[0], is("3-A.xml")); + + List betaConfig = map.get("beta"); + assertThat(betaConfig.size(), is(3)); + assertThat(betaConfig.get(0).getLocations()[0], is("1-B.xml")); + assertThat(betaConfig.get(1).getLocations()[0], is("2-B.xml")); + assertThat(betaConfig.get(2).getLocations()[0], is("3-B.xml")); + + List gammaConfig = map.get("gamma"); + assertThat(gammaConfig.size(), is(1)); + assertThat(gammaConfig.get(0).getLocations()[0], is("3-C.xml")); + } + + @Test + public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchiesAndUnnamedConfig() { + Map> map = buildContextHierarchyMap(TestClass3WithMultiLevelContextHierarchyAndUnnamedConfig.class); + + String level1 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 1; + String level2 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 2; + String level3 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 3; + String level4 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 4; + String level5 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 5; + String level6 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 6; + String level7 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 7; + + assertThat(map.size(), is(7)); + assertThat(map.keySet(), hasItems(level1, level2, level3, level4, level5, level6, level7)); + + List level1Config = map.get(level1); + assertThat(level1Config.size(), is(1)); + assertThat(level1Config.get(0).getLocations()[0], is("1-A.xml")); + + List level2Config = map.get(level2); + assertThat(level2Config.size(), is(1)); + assertThat(level2Config.get(0).getLocations()[0], is("1-B.xml")); + + List level3Config = map.get(level3); + assertThat(level3Config.size(), is(1)); + assertThat(level3Config.get(0).getLocations()[0], is("2-A.xml")); + + // ... + + List level7Config = map.get(level7); + assertThat(level7Config.size(), is(1)); + assertThat(level7Config.get(0).getLocations()[0], is("3-C.xml")); + } + + @Test + public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchiesAndPartiallyNamedConfig() { + Map> map = buildContextHierarchyMap(TestClass2WithMultiLevelContextHierarchyAndPartiallyNamedConfig.class); + + String level1 = "parent"; + String level2 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 2; + String level3 = GENERATED_CONTEXT_HIERARCHY_LEVEL_PREFIX + 3; + + assertThat(map.size(), is(3)); + assertThat(map.keySet(), hasItems(level1, level2, level3)); + Iterator levels = map.keySet().iterator(); + assertThat(levels.next(), is(level1)); + assertThat(levels.next(), is(level2)); + assertThat(levels.next(), is(level3)); + + List level1Config = map.get(level1); + assertThat(level1Config.size(), is(2)); + assertThat(level1Config.get(0).getLocations()[0], is("1-A.xml")); + assertThat(level1Config.get(1).getLocations()[0], is("2-A.xml")); + + List level2Config = map.get(level2); + assertThat(level2Config.size(), is(1)); + assertThat(level2Config.get(0).getLocations()[0], is("1-B.xml")); + + List level3Config = map.get(level3); + assertThat(level3Config.size(), is(1)); + assertThat(level3Config.get(0).getLocations()[0], is("2-C.xml")); + } + @Test(expected = IllegalStateException.class) public void resolveConfigAttributesWithConflictingLocations() { resolveContextConfigurationAttributes(ConflictingLocations.class); @@ -155,13 +385,13 @@ public class ContextLoaderUtilsTests { @Test(expected = IllegalArgumentException.class) public void buildMergedConfigWithoutAnnotation() { - buildMergedContextConfiguration(Enigma.class, null); + buildMergedContextConfiguration(Enigma.class, null, null); } @Test public void buildMergedConfigWithBareAnnotations() { Class testClass = BareAnnotations.class; - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig( mergedConfig, @@ -173,7 +403,7 @@ public class ContextLoaderUtilsTests { @Test public void buildMergedConfigWithLocalAnnotationAndLocations() { Class testClass = LocationsFoo.class; - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, new String[] { "classpath:/foo.xml" }, EMPTY_CLASS_ARRAY, DelegatingSmartContextLoader.class); @@ -182,7 +412,7 @@ public class ContextLoaderUtilsTests { @Test public void buildMergedConfigWithLocalAnnotationAndClasses() { Class testClass = ClassesFoo.class; - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, new Class[] { FooConfig.class }, DelegatingSmartContextLoader.class); @@ -193,7 +423,7 @@ public class ContextLoaderUtilsTests { Class testClass = LocationsFoo.class; Class expectedContextLoaderClass = GenericPropertiesContextLoader.class; MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, - expectedContextLoaderClass.getName()); + expectedContextLoaderClass.getName(), null); assertMergedConfig(mergedConfig, testClass, new String[] { "classpath:/foo.xml" }, EMPTY_CLASS_ARRAY, expectedContextLoaderClass); @@ -204,7 +434,7 @@ public class ContextLoaderUtilsTests { Class testClass = ClassesFoo.class; Class expectedContextLoaderClass = GenericPropertiesContextLoader.class; MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, - expectedContextLoaderClass.getName()); + expectedContextLoaderClass.getName(), null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, new Class[] { FooConfig.class }, expectedContextLoaderClass); @@ -215,7 +445,7 @@ public class ContextLoaderUtilsTests { Class testClass = LocationsBar.class; String[] expectedLocations = new String[] { "/foo.xml", "/bar.xml" }; - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, expectedLocations, EMPTY_CLASS_ARRAY, AnnotationConfigContextLoader.class); } @@ -225,7 +455,7 @@ public class ContextLoaderUtilsTests { Class testClass = ClassesBar.class; Class[] expectedClasses = new Class[] { FooConfig.class, BarConfig.class }; - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses, AnnotationConfigContextLoader.class); } @@ -235,7 +465,7 @@ public class ContextLoaderUtilsTests { Class testClass = OverriddenLocationsBar.class; String[] expectedLocations = new String[] { "/bar.xml" }; - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, expectedLocations, EMPTY_CLASS_ARRAY, AnnotationConfigContextLoader.class); } @@ -245,7 +475,7 @@ public class ContextLoaderUtilsTests { Class testClass = OverriddenClassesBar.class; Class[] expectedClasses = new Class[] { BarConfig.class }; - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses, AnnotationConfigContextLoader.class); } @@ -258,7 +488,7 @@ public class ContextLoaderUtilsTests { = new HashSet>>(); expectedInitializerClasses.add(FooInitializer.class); - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses, expectedInitializerClasses, DelegatingSmartContextLoader.class); } @@ -272,7 +502,7 @@ public class ContextLoaderUtilsTests { expectedInitializerClasses.add(FooInitializer.class); expectedInitializerClasses.add(BarInitializer.class); - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses, expectedInitializerClasses, DelegatingSmartContextLoader.class); } @@ -285,7 +515,7 @@ public class ContextLoaderUtilsTests { = new HashSet>>(); expectedInitializerClasses.add(BarInitializer.class); - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses, expectedInitializerClasses, DelegatingSmartContextLoader.class); } @@ -298,7 +528,7 @@ public class ContextLoaderUtilsTests { = new HashSet>>(); expectedInitializerClasses.add(BarInitializer.class); - MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null); + MergedContextConfiguration mergedConfig = buildMergedContextConfiguration(testClass, null, null); assertMergedConfig(mergedConfig, testClass, EMPTY_STRING_ARRAY, expectedClasses, expectedInitializerClasses, DelegatingSmartContextLoader.class); } @@ -377,6 +607,8 @@ public class ContextLoaderUtilsTests { } + // ------------------------------------------------------------------------- + private static class Enigma { } @@ -475,4 +707,140 @@ public class ContextLoaderUtilsTests { private static class OverriddenInitializersAndClassesBar extends InitializersFoo { } + @ContextConfiguration("foo.xml") + @ContextHierarchy(@ContextConfiguration("bar.xml")) + private static class SingleTestClassWithContextConfigurationAndContextHierarchy { + } + + @ContextHierarchy(@ContextConfiguration("A.xml")) + private static class SingleTestClassWithSingleLevelContextHierarchy { + } + + @ContextHierarchy({// + // + @ContextConfiguration("A.xml"),// + @ContextConfiguration("B.xml"),// + @ContextConfiguration("C.xml") // + }) + private static class SingleTestClassWithTripleLevelContextHierarchy { + } + + @ContextHierarchy(@ContextConfiguration("one.xml")) + private static class TestClass1WithSingleLevelContextHierarchy { + } + + @ContextHierarchy(@ContextConfiguration({ "two-A.xml", "two-B.xml" })) + private static class TestClass2WithSingleLevelContextHierarchy extends TestClass1WithSingleLevelContextHierarchy { + } + + @ContextHierarchy(@ContextConfiguration("three.xml")) + private static class TestClass3WithSingleLevelContextHierarchy extends TestClass2WithSingleLevelContextHierarchy { + } + + @ContextConfiguration("one.xml") + private static class TestClass1WithBareContextConfigurationInSuperclass { + } + + @ContextHierarchy(@ContextConfiguration("two.xml")) + private static class TestClass2WithBareContextConfigurationInSuperclass extends + TestClass1WithBareContextConfigurationInSuperclass { + } + + @ContextHierarchy(@ContextConfiguration("one.xml")) + private static class TestClass1WithBareContextConfigurationInSubclass { + } + + @ContextConfiguration("two.xml") + private static class TestClass2WithBareContextConfigurationInSubclass extends + TestClass1WithBareContextConfigurationInSuperclass { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "1-A.xml", name = "alpha"),// + @ContextConfiguration(locations = "1-B.xml", name = "beta") // + }) + private static class TestClass1WithMultiLevelContextHierarchy { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "2-A.xml", name = "alpha"),// + @ContextConfiguration(locations = "2-B.xml", name = "beta") // + }) + private static class TestClass2WithMultiLevelContextHierarchy extends TestClass1WithMultiLevelContextHierarchy { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "3-A.xml", name = "alpha"),// + @ContextConfiguration(locations = "3-B.xml", name = "beta"),// + @ContextConfiguration(locations = "3-C.xml", name = "gamma") // + }) + private static class TestClass3WithMultiLevelContextHierarchy extends TestClass2WithMultiLevelContextHierarchy { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "1-A.xml"),// + @ContextConfiguration(locations = "1-B.xml") // + }) + private static class TestClass1WithMultiLevelContextHierarchyAndUnnamedConfig { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "2-A.xml"),// + @ContextConfiguration(locations = "2-B.xml") // + }) + private static class TestClass2WithMultiLevelContextHierarchyAndUnnamedConfig extends + TestClass1WithMultiLevelContextHierarchyAndUnnamedConfig { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "3-A.xml"),// + @ContextConfiguration(locations = "3-B.xml"),// + @ContextConfiguration(locations = "3-C.xml") // + }) + private static class TestClass3WithMultiLevelContextHierarchyAndUnnamedConfig extends + TestClass2WithMultiLevelContextHierarchyAndUnnamedConfig { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "1-A.xml", name = "parent"),// + @ContextConfiguration(locations = "1-B.xml") // + }) + private static class TestClass1WithMultiLevelContextHierarchyAndPartiallyNamedConfig { + } + + @ContextHierarchy({// + // + @ContextConfiguration(locations = "2-A.xml", name = "parent"),// + @ContextConfiguration(locations = "2-C.xml") // + }) + private static class TestClass2WithMultiLevelContextHierarchyAndPartiallyNamedConfig extends + TestClass1WithMultiLevelContextHierarchyAndPartiallyNamedConfig { + } + + @ContextHierarchy({ + // + @ContextConfiguration,// + @ContextConfiguration // + }) + private static class SingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig { + } + + @ContextHierarchy({ + // + @ContextConfiguration("foo.xml"),// + @ContextConfiguration(classes = BarConfig.class),// duplicate! + @ContextConfiguration("baz.xml"),// + @ContextConfiguration(classes = BarConfig.class),// duplicate! + @ContextConfiguration(loader = AnnotationConfigContextLoader.class) // + }) + private static class SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig { + } + } diff --git a/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java b/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java index 35b64fa432..863fd9da86 100644 --- a/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.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. @@ -76,7 +76,7 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, new AnnotationConfigContextLoader()); - assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode()); + assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); } @Test @@ -97,7 +97,7 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations2, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode()); + assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); } @Test @@ -118,7 +118,7 @@ public class MergedContextConfigurationTests { classes1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, classes2, EMPTY_STRING_ARRAY, loader); - assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode()); + assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); } @Test @@ -161,7 +161,7 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode()); + assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); } @Test @@ -197,15 +197,47 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader); - assertFalse(mergedConfig1.hashCode() == mergedConfig2.hashCode()); + assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + } + + /** + * @since 3.2.2 + */ + @Test + public void hashCodeWithSameParent() { + MergedContextConfiguration parent = new MergedContextConfiguration(getClass(), new String[] { "foo", "bar}" }, + EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); + + MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); + MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); + assertEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); + } + + /** + * @since 3.2.2 + */ + @Test + public void hashCodeWithDifferentParents() { + MergedContextConfiguration parent1 = new MergedContextConfiguration(getClass(), new String[] { "foo", "bar}" }, + EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); + MergedContextConfiguration parent2 = new MergedContextConfiguration(getClass(), new String[] { "baz", "quux" }, + EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); + + MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent1); + MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent2); + assertNotEquals(mergedConfig1.hashCode(), mergedConfig2.hashCode()); } @Test public void equalsBasics() { MergedContextConfiguration mergedConfig = new MergedContextConfiguration(null, null, null, null, null); - assertTrue(mergedConfig.equals(mergedConfig)); - assertFalse(mergedConfig.equals(null)); - assertFalse(mergedConfig.equals(new Integer(1))); + assertEquals(mergedConfig, mergedConfig); + assertNotEquals(mergedConfig, null); + assertNotEquals(mergedConfig, new Integer(1)); } @Test @@ -237,8 +269,8 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, new AnnotationConfigContextLoader()); - assertFalse(mergedConfig1.equals(mergedConfig2)); - assertFalse(mergedConfig2.equals(mergedConfig1)); + assertNotEquals(mergedConfig1, mergedConfig2); + assertNotEquals(mergedConfig2, mergedConfig1); } @Test @@ -259,8 +291,8 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations2, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); - assertFalse(mergedConfig1.equals(mergedConfig2)); - assertFalse(mergedConfig2.equals(mergedConfig1)); + assertNotEquals(mergedConfig1, mergedConfig2); + assertNotEquals(mergedConfig2, mergedConfig1); } @Test @@ -281,8 +313,8 @@ public class MergedContextConfigurationTests { classes1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, classes2, EMPTY_STRING_ARRAY, loader); - assertFalse(mergedConfig1.equals(mergedConfig2)); - assertFalse(mergedConfig2.equals(mergedConfig1)); + assertNotEquals(mergedConfig1, mergedConfig2); + assertNotEquals(mergedConfig2, mergedConfig1); } @Test @@ -325,8 +357,8 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, activeProfiles1, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader); - assertFalse(mergedConfig1.equals(mergedConfig2)); - assertFalse(mergedConfig2.equals(mergedConfig1)); + assertNotEquals(mergedConfig1, mergedConfig2); + assertNotEquals(mergedConfig2, mergedConfig1); } @Test @@ -362,8 +394,42 @@ public class MergedContextConfigurationTests { EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader); MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader); - assertFalse(mergedConfig1.equals(mergedConfig2)); - assertFalse(mergedConfig2.equals(mergedConfig1)); + assertNotEquals(mergedConfig1, mergedConfig2); + assertNotEquals(mergedConfig2, mergedConfig1); + } + + /** + * @since 3.2.2 + */ + @Test + public void equalsWithSameParent() { + MergedContextConfiguration parent = new MergedContextConfiguration(getClass(), new String[] { "foo", "bar}" }, + EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); + + MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); + MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent); + assertEquals(mergedConfig1, mergedConfig2); + assertEquals(mergedConfig2, mergedConfig1); + } + + /** + * @since 3.2.2 + */ + @Test + public void equalsWithDifferentParents() { + MergedContextConfiguration parent1 = new MergedContextConfiguration(getClass(), new String[] { "foo", "bar}" }, + EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); + MergedContextConfiguration parent2 = new MergedContextConfiguration(getClass(), new String[] { "baz", "quux" }, + EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader); + + MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent1); + MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY, + EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent2); + assertNotEquals(mergedConfig1, mergedConfig2); + assertNotEquals(mergedConfig2, mergedConfig1); } diff --git a/spring-test/src/test/java/org/springframework/test/context/SpringRunnerContextCacheTests.java b/spring-test/src/test/java/org/springframework/test/context/SpringRunnerContextCacheTests.java index d27e3ca50d..07f7383189 100644 --- a/spring-test/src/test/java/org/springframework/test/context/SpringRunnerContextCacheTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/SpringRunnerContextCacheTests.java @@ -44,7 +44,7 @@ import org.springframework.test.context.support.DirtiesContextTestExecutionListe * @author Sam Brannen * @author Juergen Hoeller * @since 2.5 - * @see TestContextCacheKeyTests + * @see ContextCacheTests */ @RunWith(OrderedMethodsSpringJUnit4ClassRunner.class) @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) diff --git a/spring-test/src/test/java/org/springframework/test/context/TestContextCacheKeyTests.java b/spring-test/src/test/java/org/springframework/test/context/TestContextCacheKeyTests.java deleted file mode 100644 index d765937940..0000000000 --- a/spring-test/src/test/java/org/springframework/test/context/TestContextCacheKeyTests.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.test.context; - -import static org.junit.Assert.assertNotNull; -import static org.springframework.test.context.SpringRunnerContextCacheTests.assertContextCacheStatistics; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.support.AnnotationConfigContextLoader; - -/** - * Unit tests for verifying proper behavior of the {@link ContextCache} in - * conjunction with cache keys used in {@link TestContext}. - * - * @author Sam Brannen - * @since 3.1 - * @see SpringRunnerContextCacheTests - */ -public class TestContextCacheKeyTests { - - private ContextCache contextCache = new ContextCache(); - - - @Before - public void initialCacheState() { - assertContextCacheStatistics(contextCache, "initial state", 0, 0, 0); - } - - private void loadAppCtxAndAssertCacheStats(Class testClass, int expectedSize, int expectedHitCount, - int expectedMissCount) { - TestContext testContext = new TestContext(testClass, contextCache); - ApplicationContext context = testContext.getApplicationContext(); - assertNotNull(context); - assertContextCacheStatistics(contextCache, testClass.getName(), expectedSize, expectedHitCount, - expectedMissCount); - } - - @Test - public void verifyCacheKeyIsBasedOnContextLoader() { - loadAppCtxAndAssertCacheStats(AnnotationConfigContextLoaderTestCase.class, 1, 0, 1); - loadAppCtxAndAssertCacheStats(AnnotationConfigContextLoaderTestCase.class, 1, 1, 1); - loadAppCtxAndAssertCacheStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 1, 2); - loadAppCtxAndAssertCacheStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 2, 2); - loadAppCtxAndAssertCacheStats(AnnotationConfigContextLoaderTestCase.class, 2, 3, 2); - loadAppCtxAndAssertCacheStats(CustomAnnotationConfigContextLoaderTestCase.class, 2, 4, 2); - } - - @Test - public void verifyCacheKeyIsBasedOnActiveProfiles() { - loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 0, 1); - loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 1, 1); - // Profiles {foo, bar} should hash to the same as {bar,foo} - loadAppCtxAndAssertCacheStats(BarFooProfilesTestCase.class, 1, 2, 1); - loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 3, 1); - loadAppCtxAndAssertCacheStats(FooBarProfilesTestCase.class, 1, 4, 1); - loadAppCtxAndAssertCacheStats(BarFooProfilesTestCase.class, 1, 5, 1); - } - - - @Configuration - static class Config { - } - - @ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class) - private static class AnnotationConfigContextLoaderTestCase { - } - - @ContextConfiguration(classes = Config.class, loader = CustomAnnotationConfigContextLoader.class) - private static class CustomAnnotationConfigContextLoaderTestCase { - } - - private static class CustomAnnotationConfigContextLoader extends AnnotationConfigContextLoader { - } - - @ActiveProfiles({ "foo", "bar" }) - @ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class) - private static class FooBarProfilesTestCase { - } - - @ActiveProfiles({ "bar", "foo" }) - @ContextConfiguration(classes = Config.class, loader = AnnotationConfigContextLoader.class) - private static class BarFooProfilesTestCase { - } - -} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java new file mode 100644 index 0000000000..716228c7c3 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelOneTests.java @@ -0,0 +1,96 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy({ +// + @ContextConfiguration(name = "parent", classes = ClassHierarchyWithMergedConfigLevelOneTests.AppConfig.class),// + @ContextConfiguration(name = "child", classes = ClassHierarchyWithMergedConfigLevelOneTests.UserConfig.class) // +}) +public class ClassHierarchyWithMergedConfigLevelOneTests { + + @Configuration + static class AppConfig { + + @Bean + public String parent() { + return "parent"; + } + } + + @Configuration + static class UserConfig { + + @Autowired + private AppConfig appConfig; + + + @Bean + public String user() { + return appConfig.parent() + " + user"; + } + + @Bean + public String beanFromUserConfig() { + return "from UserConfig"; + } + } + + + @Autowired + protected String parent; + + @Autowired + protected String user; + + @Autowired(required = false) + @Qualifier("beanFromUserConfig") + protected String beanFromUserConfig; + + @Autowired + protected ApplicationContext context; + + + @Test + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertEquals("parent", parent); + assertEquals("parent + user", user); + assertEquals("from UserConfig", beanFromUserConfig); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java new file mode 100644 index 0000000000..42a63413d2 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithMergedConfigLevelTwoTests.java @@ -0,0 +1,62 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration(name = "child", classes = ClassHierarchyWithMergedConfigLevelTwoTests.OrderConfig.class)) +public class ClassHierarchyWithMergedConfigLevelTwoTests extends ClassHierarchyWithMergedConfigLevelOneTests { + + @Configuration + static class OrderConfig { + + @Autowired + private ClassHierarchyWithMergedConfigLevelOneTests.UserConfig userConfig; + + @Bean + public String order() { + return userConfig.user() + " + order"; + } + } + + + @Autowired + private String order; + + + @Test + @Override + public void loadContextHierarchy() { + super.loadContextHierarchy(); + assertEquals("parent + user + order", order); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java new file mode 100644 index 0000000000..1f5f69a029 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/ClassHierarchyWithOverriddenConfigLevelTwoTests.java @@ -0,0 +1,73 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration(name = "child", classes = ClassHierarchyWithOverriddenConfigLevelTwoTests.TestUserConfig.class, inheritLocations = false)) +public class ClassHierarchyWithOverriddenConfigLevelTwoTests extends ClassHierarchyWithMergedConfigLevelOneTests { + + @Configuration + static class TestUserConfig { + + @Autowired + private ClassHierarchyWithMergedConfigLevelOneTests.AppConfig appConfig; + + + @Bean + public String user() { + return appConfig.parent() + " + test user"; + } + + @Bean + public String beanFromTestUserConfig() { + return "from TestUserConfig"; + } + } + + + @Autowired + private String beanFromTestUserConfig; + + + @Test + @Override + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertEquals("parent", parent); + assertEquals("parent + test user", user); + assertEquals("from TestUserConfig", beanFromTestUserConfig); + assertNull("Bean from UserConfig should not be present.", beanFromUserConfig); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java new file mode 100644 index 0000000000..95757b2cd7 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/DirtiesContextWithContextHierarchyTests.java @@ -0,0 +1,149 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import org.junit.Before; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.HierarchyMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.*; + +/** + * Integration tests that verify support for {@link DirtiesContext.HierarchyMode} + * in conjunction with context hierarchies configured via {@link ContextHierarchy}. + * + *

          Note that correct method execution order is essential, thus the use of + * {@link FixMethodOrder}. + * + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy({ @ContextConfiguration(classes = DirtiesContextWithContextHierarchyTests.ParentConfig.class), + @ContextConfiguration(classes = DirtiesContextWithContextHierarchyTests.ChildConfig.class) }) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DirtiesContextWithContextHierarchyTests { + + @Configuration + static class ParentConfig { + + @Bean + public StringBuffer foo() { + return new StringBuffer("foo"); + } + + @Bean + public StringBuffer baz() { + return new StringBuffer("baz-parent"); + } + } + + @Configuration + static class ChildConfig { + + @Bean + public StringBuffer baz() { + return new StringBuffer("baz-child"); + } + } + + + @Autowired + private StringBuffer foo; + + @Autowired + private StringBuffer baz; + + @Autowired + private ApplicationContext context; + + + // ------------------------------------------------------------------------- + + private void reverseStringBuffers() { + foo.reverse(); + baz.reverse(); + } + + private void assertOriginalState() { + assertCleanParentContext(); + assertCleanChildContext(); + } + + private void assertCleanParentContext() { + assertEquals("foo", foo.toString()); + } + + private void assertCleanChildContext() { + assertEquals("baz-child", baz.toString()); + } + + private void assertDirtyParentContext() { + assertEquals("oof", foo.toString()); + } + + private void assertDirtyChildContext() { + assertEquals("dlihc-zab", baz.toString()); + } + + // ------------------------------------------------------------------------- + + @Before + public void verifyContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + } + + @Test + public void test1_verifyOriginalStateAndDirtyContexts() { + assertOriginalState(); + reverseStringBuffers(); + } + + @Test + @DirtiesContext + public void test2_verifyContextsWereDirtiedAndTriggerExhaustiveCacheClearing() { + assertDirtyParentContext(); + assertDirtyChildContext(); + } + + @Test + @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL) + public void test3_verifyOriginalStateWasReinstatedAndDirtyContextsAndTriggerCurrentLevelCacheClearing() { + assertOriginalState(); + reverseStringBuffers(); + } + + @Test + public void test4_verifyParentContextIsStillDirtyButChildContextHasBeenReinstated() { + assertDirtyParentContext(); + assertCleanChildContext(); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java new file mode 100644 index 0000000000..b111f15270 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithSingleLevelContextHierarchyTests.java @@ -0,0 +1,63 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration) +public class SingleTestClassWithSingleLevelContextHierarchyTests { + + @Configuration + static class Config { + + @Bean + public String foo() { + return "foo"; + } + } + + + @Autowired + private String foo; + + @Autowired + private ApplicationContext context; + + + @Test + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNull("parent ApplicationContext", context.getParent()); + assertEquals("foo", foo); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java new file mode 100644 index 0000000000..5591b915b4 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.java @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy({ + @ContextConfiguration(classes = SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests.ParentConfig.class), + @ContextConfiguration("SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests-ChildConfig.xml") }) +public class SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests { + + @Configuration + static class ParentConfig { + + @Bean + public String foo() { + return "foo"; + } + + @Bean + public String baz() { + return "baz-parent"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private String baz; + + @Autowired + private ApplicationContext context; + + + @Test + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertEquals("foo", foo); + assertEquals("bar", bar); + assertEquals("baz-child", baz); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java new file mode 100644 index 0000000000..0333e5fb2d --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyTests.java @@ -0,0 +1,93 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy({ + @ContextConfiguration(classes = SingleTestClassWithTwoLevelContextHierarchyTests.ParentConfig.class), + @ContextConfiguration(classes = SingleTestClassWithTwoLevelContextHierarchyTests.ChildConfig.class) }) +public class SingleTestClassWithTwoLevelContextHierarchyTests { + + @Configuration + static class ParentConfig { + + @Bean + public String foo() { + return "foo"; + } + + @Bean + public String baz() { + return "baz-parent"; + } + } + + @Configuration + static class ChildConfig { + + @Bean + public String bar() { + return "bar"; + } + + @Bean + public String baz() { + return "baz-child"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private String baz; + + @Autowired + private ApplicationContext context; + + + @Test + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertEquals("foo", foo); + assertEquals("bar", bar); + assertEquals("baz-child", baz); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java new file mode 100644 index 0000000000..3dbf579475 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests.java @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration) +public class TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests { + + @Configuration + static class Config { + + @Bean + public String foo() { + return "foo-level-1"; + } + + @Bean + public String bar() { + return "bar"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private ApplicationContext context; + + + @Test + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNull("parent ApplicationContext", context.getParent()); + assertEquals("foo-level-1", foo); + assertEquals("bar", bar); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java new file mode 100644 index 0000000000..16b04c7f18 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests.java @@ -0,0 +1,71 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests { + + @Configuration + static class Config { + + @Bean + public String foo() { + return "foo-level-1"; + } + + @Bean + public String bar() { + return "bar"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private ApplicationContext context; + + + @Test + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNull("parent ApplicationContext", context.getParent()); + assertEquals("foo-level-1", foo); + assertEquals("bar", bar); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java new file mode 100644 index 0000000000..3e91f375d9 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelOneWithSingleLevelContextHierarchyTests.java @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration) +public class TestHierarchyLevelOneWithSingleLevelContextHierarchyTests { + + @Configuration + static class Config { + + @Bean + public String foo() { + return "foo-level-1"; + } + + @Bean + public String bar() { + return "bar"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private ApplicationContext context; + + + @Test + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNull("parent ApplicationContext", context.getParent()); + assertEquals("foo-level-1", foo); + assertEquals("bar", bar); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java new file mode 100644 index 0000000000..2054f450b9 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests.java @@ -0,0 +1,78 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class TestHierarchyLevelTwoWithBareContextConfigurationInSubclassTests extends + TestHierarchyLevelOneWithBareContextConfigurationInSubclassTests { + + @Configuration + static class Config { + + @Bean + public String foo() { + return "foo-level-2"; + } + + @Bean + public String baz() { + return "baz"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private String baz; + + @Autowired + private ApplicationContext context; + + + @Test + @Override + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertEquals("foo-level-2", foo); + assertEquals("bar", bar); + assertEquals("baz", baz); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java new file mode 100644 index 0000000000..bc38d2bb40 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests.java @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration) +public class TestHierarchyLevelTwoWithBareContextConfigurationInSuperclassTests extends + TestHierarchyLevelOneWithBareContextConfigurationInSuperclassTests { + + @Configuration + static class Config { + + @Bean + public String foo() { + return "foo-level-2"; + } + + @Bean + public String baz() { + return "baz"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private String baz; + + @Autowired + private ApplicationContext context; + + + @Test + @Override + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertEquals("foo-level-2", foo); + assertEquals("bar", bar); + assertEquals("baz", baz); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java new file mode 100644 index 0000000000..c6edd3af8b --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests.java @@ -0,0 +1,62 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration) +public class TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests extends + TestHierarchyLevelOneWithSingleLevelContextHierarchyTests { + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private String baz; + + @Autowired + private ApplicationContext context; + + + @Test + @Override + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertNull("grandparent ApplicationContext", context.getParent().getParent()); + assertEquals("foo-level-2", foo); + assertEquals("bar", bar); + assertEquals("baz", baz); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java new file mode 100644 index 0000000000..edc8fb3396 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests.java @@ -0,0 +1,78 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.standard; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy(@ContextConfiguration) +public class TestHierarchyLevelTwoWithSingleLevelContextHierarchyTests extends + TestHierarchyLevelOneWithSingleLevelContextHierarchyTests { + + @Configuration + static class Config { + + @Bean + public String foo() { + return "foo-level-2"; + } + + @Bean + public String baz() { + return "baz"; + } + } + + + @Autowired + private String foo; + + @Autowired + private String bar; + + @Autowired + private String baz; + + @Autowired + private ApplicationContext context; + + + @Test + @Override + public void loadContextHierarchy() { + assertNotNull("child ApplicationContext", context); + assertNotNull("parent ApplicationContext", context.getParent()); + assertEquals("foo-level-2", foo); + assertEquals("bar", bar); + assertEquals("baz", baz); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java new file mode 100644 index 0000000000..a6282218f2 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/ControllerIntegrationTests.java @@ -0,0 +1,102 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.web; + +import javax.servlet.ServletContext; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.hierarchies.web.ControllerIntegrationTests.AppConfig; +import org.springframework.test.context.hierarchies.web.ControllerIntegrationTests.WebConfig; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.Assert.*; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextHierarchy({ + // + @ContextConfiguration(name = "root", classes = AppConfig.class), + @ContextConfiguration(name = "dispatcher", classes = WebConfig.class) // +}) +public class ControllerIntegrationTests { + + @Configuration + static class AppConfig { + + @Bean + public String foo() { + return "foo"; + } + } + + @Configuration + static class WebConfig { + + @Bean + public String bar() { + return "bar"; + } + } + + + // ------------------------------------------------------------------------- + + @Autowired + private WebApplicationContext wac; + + @Autowired + private String foo; + + @Autowired + private String bar; + + + @Test + public void verifyRootWacSupport() { + assertEquals("foo", foo); + assertEquals("bar", bar); + + ApplicationContext parent = wac.getParent(); + assertNotNull(parent); + assertTrue(parent instanceof WebApplicationContext); + WebApplicationContext root = (WebApplicationContext) parent; + assertFalse(root.getBeansOfType(String.class).containsKey("bar")); + + ServletContext childServletContext = wac.getServletContext(); + assertNotNull(childServletContext); + ServletContext rootServletContext = root.getServletContext(); + assertNotNull(rootServletContext); + assertSame(childServletContext, rootServletContext); + + assertSame(root, rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + assertSame(root, childServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java new file mode 100644 index 0000000000..622547c48b --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests.java @@ -0,0 +1,88 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.web; + +import javax.servlet.ServletContext; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.Assert.*; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@ContextHierarchy(@ContextConfiguration) +public class DispatcherWacRootWacEarTests extends RootWacEarTests { + + @Autowired + private WebApplicationContext wac; + + @Autowired + private String ear; + + @Autowired + private String root; + + @Autowired + private String dispatcher; + + + @Test + @Override + public void verifyEarConfig() { + /* no-op */ + } + + @Test + @Override + public void verifyRootWacConfig() { + /* no-op */ + } + + @Test + public void verifyDispatcherWacConfig() { + ApplicationContext parent = wac.getParent(); + assertNotNull(parent); + assertTrue(parent instanceof WebApplicationContext); + + ApplicationContext grandParent = parent.getParent(); + assertNotNull(grandParent); + assertFalse(grandParent instanceof WebApplicationContext); + + ServletContext dispatcherServletContext = wac.getServletContext(); + assertNotNull(dispatcherServletContext); + ServletContext rootServletContext = ((WebApplicationContext) parent).getServletContext(); + assertNotNull(rootServletContext); + assertSame(dispatcherServletContext, rootServletContext); + + assertSame(parent, + rootServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + assertSame(parent, + dispatcherServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)); + + assertEquals("ear", ear); + assertEquals("root", root); + assertEquals("dispatcher", dispatcher); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java new file mode 100644 index 0000000000..8cd7eaf1b4 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/EarTests.java @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.web; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.Assert.*; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class EarTests { + + @Configuration + static class EarConfig { + + @Bean + public String ear() { + return "ear"; + } + } + + + // ------------------------------------------------------------------------- + + @Autowired + private ApplicationContext context; + + @Autowired + private String ear; + + + @Test + public void verifyEarConfig() { + assertFalse(context instanceof WebApplicationContext); + assertNull(context.getParent()); + assertEquals("ear", ear); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java new file mode 100644 index 0000000000..dbd3e93aa8 --- /dev/null +++ b/spring-test/src/test/java/org/springframework/test/context/hierarchies/web/RootWacEarTests.java @@ -0,0 +1,76 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.context.hierarchies.web; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.context.WebApplicationContext; + +import static org.junit.Assert.*; + +/** + * @author Sam Brannen + * @since 3.2.2 + */ +@WebAppConfiguration +@ContextHierarchy(@ContextConfiguration) +public class RootWacEarTests extends EarTests { + + @Configuration + static class RootWacConfig { + + @Bean + public String root() { + return "root"; + } + } + + + // ------------------------------------------------------------------------- + + @Autowired + private WebApplicationContext wac; + + @Autowired + private String ear; + + @Autowired + private String root; + + + @Test + @Override + public void verifyEarConfig() { + /* no-op */ + } + + @Test + public void verifyRootWacConfig() { + ApplicationContext parent = wac.getParent(); + assertNotNull(parent); + assertFalse(parent instanceof WebApplicationContext); + assertEquals("ear", ear); + assertEquals("root", root); + } + +} diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java index b5d74839f6..fd82c559b6 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java @@ -33,21 +33,21 @@ import org.springframework.test.context.support.GenericPropertiesContextLoader; /** *

          * JUnit 4 based test class, which verifies the expected functionality of - * {@link SpringJUnit4ClassRunner} in conjunction with support for application - * contexts loaded from Java {@link Properties} files. Specifically, the - * {@link ContextConfiguration#loader() loaderClass} and - * {@link ContextConfiguration#resourceSuffix() resourceSuffix} attributes of - * @ContextConfiguration are tested. + * {@link SpringJUnit4ClassRunner} in conjunction with support for application contexts + * loaded from Java {@link Properties} files. Specifically, the + * {@link ContextConfiguration#loader() loader} attribute of {@code ContextConfiguration} + * and the + * {@link org.springframework.test.context.support.GenericPropertiesContextLoader#getResourceSuffix() + * resourceSuffix} property of {@code GenericPropertiesContextLoader} are tested. *

          *

          - * Since no {@link ContextConfiguration#locations() locations} are explicitly - * defined, the {@link ContextConfiguration#resourceSuffix() resourceSuffix} is - * set to "-context.properties", and - * {@link ContextConfiguration#generateDefaultLocations() generateDefaultLocations} - * is left set to its default value of {@code true}, this test class's - * dependencies will be injected via - * {@link Autowired annotation-based autowiring} from beans defined in the - * {@link ApplicationContext} loaded from the default classpath resource: "{@code /org/springframework/test/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties}". + * Since no {@link ContextConfiguration#locations() locations} are explicitly defined, the + * {@code resourceSuffix} is set to "-context.properties", and since default + * resource locations will be detected by default, this test class's dependencies will be + * injected via {@link Autowired annotation-based autowiring} from beans defined in the + * {@link ApplicationContext} loaded from the default classpath resource: " + * {@code /org/springframework/test/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties} + * ". *

          * * @author Sam Brannen diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/Spr8849Tests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/Spr8849Tests.java index fa0412abc1..dd58986717 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/Spr8849Tests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr8849/Spr8849Tests.java @@ -38,6 +38,7 @@ import org.junit.runners.Suite.SuiteClasses; * @author Sam Brannen * @since 3.2 */ +@SuppressWarnings("javadoc") @RunWith(Suite.class) @SuiteClasses({ TestClass1.class, TestClass2.class }) public class Spr8849Tests { diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java index f20e466410..66ffc2026c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java @@ -43,10 +43,11 @@ import org.testng.annotations.Test; /** * Integration tests that verify support for - * {@link import org.springframework.context.annotation.Configuration @Configuration} - * classes with TestNG-based tests. + * {@link org.springframework.context.annotation.Configuration @Configuration} classes + * with TestNG-based tests. * - *

          Configuration will be loaded from + *

          + * Configuration will be loaded from * {@link AnnotationConfigTransactionalTestNGSpringContextTests.ContextConfiguration}. * * @author Sam Brannen diff --git a/spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests-ChildConfig.xml b/spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests-ChildConfig.xml new file mode 100644 index 0000000000..2189b42fee --- /dev/null +++ b/spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/SingleTestClassWithTwoLevelContextHierarchyAndMixedConfigTypesTests-ChildConfig.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests-context.xml b/spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests-context.xml new file mode 100644 index 0000000000..3abc44bda6 --- /dev/null +++ b/spring-test/src/test/resources/org/springframework/test/context/hierarchies/standard/TestHierarchyLevelTwoWithSingleLevelContextHierarchyAndMixedConfigTypesTests-context.xml @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/spring-test/src/test/resources/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests-context.xml b/spring-test/src/test/resources/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests-context.xml new file mode 100644 index 0000000000..496fc0b08e --- /dev/null +++ b/spring-test/src/test/resources/org/springframework/test/context/hierarchies/web/DispatcherWacRootWacEarTests-context.xml @@ -0,0 +1,7 @@ + + + + + + diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 1e6da7b4ef..3d29e95e6e 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -41,6 +41,8 @@ Changes in version 3.2.2 (2013-03-11) * MappingJackson(2)JsonView allows subclasses to access the ObjectMapper and to override content writing (SPR-7619) * Log4jWebConfigurer supports resolving placeholders against ServletContext init-parameters as well (SPR-10284) * consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks (SPR-10224) +* introduced support for context hierarchies in the TestContext framework (SPR-5613) +* introduced support for WebApplicationContext hierarchies in the TestContext framework (SPR-9863) Changes in version 3.2.1 (2013-01-24) From eefd1c4ca69fc82c63230dfe30a5752c661388e9 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Thu, 7 Mar 2013 11:20:19 -0500 Subject: [PATCH 06/28] Add context hierarchy tests to Spring MVC Test Issue: SPR-5613 --- .../samples/context/JavaConfigTests.java | 50 +++++++++++++++++-- .../samples/context/PersonController.java | 42 ++++++++++++++++ .../servlet/samples/context/PersonDao.java | 25 ++++++++++ .../samples/context/WebAppResourceTests.java | 6 ++- .../samples/context/XmlConfigTests.java | 29 +++++++++-- .../servlet/samples/context/root-context.xml | 12 +++++ .../samples/context/servlet-context.xml | 4 ++ 7 files changed, 158 insertions(+), 10 deletions(-) create mode 100644 spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonController.java create mode 100644 spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonDao.java create mode 100644 spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/root-context.xml diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java index fb75d1048f..63ee9376bf 100644 --- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java @@ -16,20 +16,21 @@ package org.springframework.test.web.servlet.samples.context; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.Person; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.samples.context.JavaConfigTests.RootConfig; import org.springframework.test.web.servlet.samples.context.JavaConfigTests.WebConfig; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @@ -42,6 +43,13 @@ import org.springframework.web.servlet.view.UrlBasedViewResolver; import org.springframework.web.servlet.view.tiles3.TilesConfigurer; import org.springframework.web.servlet.view.tiles3.TilesView; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.mockito.Mockito.*; + + /** * Tests with Java configuration. * @@ -50,18 +58,33 @@ import org.springframework.web.servlet.view.tiles3.TilesView; */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("src/test/resources/META-INF/web-resources") -@ContextConfiguration(classes = WebConfig.class) +@ContextHierarchy({ + @ContextConfiguration(classes = RootConfig.class), + @ContextConfiguration(classes = WebConfig.class) +}) public class JavaConfigTests { @Autowired private WebApplicationContext wac; + @Autowired + private PersonDao personDao; + private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + when(this.personDao.getPerson(5L)).thenReturn(new Person("Joe")); + } + + @Test + public void person() throws Exception { + this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}")); } @Test @@ -72,10 +95,27 @@ public class JavaConfigTests { } + @Configuration + static class RootConfig { + + @Bean + public PersonDao personDao() { + return Mockito.mock(PersonDao.class); + } + } + @Configuration @EnableWebMvc static class WebConfig extends WebMvcConfigurerAdapter { + @Autowired + private RootConfig rootConfig; + + @Bean + public PersonController personController() { + return new PersonController(this.rootConfig.personDao()); + } + @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonController.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonController.java new file mode 100644 index 0000000000..ffeea88e44 --- /dev/null +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonController.java @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.web.servlet.samples.context; + +import org.springframework.stereotype.Controller; +import org.springframework.test.web.Person; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class PersonController { + + private final PersonDao personDao; + + + public PersonController(PersonDao personDao) { + this.personDao = personDao; + } + + @RequestMapping(value="/person/{id}", method=RequestMethod.GET) + @ResponseBody + public Person getPerson(@PathVariable long id) { + return this.personDao.getPerson(id); + } + +} diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonDao.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonDao.java new file mode 100644 index 0000000000..035b9595d4 --- /dev/null +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/PersonDao.java @@ -0,0 +1,25 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.web.servlet.samples.context; + +import org.springframework.test.web.Person; + +public interface PersonDao { + + Person getPerson(Long id); + +} diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java index 2fb361f915..23cd46d5c3 100644 --- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/WebAppResourceTests.java @@ -28,6 +28,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; @@ -42,7 +43,10 @@ import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("src/test/resources/META-INF/web-resources") -@ContextConfiguration("servlet-context.xml") +@ContextHierarchy({ + @ContextConfiguration("root-context.xml"), + @ContextConfiguration("servlet-context.xml") +}) public class WebAppResourceTests { @Autowired diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java index 73ab1ab0a9..e9091ef5b0 100644 --- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/context/XmlConfigTests.java @@ -16,20 +16,26 @@ package org.springframework.test.web.servlet.samples.context; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.Person; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; +import static org.mockito.Mockito.*; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + /** * Tests with XML configuration. * @@ -38,18 +44,33 @@ import org.springframework.web.context.WebApplicationContext; */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration("src/test/resources/META-INF/web-resources") -@ContextConfiguration("servlet-context.xml") +@ContextHierarchy({ + @ContextConfiguration("root-context.xml"), + @ContextConfiguration("servlet-context.xml") +}) public class XmlConfigTests { @Autowired private WebApplicationContext wac; + @Autowired + private PersonDao personDao; + private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); + when(this.personDao.getPerson(5L)).thenReturn(new Person("Joe")); + } + + @Test + public void person() throws Exception { + this.mockMvc.perform(get("/person/5").accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()) + .andExpect(content().string("{\"name\":\"Joe\",\"someDouble\":0.0,\"someBoolean\":false}")); } @Test diff --git a/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/root-context.xml b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/root-context.xml new file mode 100644 index 0000000000..6456a634ca --- /dev/null +++ b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/root-context.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml index 4e567b1a84..615534d26d 100644 --- a/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml +++ b/spring-test-mvc/src/test/resources/org/springframework/test/web/servlet/samples/context/servlet-context.xml @@ -7,6 +7,10 @@ + + + + From 8e4e0f353150f1f06840eafa60a1edcb7c89dcba Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Thu, 7 Mar 2013 12:33:44 -0500 Subject: [PATCH 07/28] Use null in MockServletContext for unknown mime types MockServletContext.getMimeTypes now returns null if the Java Activation Framework returns "application/octet-stream", which is the default media type it returns if the mime type is unknown. This enforces the contract for ServletContext.getMimeTypes (return null for uknown mime types) but does mean "application/octet-stream" cannot be returned. Issue: SPR-10334 --- .../springframework/mock/web/MockServletContext.java | 10 +++++++++- .../mock/web/test/MockServletContext.java | 11 +++++++++-- .../PathExtensionContentNegotiationStrategyTests.java | 6 ++++-- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java b/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java index 76b65c3904..7575d11863 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java @@ -242,8 +242,16 @@ public class MockServletContext implements ServletContext { return this.effectiveMinorVersion; } + /** + * This method uses the Java Activation framework, which returns + * "application/octet-stream" when the mime type is unknown (i.e. it never returns + * {@code null}). In order to maintain the {@link ServletContext#getMimeType(String) + * contract, as of version 3.2.2, this method returns null if the mimeType is + * "application/octet-stream". + */ public String getMimeType(String filePath) { - return MimeTypeResolver.getMimeType(filePath); + String mimeType = MimeTypeResolver.getMimeType(filePath); + return ("application/octet-stream".equals(mimeType)) ? null : mimeType; } public Set getResourcePaths(String path) { diff --git a/spring-web/src/test/java/org/springframework/mock/web/test/MockServletContext.java b/spring-web/src/test/java/org/springframework/mock/web/test/MockServletContext.java index d18678dc4a..dd070c7785 100644 --- a/spring-web/src/test/java/org/springframework/mock/web/test/MockServletContext.java +++ b/spring-web/src/test/java/org/springframework/mock/web/test/MockServletContext.java @@ -45,7 +45,6 @@ import javax.servlet.descriptor.JspConfigDescriptor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; @@ -258,9 +257,17 @@ public class MockServletContext implements ServletContext { return this.effectiveMinorVersion; } + /** + * This method uses the Java Activation framework, which returns + * "application/octet-stream" when the mime type is unknown (i.e. it never returns + * {@code null}). In order to maintain the {@link ServletContext#getMimeType(String) + * contract, as of version 3.2.2, this method returns null if the mimeType is + * "application/octet-stream". + */ @Override public String getMimeType(String filePath) { - return MimeTypeResolver.getMimeType(filePath); + String mimeType = MimeTypeResolver.getMimeType(filePath); + return ("application/octet-stream".equals(mimeType)) ? null : mimeType; } @Override diff --git a/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java b/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java index 81029401f0..b814c5926e 100644 --- a/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java +++ b/spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java @@ -74,10 +74,12 @@ public class PathExtensionContentNegotiationStrategyTests { assertEquals(Arrays.asList(new MediaType("application", "vnd.ms-excel")), mediaTypes); } + // SPR-10334 + @Test public void getMediaTypeFromFilenameNoJaf() { - this.servletRequest.setRequestURI("test.xls"); + this.servletRequest.setRequestURI("test.json"); ServletContext servletContext = this.servletRequest.getServletContext(); PathExtensionContentNegotiationStrategy strategy = @@ -86,7 +88,7 @@ public class PathExtensionContentNegotiationStrategyTests { List mediaTypes = strategy.resolveMediaTypes(this.webRequest); - assertEquals(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM), mediaTypes); + assertEquals(Collections.emptyList(), mediaTypes); } // SPR-8678 From 3eb361066067438efbcf0758e78f229e2655a599 Mon Sep 17 00:00:00 2001 From: Oliver Gierke Date: Fri, 8 Mar 2013 17:22:13 +0100 Subject: [PATCH 08/28] UriComponentsBuilder parse of empty fragments Check for an empty fragment in UriComponentsBuilder.fromUriString(...) to prevent the invocation of fragment(...). Previously, UriComponentsBuilder.fromUriString(...) threw an exception in the case of an empty fragment being provided (e.g. /example#). Issue: SPR-10363 --- .../web/util/UriComponentsBuilder.java | 6 +++++- .../web/util/UriComponentsBuilderTests.java | 11 +++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java index 30dcac0f84..7fbd0178f2 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java @@ -48,6 +48,7 @@ import org.springframework.web.util.HierarchicalUriComponents.PathComponent; * @author Arjen Poutsma * @author Rossen Stoyanchev * @author Phillip Webb + * @author Oliver Gierke * @since 3.1 * @see #newInstance() * @see #fromPath(String) @@ -204,7 +205,10 @@ public class UriComponentsBuilder { builder.path(path); builder.query(query); } - builder.fragment(fragment); + + if (StringUtils.hasText(fragment)) { + builder.fragment(fragment); + } return builder; } diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index 25fbb98d59..fd60e2dcd9 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java @@ -23,16 +23,16 @@ import java.util.HashMap; import java.util.Map; import org.junit.Test; - import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; /** * @author Arjen Poutsma * @author Phillip Webb + * @author Oliver Gierke */ public class UriComponentsBuilderTests { @@ -354,4 +354,11 @@ public class UriComponentsBuilderTests { assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").path("/x/").path("/y/z").build().toString(), equalTo("http://example.com/abc/x/y/z")); assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").pathSegment("x").path("y").build().toString(), equalTo("http://example.com/abc/x/y")); } + + @Test + public void parsesEmptyFragment() { + UriComponents components = UriComponentsBuilder.fromUriString("/example#").build(); + assertThat(components.getFragment(), is(nullValue())); + assertThat(components.toString(), equalTo("/example")); + } } From 4e7098dc637e2f66a160251e29aa89dc3d16cf65 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sun, 10 Mar 2013 01:39:14 +0100 Subject: [PATCH 09/28] Document context hierarchy support in the TCF This commit adds examples to the Javadoc for @ContextHierarchy and updates the Javadoc for @ContextConfiguration accordingly. Issue: SPR-10357 --- .../test/context/ContextConfiguration.java | 13 ++- .../test/context/ContextHierarchy.java | 105 +++++++++++++++++- 2 files changed, 111 insertions(+), 7 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java index b86032a7d2..ef4bda8402 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java @@ -287,13 +287,14 @@ public @interface ContextConfiguration { /** * The name of the context hierarchy level represented by this configuration. * - *

          If not specified the name will be inferred based on the numerical level within all - * declared contexts within the hierarchy. + *

          If not specified the name will be inferred based on the numerical level + * within all declared contexts within the hierarchy. * - *

          This attribute is only applicable when used within a test class hierarchy that is - * configured using {@link ContextHierarchy @ContextHierarchy}, in which case the name - * can be used for merging or overriding this configuration with configuration of the - * same name in hierarchy levels defined in superclasses. + *

          This attribute is only applicable when used within a test class hierarchy + * that is configured using {@code @ContextHierarchy}, in which case the name + * can be used for merging or overriding this configuration + * with configuration of the same name in hierarchy levels defined in superclasses. + * See the Javadoc for {@link ContextHierarchy @ContextHierarchy} for details. * * @since 3.2.2 */ diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java b/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java index b7846b7a0d..e9a68af829 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java @@ -28,6 +28,109 @@ import java.lang.annotation.Target; * a hierarchy of {@link org.springframework.context.ApplicationContext * ApplicationContexts} for integration tests. * + *

          Examples

          + *

          The following JUnit-based examples demonstrate common configuration + * scenarios for integration tests that require the use of context hierarchies. + * + *

          Single Test Class with Context Hierarchy

          + *

          {@code ControllerIntegrationTests} represents a typical integration testing + * scenario for a Spring MVC web application by declaring a context hierarchy + * consisting of two levels, one for the root {@code WebApplicationContext} + * (with {@code TestAppConfig}) and one for the dispatcher servlet + * {@code WebApplicationContext} (with {@code WebConfig}). The {@code + * WebApplicationContext} that is autowired into the test instance is + * the one for the child context (i.e., the lowest context in the hierarchy). + * + *

          + * @RunWith(SpringJUnit4ClassRunner.class)
          + * @WebAppConfiguration
          + * @ContextHierarchy({
          + *     @ContextConfiguration(classes = TestAppConfig.class),
          + *     @ContextConfiguration(classes = WebConfig.class)
          + * })
          + * public class ControllerIntegrationTests {
          + *
          + *     @Autowired
          + *     private WebApplicationContext wac;
          + *
          + *     // ...
          + * }
          + * + *

          Class Hierarchy with Implicit Parent Context

          + *

          The following test classes define a context hierarchy within a test class + * hierarchy. {@code AbstractWebTests} declares the configuration for a root + * {@code WebApplicationContext} in a Spring-powered web application. Note, + * however, that {@code AbstractWebTests} does not declare {@code @ContextHierarchy}; + * consequently, subclasses of {@code AbstractWebTests} can optionally participate + * in a context hierarchy or follow the standard semantics for {@code @ContextConfiguration}. + * {@code SoapWebServiceTests} and {@code RestWebServiceTests} both extend + * {@code AbstractWebTests} and define a context hierarchy via {@code @ContextHierarchy}. + * The result is that three application contexts will be loaded (one for each + * declaration of {@code @ContextConfiguration}, and the application context + * loaded based on the configuration in {@code AbstractWebTests} will be set as + * the parent context for each of the contexts loaded for the concrete subclasses. + * + *

          + * @RunWith(SpringJUnit4ClassRunner.class)
          + * @WebAppConfiguration
          + * @ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml")
          + * public abstract class AbstractWebTests {}
          + *
          + * @ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml")
          + * public class SoapWebServiceTests extends AbstractWebTests {}
          + *
          + * @ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml")
          + * public class RestWebServiceTests extends AbstractWebTests {}
          + * + *

          Class Hierarchy with Merged Context Hierarchy Configuration

          + *

          The following classes demonstrate the use of named hierarchy levels + * in order to merge the configuration for specific levels in a context + * hierarchy. {@code BaseTests} defines two levels in the hierarchy, {@code parent} + * and {@code child}. {@code ExtendedTests} extends {@code BaseTests} and instructs + * the Spring TestContext Framework to merge the context configuration for the + * {@code child} hierarchy level, simply by ensuring that the names declared via + * {@link ContextConfiguration#name} are both {@code "child"}. The result is that + * three application contexts will be loaded: one for {@code "/app-config.xml"}, + * one for {@code "/user-config.xml"}, and one for {"/user-config.xml", + * "/order-config.xml"}. As with the previous example, the application + * context loaded from {@code "/app-config.xml"} will be set as the parent context + * for the contexts loaded from {@code "/user-config.xml"} and {"/user-config.xml", + * "/order-config.xml"}. + * + *

          + * @RunWith(SpringJUnit4ClassRunner.class)
          + * @ContextHierarchy({
          + *     @ContextConfiguration(name = "parent", locations = "/app-config.xml"),
          + *     @ContextConfiguration(name = "child",  locations = "/user-config.xml")
          + * })
          + * public class BaseTests {}
          + * 
          + * @ContextHierarchy(
          + *     @ContextConfiguration(name = "child",  locations = "/order-config.xml")
          + * )
          + * public class ExtendedTests extends BaseTests {}
          + * + *

          Class Hierarchy with Overridden Context Hierarchy Configuration

          + *

          In contrast to the previous example, this example demonstrates how to + * override the configuration for a given named level in a context hierarchy + * by setting the {@link ContextConfiguration#inheritLocations} flag to {@code false}. + * Consequently, the application context for {@code ExtendedTests} will be loaded + * only from {@code "/test-user-config.xml"} and will have its parent set to the + * context loaded from {@code "/app-config.xml"}. + * + *

          + * @RunWith(SpringJUnit4ClassRunner.class)
          + * @ContextHierarchy({
          + *     @ContextConfiguration(name = "parent", locations = "/app-config.xml"),
          + *     @ContextConfiguration(name = "child",  locations = "/user-config.xml")
          + * })
          + * public class BaseTests {}
          + * 
          + * @ContextHierarchy(
          + *     @ContextConfiguration(name = "child",  locations = "/test-user-config.xml", inheritLocations=false)
          + * )
          + * public class ExtendedTests extends BaseTests {}
          + * * @author Sam Brannen * @since 3.2.2 * @see ContextConfiguration @@ -47,7 +150,7 @@ public @interface ContextHierarchy { * of the context hierarchy within a test class hierarchy, you must explicitly * name that level by supplying the same value to the {@link ContextConfiguration#name * name} attribute in {@code @ContextConfiguration} at each level in the - * class hierarchy. + * class hierarchy. See the class-level Javadoc for examples. */ ContextConfiguration[] value(); From ccdb48210a58e2ab497a4be5b29ea26cb5a4b2a9 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sun, 10 Mar 2013 14:26:19 +0100 Subject: [PATCH 10/28] Document context hierarchy support in the TCF This commit polishes the Javadoc for @ContextHierarchy and @ContextConfiguration. Issue: SPR-10357 --- .../test/context/ContextConfiguration.java | 21 +++++++++++++------ .../test/context/ContextHierarchy.java | 10 ++++----- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java b/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java index ef4bda8402..7033765c0b 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextConfiguration.java @@ -58,7 +58,7 @@ import org.springframework.context.ConfigurableApplicationContext; * {@link org.springframework.context.annotation.Bean @Bean}-methods
        • *
        * - * Consult the Javadoc for + *

        Consult the Javadoc for * {@link org.springframework.context.annotation.Configuration @Configuration} and * {@link org.springframework.context.annotation.Bean @Bean} * for further information regarding the configuration and semantics of @@ -270,16 +270,25 @@ public @interface ContextConfiguration { * explicit loader. If no class in the hierarchy specifies an explicit * loader, a default loader will be used instead. * - *

        The default concrete implementation chosen at runtime will be + *

        The default concrete implementation chosen at runtime will be either * {@link org.springframework.test.context.support.DelegatingSmartContextLoader - * DelegatingSmartContextLoader}. For further details on the default behavior - * of various concrete {@code ContextLoaders}, check out the Javadoc for + * DelegatingSmartContextLoader} or + * {@link org.springframework.test.context.web.WebDelegatingSmartContextLoader + * WebDelegatingSmartContextLoader} depending on the absence or presence of + * {@link org.springframework.test.context.web.WebAppConfiguration + * @WebAppConfiguration}. For further details on the default behavior + * of various concrete {@code SmartContextLoaders}, check out the Javadoc for * {@link org.springframework.test.context.support.AbstractContextLoader * AbstractContextLoader}, * {@link org.springframework.test.context.support.GenericXmlContextLoader - * GenericXmlContextLoader}, and + * GenericXmlContextLoader}, * {@link org.springframework.test.context.support.AnnotationConfigContextLoader - * AnnotationConfigContextLoader}. + * AnnotationConfigContextLoader}, + * {@link org.springframework.test.context.web.GenericXmlWebContextLoader + * GenericXmlWebContextLoader}, and + * {@link org.springframework.test.context.web.AnnotationConfigWebContextLoader + * AnnotationConfigWebContextLoader}. + * * @since 2.5 */ Class loader() default ContextLoader.class; diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java b/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java index e9a68af829..7eac62d6e5 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextHierarchy.java @@ -28,11 +28,11 @@ import java.lang.annotation.Target; * a hierarchy of {@link org.springframework.context.ApplicationContext * ApplicationContexts} for integration tests. * - *

        Examples

        + *

        Examples

        *

        The following JUnit-based examples demonstrate common configuration * scenarios for integration tests that require the use of context hierarchies. * - *

        Single Test Class with Context Hierarchy

        + *

        Single Test Class with Context Hierarchy

        *

        {@code ControllerIntegrationTests} represents a typical integration testing * scenario for a Spring MVC web application by declaring a context hierarchy * consisting of two levels, one for the root {@code WebApplicationContext} @@ -56,7 +56,7 @@ import java.lang.annotation.Target; * // ... * } * - *

        Class Hierarchy with Implicit Parent Context

        + *

        Class Hierarchy with Implicit Parent Context

        *

        The following test classes define a context hierarchy within a test class * hierarchy. {@code AbstractWebTests} declares the configuration for a root * {@code WebApplicationContext} in a Spring-powered web application. Note, @@ -82,7 +82,7 @@ import java.lang.annotation.Target; * @ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml") * public class RestWebServiceTests extends AbstractWebTests {} * - *

        Class Hierarchy with Merged Context Hierarchy Configuration

        + *

        Class Hierarchy with Merged Context Hierarchy Configuration

        *

        The following classes demonstrate the use of named hierarchy levels * in order to merge the configuration for specific levels in a context * hierarchy. {@code BaseTests} defines two levels in the hierarchy, {@code parent} @@ -110,7 +110,7 @@ import java.lang.annotation.Target; * ) * public class ExtendedTests extends BaseTests {} * - *

        Class Hierarchy with Overridden Context Hierarchy Configuration

        + *

        Class Hierarchy with Overridden Context Hierarchy Configuration

        *

        In contrast to the previous example, this example demonstrates how to * override the configuration for a given named level in a context hierarchy * by setting the {@link ContextConfiguration#inheritLocations} flag to {@code false}. From 2b24e99d44cce6c655f572986fd9ac50cbfeb09b Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Sun, 10 Mar 2013 14:49:10 +0100 Subject: [PATCH 11/28] Reformat the testing chapter This commit reformats the testing chapter (and adds minor polishing changes) in order to avoid massive merge diffs in upcoming commits. Issue: SPR-10357 --- src/reference/docbook/testing.xml | 1578 ++++++++++++++--------------- 1 file changed, 756 insertions(+), 822 deletions(-) diff --git a/src/reference/docbook/testing.xml b/src/reference/docbook/testing.xml index 7e819cec47..e5bb9aafd7 100644 --- a/src/reference/docbook/testing.xml +++ b/src/reference/docbook/testing.xml @@ -1,12 +1,13 @@ - + Testing

        @@ -14,11 +15,10 @@ Testing is an integral part of enterprise software development. This chapter focuses on the value-add of the IoC principle to unit testing and on the benefits of the - Spring Framework's support for integration testing. (A - thorough treatment of testing in the enterprise is beyond the scope of - this reference manual.) + linkend="unit-testing">unit testing and on the benefits of the Spring + Framework's support for integration + testing. (A thorough treatment of testing in the enterprise + is beyond the scope of this reference manual.)
        @@ -27,21 +27,21 @@ Dependency Injection should make your code less dependent on the container than it would be with traditional Java EE development. The POJOs that make up your application should be testable in JUnit or TestNG tests, - with objects simply instantiated using the new - operator, without Spring or any other container. You - can use mock objects (in conjunction - with other valuable testing techniques) to test your code in isolation. If - you follow the architecture recommendations for Spring, the resulting - clean layering and componentization of your codebase will facilitate - easier unit testing. For example, you can test service layer objects by - stubbing or mocking DAO or Repository interfaces, without needing to - access persistent data while running unit tests. + with objects simply instantiated using the new operator, + without Spring or any other container. You can use + mock objects (in conjunction with other + valuable testing techniques) to test your code in isolation. If you follow + the architecture recommendations for Spring, the resulting clean layering + and componentization of your codebase will facilitate easier unit testing. + For example, you can test service layer objects by stubbing or mocking DAO + or Repository interfaces, without needing to access persistent data while + running unit tests. True unit tests typically run extremely quickly, as there is no runtime infrastructure to set up. Emphasizing true unit tests as part of - your development methodology will boost your productivity. You may not - need this section of the testing chapter to help you write effective unit - tests for your IoC-based applications. For certain unit testing scenarios, + your development methodology will boost your productivity. You may not need + this section of the testing chapter to help you write effective unit tests + for your IoC-based applications. For certain unit testing scenarios, however, the Spring Framework provides the following mock objects and testing support classes. @@ -54,10 +54,9 @@ The org.springframework.mock.env package contains mock implementations of the Environment and - PropertySource abstractions introduced - in Spring 3.1 (see and ). + PropertySource abstractions introduced in + Spring 3.1 (see and + ). MockEnvironment and MockPropertySource are useful for developing out-of-container tests for code that depends on @@ -68,12 +67,12 @@ JNDI The org.springframework.mock.jndi package - contains an implementation of the JNDI SPI, which you can use to set - up a simple JNDI environment for test suites or stand-alone - applications. If, for example, JDBC DataSources - get bound to the same JNDI names in test code as within a Java EE - container, you can reuse both application code and configuration in - testing scenarios without modification. + contains an implementation of the JNDI SPI, which you can use to set up + a simple JNDI environment for test suites or stand-alone applications. + If, for example, JDBC DataSources get bound to + the same JNDI names in test code as within a Java EE container, you can + reuse both application code and configuration in testing scenarios + without modification.
        @@ -81,8 +80,8 @@ The org.springframework.mock.web package contains a comprehensive set of Servlet API mock objects, targeted at - usage with Spring's Web MVC framework, which are useful for testing - web contexts and controllers. These mock objects are generally more + usage with Spring's Web MVC framework, which are useful for testing web + contexts and controllers. These mock objects are generally more convenient to use than dynamic mock objects such as EasyMock or existing Servlet API mock objects such as The org.springframework.test.util package contains ReflectionTestUtils, which is a collection of reflection-based utility methods. Developers use these - methods in unit and integration testing scenarios in which they need - to set a non-public field or invoke a + methods in unit and integration testing scenarios in which they need to + set a non-public field or invoke a non-public setter method when testing application code involving, for example: @@ -124,8 +123,8 @@ Spring's support for annotations such as @Autowired, @Inject, and - @Resource, which provides - dependency injection for private or + @Resource, which provides dependency + injection for private or protected fields, setter methods, and configuration methods. @@ -136,9 +135,9 @@ Spring MVC The org.springframework.test.web package - contains ModelAndViewAssert, which you can use - in combination with JUnit, TestNG, or any other testing framework for - unit tests dealing with Spring MVC ModelAndView + contains ModelAndViewAssert, which you can use in + combination with JUnit, TestNG, or any other testing framework for unit + tests dealing with Spring MVC ModelAndView objects. @@ -149,8 +148,7 @@ MockHttpServletRequest, MockHttpSession, and so on from the - org.springframework.mock.web - package. + org.springframework.mock.web package.
        @@ -164,13 +162,12 @@ It is important to be able to perform some integration testing without requiring deployment to your application server or connecting to - other enterprise infrastructure. This will enable you to test things - such as: + other enterprise infrastructure. This will enable you to test things such + as: - The correct wiring of your Spring IoC container - contexts. + The correct wiring of your Spring IoC container contexts. @@ -182,30 +179,29 @@ The Spring Framework provides first-class support for integration testing in the spring-test - module. The name of the actual JAR file might include the release - version and might also be in the long - org.springframework.test form, depending on where - you get it from (see the section - on Dependency Management for an explanation). This library - includes the org.springframework.test package, which - contains valuable classes for integration testing with a Spring - container. This testing does not rely on an application server or other - deployment environment. Such tests are slower to run than unit tests but - much faster than the equivalent Cactus tests or remote tests that rely - on deployment to an application server. + module. The name of the actual JAR file might include the release version + and might also be in the long + org.springframework.test form, depending on where you + get it from (see the section on + Dependency Management for an explanation). This library includes + the org.springframework.test package, which contains + valuable classes for integration testing with a Spring container. This + testing does not rely on an application server or other deployment + environment. Such tests are slower to run than unit tests but much faster + than the equivalent Cactus tests or remote tests that rely on deployment + to an application server. In Spring 2.5 and later, unit and integration testing support is provided in the form of the annotation-driven Spring TestContext Framework. The - TestContext framework is agnostic of the actual testing framework in - use, thus allowing instrumentation of tests in various environments - including JUnit, TestNG, and so on. + TestContext framework is agnostic of the actual testing framework in use, + thus allowing instrumentation of tests in various environments including + JUnit, TestNG, and so on. JUnit 3.8 support is deprecated - As of Spring 3.0, the legacy JUnit 3.8 base class hierarchy - (i.e., + As of Spring 3.0, the legacy JUnit 3.8 base class hierarchy (i.e., AbstractDependencyInjectionSpringContextTests, AbstractTransactionalDataSourceSpringContextTests, etc.) is officially deprecated and will be removed in a later release. @@ -221,10 +217,10 @@ officially deprecated and will be removed in a later release. Any test classes based on this code should be migrated to the JUnit 4 or TestNG support provided by the Spring - TestContext Framework. Similarly, any test methods annotated - with @ExpectedException should be - modified to use the built-in support for expected exceptions in JUnit - and TestNG. + TestContext Framework. Similarly, any test methods annotated with + @ExpectedException should be modified to + use the built-in support for expected exceptions in JUnit and + TestNG. @@ -252,9 +248,8 @@ To supply Spring-specific base - classes that assist developers in writing integration - tests. + linkend="testing-support-classes">Spring-specific base classes + that assist developers in writing integration tests. @@ -267,18 +262,18 @@ The Spring TestContext Framework provides consistent loading of Spring ApplicationContexts and WebApplicationContexts as well as caching of - those contexts. Support for the caching of loaded contexts is - important, because startup time can become an issue — not because of - the overhead of Spring itself, but because the objects instantiated by - the Spring container take time to instantiate. For example, a project - with 50 to 100 Hibernate mapping files might take 10 to 20 seconds to - load the mapping files, and incurring that cost before running every - test in every test fixture leads to slower overall test runs that - reduce developer productivity. + those contexts. Support for the caching of loaded contexts is important, + because startup time can become an issue — not because of the overhead + of Spring itself, but because the objects instantiated by the Spring + container take time to instantiate. For example, a project with 50 to + 100 Hibernate mapping files might take 10 to 20 seconds to load the + mapping files, and incurring that cost before running every test in + every test fixture leads to slower overall test runs that reduce + developer productivity. Test classes typically declare either an array of - resource locations for XML configuration metadata - — often in the classpath — or an array of annotated + resource locations for XML configuration metadata — + often in the classpath — or an array of annotated classes that is used to configure the application. These locations or classes are the same as or similar to those specified in web.xml or other deployment configuration @@ -291,11 +286,10 @@ test suite means all tests run in the same JVM — for example, all tests run from an Ant, Maven, or Gradle build for a given project or module. In the unlikely case that a test corrupts the - application context and requires reloading — for example, by modifying - a bean definition or the state of an application object — the - TestContext framework can be configured to reload the configuration - and rebuild the application context before executing the next - test. + application context and requires reloading — for example, by modifying a + bean definition or the state of an application object — the TestContext + framework can be configured to reload the configuration and rebuild the + application context before executing the next test. See context management and caching with the TestContext @@ -305,15 +299,15 @@
        Dependency Injection of test fixtures - When the TestContext framework loads your application context, - it can optionally configure instances of your test classes via - Dependency Injection. This provides a convenient mechanism for setting - up test fixtures using preconfigured beans from your application - context. A strong benefit here is that you can reuse application - contexts across various testing scenarios (e.g., for configuring - Spring-managed object graphs, transactional proxies, - DataSources, etc.), thus avoiding the need to - duplicate complex test fixture setup for individual test cases. + When the TestContext framework loads your application context, it + can optionally configure instances of your test classes via Dependency + Injection. This provides a convenient mechanism for setting up test + fixtures using preconfigured beans from your application context. A + strong benefit here is that you can reuse application contexts across + various testing scenarios (e.g., for configuring Spring-managed object + graphs, transactional proxies, DataSources, + etc.), thus avoiding the need to duplicate complex test fixture setup + for individual test cases. As an example, consider the scenario where we have a class, HibernateTitleRepository, that implements data @@ -322,22 +316,22 @@ - The Spring configuration: basically, is everything related - to the configuration of the + The Spring configuration: basically, is everything related to + the configuration of the HibernateTitleRepository bean correct and present? - The Hibernate mapping file configuration: is everything - mapped correctly, and are the correct lazy-loading settings in + The Hibernate mapping file configuration: is everything mapped + correctly, and are the correct lazy-loading settings in place? The logic of the - HibernateTitleRepository: does the - configured instance of this class perform as anticipated? + HibernateTitleRepository: does the configured + instance of this class perform as anticipated? @@ -351,21 +345,20 @@ One common issue in tests that access a real database is their effect on the state of the persistence store. Even when you're using a development database, changes to the state may affect future tests. - Also, many operations — such as inserting or modifying persistent data - — cannot be performed (or verified) outside a transaction. + Also, many operations — such as inserting or modifying persistent data — + cannot be performed (or verified) outside a transaction. The TestContext framework addresses this issue. By default, the framework will create and roll back a transaction for each test. You - simply write code that can assume the existence of a transaction. If - you call transactionally proxied objects in your tests, they will - behave correctly, according to their configured transactional - semantics. In addition, if a test method deletes the contents of - selected tables while running within the transaction managed for the - test, the transaction will roll back by default, and the database will - return to its state prior to execution of the test. Transactional - support is provided to a test via a - PlatformTransactionManager bean defined in the - test's application context. + simply write code that can assume the existence of a transaction. If you + call transactionally proxied objects in your tests, they will behave + correctly, according to their configured transactional semantics. In + addition, if a test method deletes the contents of selected tables while + running within the transaction managed for the test, the transaction + will roll back by default, and the database will return to its state + prior to execution of the test. Transactional support is provided to a + test via a PlatformTransactionManager bean + defined in the test's application context. If you want a transaction to commit — unusual, but occasionally useful when you want a particular test to populate or modify the @@ -384,10 +377,10 @@ Support classes for integration testing The Spring TestContext Framework provides several - abstract support classes that simplify the writing - of integration tests. These base test classes provide well-defined - hooks into the testing framework as well as convenient instance - variables and methods, which enable you to access: + abstract support classes that simplify the writing of + integration tests. These base test classes provide well-defined hooks + into the testing framework as well as convenient instance variables and + methods, which enable you to access: @@ -400,18 +393,18 @@ A JdbcTemplate, for executing SQL statements to query the database. Such queries can be used to confirm database state both prior to and - after execution of database-related - application code, and Spring ensures that such queries run in the - scope of the same transaction as the application code. When used - in conjunction with an ORM tool, be sure to avoid after execution of database-related application + code, and Spring ensures that such queries run in the scope of the + same transaction as the application code. When used in conjunction + with an ORM tool, be sure to avoid false positives. In addition, you may want to create your own custom, - application-wide superclass with instance variables and methods - specific to your project. + application-wide superclass with instance variables and methods specific + to your project. See support classes for the TestContext @@ -435,8 +428,8 @@ The spring-jdbc module provides support for configuring and launching an embedded database which can be used in integration tests that interact with a database. For details, see and . + linkend="jdbc-embedded-database-support"/> and .
        @@ -449,8 +442,7 @@ Spring-specific annotations that you can use in your unit and integration tests in conjunction with the TestContext framework. Refer to the respective Javadoc for further information, - including default attribute values, attribute aliases, and so - on. + including default attribute values, attribute aliases, and so on. @@ -458,8 +450,8 @@ @ContextConfiguration - Defines class-level metadata that is used to determine how - to load and configure an + Defines class-level metadata that is used to determine how to + load and configure an ApplicationContext for integration tests. Specifically, @ContextConfiguration declares @@ -480,36 +472,34 @@ public class XmlApplicationContextTests { } @ContextConfiguration(classes=TestConfig.class) + role="bold">classes = TestConfig.class) public class ConfigClassApplicationContextTests { // class body... } As an alternative or in addition to declaring resource locations or annotated classes, - @ContextConfiguration may be used - to declare - ApplicationContextInitializer + @ContextConfiguration may be used to + declare ApplicationContextInitializer classes. @ContextConfiguration(initializers=CustomContextIntializer.class) + role="bold">initializers = CustomContextIntializer.class) public class ContextInitializerTests { // class body... } @ContextConfiguration may optionally be used to declare the - ContextLoader strategy as well. - Note, however, that you typically do not need to explicitly - configure the loader since the default loader supports either - resource locations or annotated - classes as well as - initializers. + ContextLoader strategy as well. Note, + however, that you typically do not need to explicitly configure the + loader since the default loader supports either resource + locations or annotated classes + as well as initializers. @ContextConfiguration(locations="/test-context.xml", loader=CustomContextLoader.class) + role="bold">locations = "/test-context.xml", loader = CustomContextLoader.class) public class CustomLoaderXmlApplicationContextTests { // class body... } @@ -517,8 +507,8 @@ public class CustomLoaderXmlApplicationContextTests { @ContextConfiguration provides support for inheriting resource - locations or configuration classes as well as context - initializers declared by superclasses by default. + locations or configuration classes as well as context initializers + declared by superclasses by default. See Context @@ -535,16 +525,15 @@ public class CustomLoaderXmlApplicationContextTests { ApplicationContext loaded for an integration test should be a WebApplicationContext. The mere - presence of @WebAppConfiguration on - a test class ensures that a - WebApplicationContext will be - loaded for the test, using the default value of + presence of @WebAppConfiguration on a + test class ensures that a + WebApplicationContext will be loaded + for the test, using the default value of "file:src/main/webapp" for the path to the root of the web application (i.e., the resource base path). The resource base path is used behind the scenes to create a MockServletContext which serves - as the ServletContext for the - test's + as the ServletContext for the test's WebApplicationContext. @ContextConfiguration @@ -556,9 +545,9 @@ public class WebAppTests { To override the default, specify a different base resource path via the implicit value attribute. Both - classpath: and file: - resource prefixes are supported. If no resource prefix is supplied - the path is assumed to be a file system resource. + classpath: and file: resource + prefixes are supported. If no resource prefix is supplied the path + is assumed to be a file system resource. @ContextConfiguration @WebAppConfiguration("classpath:test-web-resources") @@ -566,14 +555,12 @@ public class WebAppTests { // class body... } - Note that - @WebAppConfiguration must be used - in conjunction with - @ContextConfiguration, either - within a single test class or within a test class hierarchy. See - the Javadoc for - @WebAppConfiguration for further - details. + Note that @WebAppConfiguration + must be used in conjunction with + @ContextConfiguration, either within + a single test class or within a test class hierarchy. See the + Javadoc for @WebAppConfiguration for + further details. @@ -581,9 +568,9 @@ public class WebAppTests { @ActiveProfiles A class-level annotation that is used to declare which - bean definition profiles should be active - when loading an ApplicationContext - for test classes. + bean definition profiles should be active when + loading an ApplicationContext for + test classes. @ContextConfiguration @ActiveProfiles("dev") @@ -599,8 +586,8 @@ public class DeveloperIntegrationTests { @ActiveProfiles provides - support for inheriting active bean - definition profiles declared by superclasses by default. + support for inheriting active bean definition + profiles declared by superclasses by default. See After the current test class, when declared on a class - with class mode set to AFTER_CLASS, which - is the default class mode. + with class mode set to AFTER_CLASS, which is + the default class mode. @@ -636,8 +623,7 @@ public class DeveloperIntegrationTests { - After the current test, when declared on a - method. + After the current test, when declared on a method. @@ -646,14 +632,14 @@ public class DeveloperIntegrationTests { supplied a new context. With JUnit 4.5+ or TestNG you can use - @DirtiesContext as both a - class-level and method-level annotation within the same test - class. In such scenarios, the - ApplicationContext is marked as - dirty after any such annotated method as well - as after the entire class. If the ClassMode - is set to AFTER_EACH_TEST_METHOD, the context - is marked dirty after each test method in the class. + @DirtiesContext as both a class-level + and method-level annotation within the same test class. In such + scenarios, the ApplicationContext is + marked as dirty after any such annotated method + as well as after the entire class. If the + ClassMode is set to + AFTER_EACH_TEST_METHOD, the context is marked + dirty after each test method in the class. @DirtiesContext public class ContextDirtyingTests { @@ -675,8 +661,8 @@ public void testProcessWhichDirtiesAppCtx() { When an application context is marked dirty, it is removed from the testing framework's cache and closed; thus the underlying Spring container - is rebuilt for any subsequent test that requires a context with - the same set of resource locations. + is rebuilt for any subsequent test that requires a context with the + same configuration metadata. @@ -687,8 +673,8 @@ public void testProcessWhichDirtiesAppCtx() { Defines class-level metadata for configuring which TestExecutionListeners should be registered with the TestContextManager. - Typically, @TestExecutionListeners - is used in conjunction with + Typically, @TestExecutionListeners is + used in conjunction with @ContextConfiguration. @ContextConfiguration @@ -710,23 +696,21 @@ public class CustomTestExecutionListenerTests { Defines class-level metadata for configuring transactional tests. Specifically, the bean name of the PlatformTransactionManager that - should be used to drive transactions can be explicitly specified - if there are multiple beans of type + should be used to drive transactions can be explicitly specified if + there are multiple beans of type PlatformTransactionManager in the - test's ApplicationContext and if - the bean name of the desired + test's ApplicationContext and if the + bean name of the desired PlatformTransactionManager is not "transactionManager". In addition, you can change the - defaultRollback flag to - false. Typically, - @TransactionConfiguration is used - in conjunction with + defaultRollback flag to false. + Typically, @TransactionConfiguration + is used in conjunction with @ContextConfiguration. @ContextConfiguration -@TransactionConfiguration(transactionManager="txMgr", defaultRollback=false) +@TransactionConfiguration(transactionManager = "txMgr", defaultRollback = false) public class CustomConfiguredTransactionalTests { // class body... } @@ -752,8 +736,8 @@ public class CustomConfiguredTransactionalTests { Indicates whether the transaction for the annotated test method should be rolled back after the test - method has completed. If true, the transaction - is rolled back; otherwise, the transaction is committed. Use + method has completed. If true, the transaction is + rolled back; otherwise, the transaction is committed. Use @Rollback to override the default rollback flag configured at the class level. @@ -766,13 +750,12 @@ public void testProcessWithoutRollback() { - @BeforeTransaction - + @BeforeTransaction Indicates that the annotated public void - method should be executed before a - transaction is started for test methods configured to run within a - transaction via the @Transactional + method should be executed before a transaction + is started for test methods configured to run within a transaction + via the @Transactional annotation. @BeforeTransaction @@ -783,8 +766,7 @@ public void testProcessWithoutRollback() { - @AfterTransaction - + @AfterTransaction Indicates that the annotated public void method should be executed after a transaction @@ -800,12 +782,11 @@ public void testProcessWithoutRollback() { - @NotTransactional - + @NotTransactional The presence of this annotation indicates that the annotated - test method must not execute in a - transactional context. + test method must not execute in a transactional + context. @NotTransactional @Test @@ -817,14 +798,14 @@ public void testProcessWithoutTransaction() { @NotTransactional is deprecated As of Spring 3.0, - @NotTransactional is deprecated - in favor of moving the non-transactional - test method to a separate (non-transactional) test class or to a + @NotTransactional is deprecated in + favor of moving the non-transactional test + method to a separate (non-transactional) test class or to a @BeforeTransaction or @AfterTransaction method. As an alternative to annotating an entire class with - @Transactional, consider - annotating individual methods with + @Transactional, consider annotating + individual methods with @Transactional; doing so allows a mix of transactional and non-transactional methods in the same test class without the need for using @@ -839,8 +820,8 @@ public void testProcessWithoutTransaction() { The following annotations are supported with standard semantics for all configurations of the Spring TestContext Framework. Note that - these annotations are not specific to tests and can be used anywhere - in the Spring Framework. + these annotations are not specific to tests and can be used anywhere in + the Spring Framework. @@ -856,14 +837,13 @@ public void testProcessWithoutTransaction() { @Resource - (javax.annotation) if JSR-250 is - present + (javax.annotation) if JSR-250 is present - - @Inject (javax.inject) - if JSR-330 is present + @Inject + (javax.inject) if JSR-330 is + present @@ -910,13 +890,13 @@ public void testProcessWithoutTransaction() { @PostConstruct, that method will be executed before any before methods of the underlying test framework (e.g., methods annotated with JUnit's - @Before), and that will apply for - every test method in the test class. On the other hand, if a method - within a test class is annotated with - @PreDestroy, that method will - never be executed. Within a test - class it is therefore recommended to use test lifecycle callbacks - from the underlying test framework instead of + @Before), and that will apply for every + test method in the test class. On the other hand, if a method within a + test class is annotated with + @PreDestroy, that method will never be executed. Within a test class it is + therefore recommended to use test lifecycle callbacks from the + underlying test framework instead of @PostConstruct and @PreDestroy. @@ -925,8 +905,8 @@ public void testProcessWithoutTransaction() {
        Spring JUnit Testing Annotations - The following annotations are only - supported when used in conjunction with the The following annotations are only supported + when used in conjunction with the SpringJUnit4ClassRunner or the JUnit support classes. @@ -945,8 +925,7 @@ public void testProcessWithoutTransaction() { method-level usage. @IfProfileValue(name="java.vendor", value="Sun Microsystems Inc.") + role="bold">name="java.vendor", value="Sun Microsystems Inc.") @Test public void testProcessWhichRunsOnlyOnSunJvm() { // some logic that should run only on Java VMs from Sun Microsystems @@ -955,13 +934,11 @@ public void testProcessWhichRunsOnlyOnSunJvm() { Alternatively, you can configure @IfProfileValue with a list of values (with OR semantics) - to achieve TestNG-like support for test - groups in a JUnit environment. Consider the following - example: + to achieve TestNG-like support for test groups + in a JUnit environment. Consider the following example: @IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"}) + role="bold">name="test-groups", values={"unit-tests", "integration-tests"}) @Test public void testProcessWhichRunsForUnitOrIntegrationTestGroups() { // some logic that should run only for unit and integration test groups @@ -992,24 +969,23 @@ public class CustomProfileValueSourceTests { @Timed - Indicates that the annotated test method must finish - execution in a specified time period (in milliseconds). If the - text execution time exceeds the specified time period, the test - fails. + Indicates that the annotated test method must finish execution + in a specified time period (in milliseconds). If the text execution + time exceeds the specified time period, the test fails. - The time period includes execution of the test method - itself, any repetitions of the test (see + The time period includes execution of the test method itself, + any repetitions of the test (see @Repeat), as well as any - set up or tear down of - the test fixture. + set up or tear down of the + test fixture. @Timed(millis=1000) public void testProcessWithOneSecondTimeout() { // some logic that should not take longer than 1 second to execute } - Spring's @Timed annotation - has different semantics than JUnit's + Spring's @Timed annotation has + different semantics than JUnit's @Test(timeout=...) support. Specifically, due to the manner in which JUnit handles test execution timeouts (that is, by executing the test method in a @@ -1017,23 +993,23 @@ public void testProcessWithOneSecondTimeout() { @Test(timeout=...) applies to each iteration in the case of repetitions and preemptively fails the test if the test takes too long. Spring's - @Timed, on the other hand, times - the total test execution time (including all + @Timed, on the other hand, times the + total test execution time (including all repetitions) and does not preemptively fail the test but rather waits for the test to complete before failing. - - @Repeat + @Repeat + Indicates that the annotated test method must be executed repeatedly. The number of times that the test method is to be executed is specified in the annotation. The scope of execution to be repeated includes execution of - the test method itself as well as any set up - or tear down of the test fixture. + the test method itself as well as any set up or + tear down of the test fixture. @Repeat(10) @Test @@ -1060,20 +1036,18 @@ public void testProcessRepeatedly() { In addition to generic testing infrastructure, the TestContext framework provides explicit support for JUnit and TestNG in the form of abstract support classes. For JUnit, Spring also - provides a custom JUnit Runner that - allows one to write so-called POJO test classes. - POJO test classes are not required to extend a particular class - hierarchy. + provides a custom JUnit Runner that allows + one to write so-called POJO test classes. POJO test + classes are not required to extend a particular class hierarchy. The following section provides an overview of the internals of the TestContext framework. If you are only interested in using the framework and not necessarily interested in extending it with your own custom - listeners or custom loaders, feel free to go directly to the - configuration (context - management, dependency - injection, transaction - management), support - classes, and context management, + dependency injection, transaction management), support classes, and annotation support sections. @@ -1086,21 +1060,20 @@ public void testProcessRepeatedly() { TestExecutionListener, ContextLoader, and SmartContextLoader interfaces. A - TestContextManager is created on a per-test - basis (e.g., for the execution of a single test method in JUnit). The + TestContextManager is created on a per-test basis + (e.g., for the execution of a single test method in JUnit). The TestContextManager in turn manages a - TestContext that holds the context of the - current test. The TestContextManager also - updates the state of the TestContext as the - test progresses and delegates to - TestExecutionListeners, which - instrument the actual test execution by providing dependency + TestContext that holds the context of the current + test. The TestContextManager also updates the + state of the TestContext as the test progresses + and delegates to TestExecutionListeners, + which instrument the actual test execution by providing dependency injection, managing transactions, and so on. A ContextLoader (or SmartContextLoader) is responsible for - loading an ApplicationContext for a - given test class. Consult the Javadoc and the Spring test suite for - further information and examples of various implementations. + loading an ApplicationContext for a given + test class. Consult the Javadoc and the Spring test suite for further + information and examples of various implementations. @@ -1125,8 +1098,8 @@ public void testProcessRepeatedly() { - prior to any before class methods - of a particular testing framework + prior to any before class methods of + a particular testing framework @@ -1151,15 +1124,14 @@ public void testProcessRepeatedly() { - TestExecutionListener: - Defines a listener API for reacting to test - execution events published by the - TestContextManager with which the listener - is registered. + TestExecutionListener: Defines + a listener API for reacting to test execution + events published by the TestContextManager + with which the listener is registered. Spring provides four - TestExecutionListener - implementations that are configured by default: + TestExecutionListener implementations + that are configured by default: ServletTestExecutionListener, DependencyInjectionTestExecutionListener, DirtiesContextTestExecutionListener, and @@ -1168,16 +1140,14 @@ public void testProcessRepeatedly() { WebApplicationContext, dependency injection of the test instance, handling of the @DirtiesContext annotation, and - transactional test execution with default rollback - semantics. + transactional test execution with default rollback semantics. ContextLoader: Strategy interface introduced in Spring 2.5 for loading an - ApplicationContext for an - integration test managed by the Spring TestContext - Framework. + ApplicationContext for an integration + test managed by the Spring TestContext Framework. As of Spring 3.1, implement SmartContextLoader instead of this @@ -1191,8 +1161,8 @@ public void testProcessRepeatedly() { introduced in Spring 3.1. The SmartContextLoader SPI - supersedes the ContextLoader SPI - that was introduced in Spring 2.5. Specifically, a + supersedes the ContextLoader SPI that + was introduced in Spring 2.5. Specifically, a SmartContextLoader can choose to process resource locations, annotated classes, or context @@ -1207,9 +1177,9 @@ public void testProcessRepeatedly() { DelegatingSmartContextLoader: one of two default loaders which delegates internally to an AnnotationConfigContextLoader or a - GenericXmlContextLoader depending - either on the configuration declared for the test class or on - the presence of default locations or default configuration + GenericXmlContextLoader depending either + on the configuration declared for the test class or on the + presence of default locations or default configuration classes. @@ -1220,8 +1190,8 @@ public void testProcessRepeatedly() { GenericXmlWebContextLoader depending either on the configuration declared for the test class or on the presence of default locations or default configuration - classes. A web ContextLoader - will only be used if + classes. A web ContextLoader will + only be used if @WebAppConfiguration is present on the test class. @@ -1241,14 +1211,14 @@ public void testProcessRepeatedly() { GenericXmlContextLoader: loads a - standard ApplicationContext - from XML resource locations. + standard ApplicationContext from + XML resource locations. - GenericXmlWebContextLoader: loads - a WebApplicationContext from - XML resource locations. + GenericXmlWebContextLoader: loads a + WebApplicationContext from XML + resource locations. @@ -1263,8 +1233,8 @@ public void testProcessRepeatedly() { The following sections explain how to configure the TestContext framework through annotations and - provide working examples of how to write unit and integration tests - with the framework. + provide working examples of how to write unit and integration tests with + the framework.
        @@ -1288,10 +1258,10 @@ public void testProcessRepeatedly() { @Autowired ApplicationContext As an alternative to implementing the - ApplicationContextAware interface, - you can inject the application context for your test class through - the @Autowired annotation on either a - field or setter method. For example: + ApplicationContextAware interface, you + can inject the application context for your test class through the + @Autowired annotation on either a field + or setter method. For example: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @@ -1320,29 +1290,29 @@ public class MyWebAppTest { Dependency injection via @Autowired is provided by the - DependencyInjectionTestExecutionListener - which is configured by default (see ). + DependencyInjectionTestExecutionListener which + is configured by default (see ). Test classes that use the TestContext framework do not need to extend any particular class or implement a specific interface to - configure their application context. Instead, configuration is - achieved simply by declaring the + configure their application context. Instead, configuration is achieved + simply by declaring the @ContextConfiguration annotation at the - class level. If your test class does not explicitly declare - application context resource locations or annotated + class level. If your test class does not explicitly declare application + context resource locations or annotated classes, the configured ContextLoader determines how to load a context from a default location or default configuration classes. In - addition to context resource locations and - annotated classes, an application context can also - be configured via application context + addition to context resource locations and annotated + classes, an application context can also be + configured via application context initializers. The following sections explain how to configure an - ApplicationContext via XML - configuration files, annotated classes (typically + ApplicationContext via XML configuration + files, annotated classes (typically @Configuration classes), or context initializers using Spring's @ContextConfiguration annotation. @@ -1353,18 +1323,17 @@ public class MyWebAppTest {
        Context configuration with XML resources - To load an ApplicationContext - for your tests using XML configuration files, annotate your test - class with @ContextConfiguration and + To load an ApplicationContext for + your tests using XML configuration files, annotate your test class + with @ContextConfiguration and configure the locations attribute with an array - that contains the resource locations of XML configuration metadata. - A plain or relative path — for example - "context.xml" — will be treated as a classpath - resource that is relative to the package in which the test class is - defined. A path starting with a slash is treated as an absolute - classpath location, for example - "/org/example/config.xml". A path which - represents a resource URL (i.e., a path prefixed with + that contains the resource locations of XML configuration metadata. A + plain or relative path — for example "context.xml" + — will be treated as a classpath resource that is relative to the + package in which the test class is defined. A path starting with a + slash is treated as an absolute classpath location, for example + "/org/example/config.xml". A path which represents + a resource URL (i.e., a path prefixed with classpath:, file:, http:, etc.) will be used as is. @@ -1377,13 +1346,13 @@ public class MyTest { // class body... } - @ContextConfiguration supports - an alias for the locations attribute through the - standard Java value attribute. Thus, if you do - not need to declare additional attributes in - @ContextConfiguration, you can omit - the declaration of the locations attribute name - and declare the resource locations by using the shorthand format + @ContextConfiguration supports an + alias for the locations attribute through the + standard Java value attribute. Thus, if you do not + need to declare additional attributes in + @ContextConfiguration, you can omit the + declaration of the locations attribute name and + declare the resource locations by using the shorthand format demonstrated in the following example. @RunWith(SpringJUnit4ClassRunner.class) @@ -1396,12 +1365,11 @@ public class MyTest { value attributes from the @ContextConfiguration annotation, the TestContext framework will attempt to detect a default XML resource - location. Specifically, - GenericXmlContextLoader detects a default - location based on the name of the test class. If your class is named - com.example.MyTest, - GenericXmlContextLoader loads your - application context from + location. Specifically, GenericXmlContextLoader + detects a default location based on the name of the test class. If + your class is named com.example.MyTest, + GenericXmlContextLoader loads your application + context from "classpath:/com/example/MyTest-context.xml". package com.example; @@ -1418,11 +1386,11 @@ public class MyTest {
        Context configuration with annotated classes - To load an ApplicationContext - for your tests using annotated classes (see - ), annotate your test class with - @ContextConfiguration and configure - the classes attribute with an array that contains + To load an ApplicationContext for + your tests using annotated classes (see ), annotate your test class with + @ContextConfiguration and configure the + classes attribute with an array that contains references to annotated classes. @RunWith(SpringJUnit4ClassRunner.class) @@ -1437,16 +1405,16 @@ public class MyTest { TestContext framework will attempt to detect the presence of default configuration classes. Specifically, AnnotationConfigContextLoader will detect all - static inner classes of the test class that meet the requirements - for configuration class implementations as specified in the Javadoc - for @Configuration. In the following - example, the OrderServiceTest class declares - a static inner configuration class named - Config that will be automatically used to - load the ApplicationContext for the - test class. Note that the name of the configuration class is - arbitrary. In addition, a test class can contain more than one - static inner configuration class if desired. + static inner classes of the test class that meet the requirements for + configuration class implementations as specified in the Javadoc for + @Configuration. In the following + example, the OrderServiceTest class declares a + static inner configuration class named Config + that will be automatically used to load the + ApplicationContext for the test class. + Note that the name of the configuration class is arbitrary. In + addition, a test class can contain more than one static inner + configuration class if desired. @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from the @@ -1480,19 +1448,18 @@ public class OrderServiceTest {
        Mixing XML resources and annotated classes - It may sometimes be desirable to mix XML resources and - annotated classes (i.e., typically - @Configuration classes) to configure - an ApplicationContext for your tests. - For example, if you use XML configuration in production, you may - decide that you want to use - @Configuration classes to configure - specific Spring-managed components for your tests, or vice versa. As - mentioned in the TestContext - framework does not allow you to declare both - via @ContextConfiguration, but this - does not mean that you cannot use both. + It may sometimes be desirable to mix XML resources and annotated + classes (i.e., typically @Configuration + classes) to configure an + ApplicationContext for your tests. For + example, if you use XML configuration in production, you may decide + that you want to use @Configuration + classes to configure specific Spring-managed components for your + tests, or vice versa. As mentioned in the TestContext + framework does not allow you to declare both via + @ContextConfiguration, but this does + not mean that you cannot use both. If you want to use XML and @Configuration classes to configure @@ -1505,27 +1472,27 @@ public class OrderServiceTest { @ImportResource to import XML configuration files. Note that this behavior is semantically equivalent to how you configure your application in production: in - production configuration you will define either a set of XML - resource locations or a set of - @Configuration classes that your - production ApplicationContext will be - loaded from, but you still have the freedom to include or import the - other type of configuration. + production configuration you will define either a set of XML resource + locations or a set of @Configuration + classes that your production + ApplicationContext will be loaded from, + but you still have the freedom to include or import the other type of + configuration.
        Context configuration with context initializers To configure an - ApplicationContext for your tests - using context initializers, annotate your test class with - @ContextConfiguration and configure - the initializers attribute with an array that - contains references to classes that implement + ApplicationContext for your tests using + context initializers, annotate your test class with + @ContextConfiguration and configure the + initializers attribute with an array that contains + references to classes that implement ApplicationContextInitializer. The declared context initializers will then be used to initialize the - ConfigurableApplicationContext that - is loaded for your tests. Note that the concrete + ConfigurableApplicationContext that is + loaded for your tests. Note that the concrete ConfigurableApplicationContext type supported by each declared initializer must be compatible with the type of ApplicationContext created by @@ -1533,9 +1500,8 @@ public class OrderServiceTest { typically a GenericApplicationContext). Furthermore, the order in which the initializers are invoked depends on whether they implement Spring's - Ordered interface or are annotated - with Spring's @Order - annotation. + Ordered interface or are annotated with + Spring's @Order annotation. @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from TestConfig @@ -1547,14 +1513,14 @@ public class MyTest { // class body... } - It is also possible to omit the declaration of XML - configuration files or annotated classes in + It is also possible to omit the declaration of XML configuration + files or annotated classes in @ContextConfiguration entirely and instead declare only ApplicationContextInitializer classes - which are then responsible for registering beans in the context — - for example, by programmatically loading bean definitions from XML - files or configuration classes. + which are then responsible for registering beans in the context — for + example, by programmatically loading bean definitions from XML files + or configuration classes. @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be initialized by EntireAppInitializer @@ -1570,36 +1536,35 @@ public class MyTest { @ContextConfiguration supports boolean inheritLocations and - inheritInitializers attributes that denote - whether resource locations or annotated classes and context - initializers declared by superclasses should be - inherited. The default value for both flags is - true. This means that a test class inherits the - resource locations or annotated classes as well as the context - initializers declared by any superclasses. Specifically, the - resource locations or annotated classes for a test class are - appended to the list of resource locations or annotated classes - declared by superclasses. Similarly, the initializers for a given - test class will be added to the set of initializers defined by test - superclasses. Thus, subclasses have the option of + inheritInitializers attributes that denote whether + resource locations or annotated classes and context initializers + declared by superclasses should be inherited. The + default value for both flags is true. This means + that a test class inherits the resource locations or annotated classes + as well as the context initializers declared by any superclasses. + Specifically, the resource locations or annotated classes for a test + class are appended to the list of resource locations or annotated + classes declared by superclasses. Similarly, the initializers for a + given test class will be added to the set of initializers defined by + test superclasses. Thus, subclasses have the option of extending the resource locations, annotated classes, or context initializers. If @ContextConfiguration's inheritLocations or inheritInitializers attribute is set to - false, the resource locations or annotated - classes and the context initializers, respectively, for the test - class shadow and effectively replace the - configuration defined by superclasses. + false, the resource locations or annotated classes + and the context initializers, respectively, for the test class + shadow and effectively replace the configuration + defined by superclasses. In the following example that uses XML resource locations, the ApplicationContext for ExtendedTest will be loaded from "base-config.xml" and - "extended-config.xml", in that order. Beans - defined in "extended-config.xml" may therefore + role="bold">and "extended-config.xml", + in that order. Beans defined in + "extended-config.xml" may therefore override (i.e., replace) those defined in "base-config.xml". @@ -1618,14 +1583,14 @@ public class ExtendedTest extends BaseTest { // class body... } - Similarly, in the following example that uses annotated - classes, the ApplicationContext for + Similarly, in the following example that uses annotated classes, + the ApplicationContext for ExtendedTest will be loaded from the - BaseConfig and ExtendedConfig - classes, in that order. Beans defined in - ExtendedConfig may therefore override (i.e., - replace) those defined in BaseConfig. + BaseConfig and + ExtendedConfig classes, in that order. Beans + defined in ExtendedConfig may therefore + override (i.e., replace) those defined in + BaseConfig. @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be loaded from BaseConfig @@ -1644,12 +1609,11 @@ public class ExtendedTest extends BaseTest { ApplicationContext for ExtendedTest will be initialized using BaseInitializer and - ExtendedInitializer. Note, however, that the - order in which the initializers are invoked depends on whether they - implement Spring's Ordered interface - or are annotated with Spring's @Order - annotation. + role="bold">and ExtendedInitializer. + Note, however, that the order in which the initializers are invoked + depends on whether they implement Spring's + Ordered interface or are annotated with + Spring's @Order annotation. @RunWith(SpringJUnit4ClassRunner.class) // ApplicationContext will be initialized by BaseInitializer @@ -1672,19 +1636,18 @@ public class ExtendedTest extends BaseTest { Spring 3.1 introduced first-class support in the framework for the notion of environments and profiles (a.k.a., bean definition profiles), and integration tests can be - configured to activate particular bean definition profiles for - various testing scenarios. This is achieved by annotating a test - class with the @ActiveProfiles - annotation and supplying a list of profiles that should be activated - when loading the ApplicationContext - for the test. + configured to activate particular bean definition profiles for various + testing scenarios. This is achieved by annotating a test class with + the @ActiveProfiles annotation and + supplying a list of profiles that should be activated when loading the + ApplicationContext for the test. @ActiveProfiles may be used with any implementation of the new SmartContextLoader SPI, but - @ActiveProfiles is not supported - with implementations of the older + @ActiveProfiles is not supported with + implementations of the older ContextLoader SPI. @@ -1746,25 +1709,23 @@ public class TransferServiceTest { } When TransferServiceTest is run, its - ApplicationContext will be loaded - from the app-config.xml configuration file in - the root of the classpath. If you inspect - app-config.xml you'll notice that the - accountRepository bean has a dependency on a - dataSource bean; however, + ApplicationContext will be loaded from + the app-config.xml configuration file in the root + of the classpath. If you inspect app-config.xml + you'll notice that the accountRepository bean has a + dependency on a dataSource bean; however, dataSource is not defined as a top-level bean. Instead, dataSource is defined twice: once in the production profile and once in the dev profile. By annotating TransferServiceTest with - @ActiveProfiles("dev") we instruct - the Spring TestContext Framework to load the + @ActiveProfiles("dev") we instruct the + Spring TestContext Framework to load the ApplicationContext with the active profiles set to {"dev"}. As a result, an embedded - database will be created, and the - accountRepository bean will be wired with a - reference to the development + database will be created, and the accountRepository + bean will be wired with a reference to the development DataSource. And that's likely what we want in an integration test. @@ -1887,23 +1848,21 @@ public class TransferServiceTest { @WebAppConfiguration. The presence of - @WebAppConfiguration on your test - class instructs the TestContext framework (TCF) that a + @WebAppConfiguration on your test class + instructs the TestContext framework (TCF) that a WebApplicationContext (WAC) should be loaded for your integration tests. In the background the TCF makes sure that a MockServletContext is - created and supplied to your test's WAC. By default the base - resource path for your - MockServletContext will be set to - "src/main/webapp". This is interpreted as a - path relative to the root of your JVM (i.e., normally the path to + created and supplied to your test's WAC. By default the base resource + path for your MockServletContext will + be set to "src/main/webapp". This is interpreted + as a path relative to the root of your JVM (i.e., normally the path to your project). If you're familiar with the directory structure of a web application in a Maven project, you'll know that - "src/main/webapp" is the default location for - the root of your WAR. If you need to override this default, simply - provide an alternate path to the - @WebAppConfiguration annotation - (e.g., + "src/main/webapp" is the default location for the + root of your WAR. If you need to override this default, simply provide + an alternate path to the + @WebAppConfiguration annotation (e.g., @WebAppConfiguration("src/test/webapp")). If you wish to reference a base resource path from the classpath instead of the file system, just use Spring's @@ -1912,9 +1871,9 @@ public class TransferServiceTest { Please note that Spring's testing support for WebApplicationContexts is on par with its support for standard - ApplicationContexts. When testing - with a WebApplicationContext you are - free to declare either XML configuration files or + ApplicationContexts. When testing with + a WebApplicationContext you are free to + declare either XML configuration files or @Configuration classes via @ContextConfiguration. You are of course also free to use any other test annotations such as @@ -1944,19 +1903,18 @@ public class WacTests { The above example demonstrates the TestContext framework's - support for convention over configuration. If - you annotate a test class with - @WebAppConfiguration without - specifying a resource base path, the resource path will effectively - default to "file:src/main/webapp". Similarly, - if you declare @ContextConfiguration - without specifying resource - locations, annotated - classes, or context + support for convention over configuration. If you + annotate a test class with + @WebAppConfiguration without specifying + a resource base path, the resource path will effectively default to + "file:src/main/webapp". Similarly, if you declare + @ContextConfiguration without + specifying resource locations, + annotated classes, or context initializers, Spring will attempt to detect the presence of your configuration using conventions (i.e., - "WacTests-context.xml" in the same package as - the WacTests class or static nested + "WacTests-context.xml" in the same package as the + WacTests class or static nested @Configuration classes). @@ -1976,13 +1934,13 @@ public class WacTests { This example demonstrates how to explicitly declare a resource - base path with @WebAppConfiguration - and an XML resource location with + base path with @WebAppConfiguration and + an XML resource location with @ContextConfiguration. The important - thing to note here is the different semantics for paths with these - two annotations. By default, - @WebAppConfiguration resource paths - are file system based; whereas, + thing to note here is the different semantics for paths with these two + annotations. By default, + @WebAppConfiguration resource paths are + file system based; whereas, @ContextConfiguration resource locations are classpath based. @@ -2012,13 +1970,13 @@ public class WacTests { To provide comprehensive web testing support, Spring 3.2 introduces a new - ServletTestExecutionListener that - is enabled by default. When testing against a + ServletTestExecutionListener that is + enabled by default. When testing against a WebApplicationContext this TestExecutionListener sets up default thread-local state via Spring Web's - RequestContextHolder before each - test method and creates a + RequestContextHolder before each test + method and creates a MockHttpServletRequest, MockHttpServletResponse, and ServletWebRequest based on the base @@ -2032,16 +1990,15 @@ public class WacTests { thread-local state. Once you have a - WebApplicationContext loaded for - your test you might find that you need to interact with the web - mocks — for example, to set up your test fixture or to perform - assertions after invoking your web component. The following - example demonstrates which mocks can be autowired into your test - instance. Note that the - WebApplicationContext and - MockServletContext are both cached - across the test suite; whereas, the other mocks are managed per - test method by the + WebApplicationContext loaded for your + test you might find that you need to interact with the web mocks — + for example, to set up your test fixture or to perform assertions + after invoking your web component. The following example + demonstrates which mocks can be autowired into your test instance. + Note that the WebApplicationContext + and MockServletContext are both + cached across the test suite; whereas, the other mocks are managed + per test method by the ServletTestExecutionListener. @@ -2074,19 +2031,19 @@ public class WacTests { Once the TestContext framework loads an ApplicationContext (or - WebApplicationContext) for a test, - that context will be cached and reused for WebApplicationContext) for a test, that + context will be cached and reused for all subsequent tests that declare the same - unique context configuration within the same test suite. To - understand how caching works, it is important to understand what is - meant by unique and test + unique context configuration within the same test suite. To understand + how caching works, it is important to understand what is meant by + unique and test suite. An ApplicationContext can be uniquely identified by the combination of configuration parameters that are used to load it. Consequently, the - unique combination of configuration parameters are used to generate - a key under which the context is cached. The + unique combination of configuration parameters are used to generate a + key under which the context is cached. The TestContext framework uses the following configuration parameters to build the context cache key: @@ -2102,8 +2059,8 @@ public class WacTests { - contextInitializerClasses - (from @ContextConfiguration) + contextInitializerClasses (from + @ContextConfiguration) @@ -2130,9 +2087,9 @@ public class WacTests { ApplicationContext and store it in a static context cache under a key that is based solely on those locations. So if TestClassB - also defines {"app-config.xml", - "test-config.xml"} for its locations (either explicitly or - implicitly through inheritance) but does not define + also defines {"app-config.xml", "test-config.xml"} + for its locations (either explicitly or implicitly through + inheritance) but does not define @WebAppConfiguration, a different ContextLoader, different active profiles, or different context initializers, then the same @@ -2145,23 +2102,22 @@ public class WacTests { Test suites and forked processes The Spring TestContext framework stores application contexts - in a static cache. This means that the - context is literally stored in a static - variable. In other words, if tests execute in separate processes - the static cache will be cleared between each test execution, and - this will effectively disable the caching mechanism. + in a static cache. This means that the context + is literally stored in a static variable. In + other words, if tests execute in separate processes the static cache + will be cleared between each test execution, and this will + effectively disable the caching mechanism. To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE. Similarly, when - executing tests with a build framework such as Ant, Maven, or - Gradle it is important to make sure that the build framework does - not fork between tests. For example, if the - fork between tests. For example, if the forkMode for the Maven Surefire plug-in is set to always - or pertest, the TestContext framework will not - be able to cache application contexts between test classes and the + or pertest, the TestContext framework will not be + able to cache application contexts between test classes and the build process will run significantly slower as a result. @@ -2169,13 +2125,13 @@ public class WacTests { context and requires reloading — for example, by modifying a bean definition or the state of an application object — you can annotate your test class or test method with - @DirtiesContext (see the discussion - of @DirtiesContext in ). This instructs + @DirtiesContext (see the discussion of + @DirtiesContext in ). This instructs Spring to remove the context from the cache and rebuild the - application context before executing the next test. Note that - support for the @DirtiesContext - annotation is provided by the + application context before executing the next test. Note that support + for the @DirtiesContext annotation is + provided by the DirtiesContextTestExecutionListener which is enabled by default.
        @@ -2185,34 +2141,33 @@ public class WacTests { Dependency injection of test fixtures When you use the - DependencyInjectionTestExecutionListener — - which is configured by default — the dependencies of your test - instances are injected from beans in the - application context that you configured with - @ContextConfiguration. You may use - setter injection, field injection, or both, depending on which - annotations you choose and whether you place them on setter methods or - fields. For consistency with the annotation support introduced in - Spring 2.5 and 3.0, you can use Spring's - @Autowired annotation or the - @Inject annotation from JSR 300. + DependencyInjectionTestExecutionListener — which + is configured by default — the dependencies of your test instances are + injected from beans in the application context that + you configured with + @ContextConfiguration. You may use setter + injection, field injection, or both, depending on which annotations you + choose and whether you place them on setter methods or fields. For + consistency with the annotation support introduced in Spring 2.5 and + 3.0, you can use Spring's @Autowired + annotation or the @Inject annotation from + JSR 300. The TestContext framework does not instrument the manner in which a test instance is instantiated. Thus the use of @Autowired or - @Inject for constructors has no - effect for test classes. + @Inject for constructors has no effect + for test classes. Because @Autowired is used to - perform autowiring - by type , if you have multiple bean definitions of - the same type, you cannot rely on this approach for those particular - beans. In that case, you can use - @Autowired in conjunction with - @Qualifier. As of Spring 3.0 you may - also choose to use @Inject in + perform autowiring by + type , if you have multiple bean definitions of the + same type, you cannot rely on this approach for those particular beans. + In that case, you can use @Autowired in + conjunction with @Qualifier. As of Spring + 3.0 you may also choose to use @Inject in conjunction with @Named. Alternatively, if your test class has access to its ApplicationContext, you can perform an explicit @@ -2224,35 +2179,33 @@ public class WacTests { @Autowired or @Inject. Alternatively, you can disable dependency injection altogether by explicitly configuring your class - with @TestExecutionListeners and - omitting + with @TestExecutionListeners and omitting DependencyInjectionTestExecutionListener.class from the list of listeners. Consider the scenario of testing a HibernateTitleRepository class, as outlined in - the Goals section. - The next two code listings demonstrate the use of - @Autowired on fields and setter - methods. The application context configuration is presented after all - sample code listings. + the Goals section. The + next two code listings demonstrate the use of + @Autowired on fields and setter methods. + The application context configuration is presented after all sample code + listings. - The dependency injection behavior in the following code - listings is not specific to JUnit. The same DI techniques can be - used in conjunction with any testing framework. + The dependency injection behavior in the following code listings + is not specific to JUnit. The same DI techniques can be used in + conjunction with any testing framework. The following examples make calls to static assertion methods - such as assertNotNull() but without prepending - the call with Assert. In such cases, assume that - the method was properly imported through an import - static declaration that is not shown in the - example. + such as assertNotNull() but without prepending the + call with Assert. In such cases, assume that the + method was properly imported through an import + static declaration that is not shown in the example. The first code listing shows a JUnit-based implementation of the - test class that uses @Autowired for - field injection. + test class that uses @Autowired for field + injection. @RunWith(SpringJUnit4ClassRunner.class) // specifies the Spring configuration to load for this test fixture @@ -2319,10 +2272,10 @@ public class HibernateTitleRepositoryTests { </beans> - If you are extending from a Spring-provided test base class - that happens to use @Autowired on one - of its setter methods, you might have multiple beans of the affected - type defined in your application context: for example, multiple + If you are extending from a Spring-provided test base class that + happens to use @Autowired on one of its + setter methods, you might have multiple beans of the affected type + defined in your application context: for example, multiple DataSource beans. In such a case, you can override the setter method and use the @Qualifier annotation to indicate a @@ -2345,8 +2298,8 @@ public class HibernateTitleRepositoryTests { against <qualifier> declarations within the corresponding <bean> definitions. The bean name is used as a fallback qualifier value, so you may effectively - also point to a specific bean by name there (as shown above, - assuming that "myDataSource" is the bean id). + also point to a specific bean by name there (as shown above, assuming + that "myDataSource" is the bean id).
        @@ -2354,10 +2307,10 @@ public class HibernateTitleRepositoryTests { Testing request and session scoped beans Request and session - scoped beans have been supported by Spring for several years - now, but it's always been a bit non-trivial to test them. As of Spring - 3.2 it's now a breeze to test your request-scoped and session-scoped - beans by following these steps. + scoped beans have been supported by Spring for several years now, + but it's always been a bit non-trivial to test them. As of Spring 3.2 + it's now a breeze to test your request-scoped and session-scoped beans + by following these steps.
        @@ -2368,8 +2321,8 @@ public class HibernateTitleRepositoryTests { - Inject the mock request or session into your test instance - and prepare your test fixture as appropriate. + Inject the mock request or session into your test instance and + prepare your test fixture as appropriate. @@ -2384,13 +2337,13 @@ public class HibernateTitleRepositoryTests { The following code snippet displays the XML configuration for a - login use case. Note that the userService bean has - a dependency on a request-scoped loginAction bean. - Also, the LoginAction is instantiated using - SpEL expressions that retrieve the - username and password from the current HTTP request. In our test, we - will want to configure these request parameters via the mock managed - by the TestContext framework. + login use case. Note that the userService bean has a + dependency on a request-scoped loginAction bean. + Also, the LoginAction is instantiated using SpEL expressions that retrieve the username + and password from the current HTTP request. In our test, we will want to + configure these request parameters via the mock managed by the + TestContext framework. Request-scoped bean configuration @@ -2414,16 +2367,15 @@ public class HibernateTitleRepositoryTests { In RequestScopedBeanTests we inject both the UserService (i.e., the subject under test) and the MockHttpServletRequest into our test - instance. Within our requestScope() test method - we set up our test fixture by setting request parameters in the - provided MockHttpServletRequest. When the + instance. Within our requestScope() test method we + set up our test fixture by setting request parameters in the provided + MockHttpServletRequest. When the loginUser() method is invoked on our - userService we are assured that the user service - has access to the request-scoped loginAction for - the current MockHttpServletRequest (i.e., the - one we just set parameters in). We can then perform assertions against - the results based on the known inputs for the username and - password. + userService we are assured that the user service has + access to the request-scoped loginAction for the + current MockHttpServletRequest (i.e., the one we + just set parameters in). We can then perform assertions against the + results based on the known inputs for the username and password. Request-scoped bean test @@ -2449,14 +2401,14 @@ public class RequestScopedBeanTests { } - The following code snippet is similar to the one we saw above - for a request-scoped bean; however, this time the - userService bean has a dependency on a - session-scoped userPreferences bean. Note that the - UserPreferences bean is instantiated using a - SpEL expression that retrieves the theme from the - current HTTP session. In our test, we will need to configure a theme - in the mock session managed by the TestContext framework. + The following code snippet is similar to the one we saw above for + a request-scoped bean; however, this time the + userService bean has a dependency on a session-scoped + userPreferences bean. Note that the + UserPreferences bean is instantiated using a SpEL + expression that retrieves the theme from the + current HTTP session. In our test, we will need to configure a theme in + the mock session managed by the TestContext framework. Session-scoped bean configuration @@ -2484,11 +2436,10 @@ public class RequestScopedBeanTests { fixture by setting the expected "theme" attribute in the provided MockHttpSession. When the processUserPreferences() method is invoked on our - userService we are assured that the user service - has access to the session-scoped userPreferences - for the current MockHttpSession, and we can - perform assertions against the results based on the configured - theme. + userService we are assured that the user service has + access to the session-scoped userPreferences for the + current MockHttpSession, and we can perform + assertions against the results based on the configured theme. Session-scoped bean test @@ -2519,30 +2470,28 @@ public class SessionScopedBeanTests { In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that - TransactionalTestExecutionListener is - configured by default, even if you do not explicitly declare + TransactionalTestExecutionListener is configured + by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must provide a PlatformTransactionManager bean in the application context loaded by @ContextConfiguration semantics. In - addition, you must declare - @Transactional either at the class or - method level for your tests. + addition, you must declare @Transactional + either at the class or method level for your tests. For class-level transaction configuration (i.e., setting an - explicit bean name for the transaction manager and the default - rollback flag), see the - @TransactionConfiguration entry in the - annotation + explicit bean name for the transaction manager and the default rollback + flag), see the @TransactionConfiguration + entry in the annotation support section. - If transactions are not enabled for the entire test class, you - can annotate methods explicitly with + If transactions are not enabled for the entire test class, you can + annotate methods explicitly with @Transactional. To control whether a - transaction should commit for a particular test method, you can use - the @Rollback annotation to override - the class-level default rollback setting. + transaction should commit for a particular test method, you can use the + @Rollback annotation to override the + class-level default rollback setting. AbstractTransactionalJUnit4SpringContextTests @@ -2553,14 +2502,13 @@ public class SessionScopedBeanTests { Occasionally you need to execute certain code before or after a transactional test method but outside the transactional context, for - example, to verify the initial database state prior to execution of - your test or to verify expected transactional commit behavior after - test execution (if the test was configured not to roll back the - transaction). + example, to verify the initial database state prior to execution of your + test or to verify expected transactional commit behavior after test + execution (if the test was configured not to roll back the transaction). TransactionalTestExecutionListener supports the @BeforeTransaction and - @AfterTransaction annotations exactly - for such scenarios. Simply annotate any public void + @AfterTransaction annotations exactly for + such scenarios. Simply annotate any public void method in your test class with one of these annotations, and the TransactionalTestExecutionListener ensures that your before transaction method or after @@ -2569,12 +2517,11 @@ public class SessionScopedBeanTests { Any before methods (such as methods - annotated with JUnit's @Before) and - any after methods (such as methods annotated - with JUnit's @After) are executed - within a transaction. In addition, - methods annotated with - @BeforeTransaction or + annotated with JUnit's @Before) and any + after methods (such as methods annotated with + JUnit's @After) are executed within a transaction. In addition, methods + annotated with @BeforeTransaction or @AfterTransaction are naturally not executed for tests annotated with @NotTransactional. However, @@ -2623,21 +2570,21 @@ public class FictitiousTransactionalTest { } - + Avoid false positives when testing ORM code - When you test application code that manipulates the state of - the Hibernate session, make sure to flush the - underlying session within test methods that execute that code. - Failing to flush the underlying session can produce false - positives: your test may pass, but the same code throws - an exception in a live, production environment. In the following + When you test application code that manipulates the state of the + Hibernate session, make sure to flush the + underlying session within test methods that execute that code. Failing + to flush the underlying session can produce false + positives: your test may pass, but the same code throws an + exception in a live, production environment. In the following Hibernate-based example test case, one method demonstrates a false positive, and the other method correctly exposes the results of - flushing the session. Note that this applies to JPA and any other - ORM frameworks that maintain an in-memory unit of + flushing the session. Note that this applies to JPA and any other ORM + frameworks that maintain an in-memory unit of work. // ... @@ -2688,9 +2635,9 @@ public void updateWithSessionFlush() { - applicationContext: Use this - variable to perform explicit bean lookups or to test the - state of the context as a whole. + applicationContext: Use this variable + to perform explicit bean lookups or to test the state of the + context as a whole. @@ -2698,29 +2645,28 @@ public void updateWithSessionFlush() { AbstractTransactionalJUnit4SpringContextTests: Abstract transactional extension of - AbstractJUnit4SpringContextTests that - also adds some convenience functionality for JDBC access. - Expects a javax.sql.DataSource bean and a - PlatformTransactionManager bean - to be defined in the ApplicationContext. - When you extend + AbstractJUnit4SpringContextTests that also + adds some convenience functionality for JDBC access. Expects a + javax.sql.DataSource bean and a + PlatformTransactionManager bean to + be defined in the ApplicationContext. When + you extend AbstractTransactionalJUnit4SpringContextTests - you can access the following protected - instance variables: + you can access the following protected instance + variables: applicationContext: Inherited from the AbstractJUnit4SpringContextTests - superclass. Use this variable to perform explicit bean - lookups or to test the state of the context as a - whole. + superclass. Use this variable to perform explicit bean lookups + or to test the state of the context as a whole. jdbcTemplate: Use this variable to - execute SQL statements to query the database. Such queries - can be used to confirm database state both prior + execute SQL statements to query the database. Such queries can + be used to confirm database state both prior to and after execution of database-related application code, and Spring ensures that such queries run in the scope of the same transaction as the @@ -2737,8 +2683,8 @@ public void updateWithSessionFlush() { These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy — for example, if you want to directly extend the class - you are testing — you can configure your own custom test classes - by using + you are testing — you can configure your own custom test classes by + using @RunWith(SpringJUnit4ClassRunner.class), @ContextConfiguration, @TestExecutionListeners, and so @@ -2752,18 +2698,17 @@ public void updateWithSessionFlush() { The Spring TestContext Framework offers full integration with JUnit 4.5+ through a custom runner (tested on JUnit 4.5 – 4.10). By annotating test classes with - @RunWith(SpringJUnit4ClassRunner.class), - developers can implement standard JUnit-based unit and integration - tests and simultaneously reap the benefits of the TestContext - framework such as support for loading application contexts, - dependency injection of test instances, transactional test method - execution, and so on. The following code listing displays the - minimal requirements for configuring a test class to run with the - custom Spring Runner. + @RunWith(SpringJUnit4ClassRunner.class), developers + can implement standard JUnit-based unit and integration tests and + simultaneously reap the benefits of the TestContext framework such as + support for loading application contexts, dependency injection of test + instances, transactional test method execution, and so on. The + following code listing displays the minimal requirements for + configuring a test class to run with the custom Spring Runner. @TestExecutionListeners is configured with an empty list in order to disable the default listeners, which - otherwise would require an ApplicationContext to be configured - through @ContextConfiguration. + otherwise would require an ApplicationContext to be configured through + @ContextConfiguration. @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({}) @@ -2797,9 +2742,9 @@ public class SimpleTest { - applicationContext: Use this - variable to perform explicit bean lookups or to test the - state of the context as a whole. + applicationContext: Use this variable + to perform explicit bean lookups or to test the state of the + context as a whole. @@ -2807,29 +2752,28 @@ public class SimpleTest { AbstractTransactionalTestNGSpringContextTests: Abstract transactional extension of - AbstractTestNGSpringContextTests that - adds some convenience functionality for JDBC access. Expects a + AbstractTestNGSpringContextTests that adds + some convenience functionality for JDBC access. Expects a javax.sql.DataSource bean and a - PlatformTransactionManager bean - to be defined in the ApplicationContext. - When you extend + PlatformTransactionManager bean to + be defined in the ApplicationContext. When + you extend AbstractTransactionalTestNGSpringContextTests, - you can access the following protected - instance variables: + you can access the following protected instance + variables: applicationContext: Inherited from the AbstractTestNGSpringContextTests - superclass. Use this variable to perform explicit bean - lookups or to test the state of the context as a - whole. + superclass. Use this variable to perform explicit bean lookups + or to test the state of the context as a whole. jdbcTemplate: Use this variable to - execute SQL statements to query the database. Such queries - can be used to confirm database state both prior + execute SQL statements to query the database. Such queries can + be used to confirm database state both prior to and after execution of database-related application code, and Spring ensures that such queries run in the scope of the same transaction as the @@ -2846,8 +2790,8 @@ public class SimpleTest { These classes are a convenience for extension. If you do not want your test classes to be tied to a Spring-specific class hierarchy — for example, if you want to directly extend the class - you are testing — you can configure your own custom test classes - by using @ContextConfiguration, + you are testing — you can configure your own custom test classes by + using @ContextConfiguration, @TestExecutionListeners, and so on, and by manually instrumenting your test class with a TestContextManager. See the source code of @@ -2873,71 +2817,70 @@ public class SimpleTest { xl:href="https://github.com/SpringSource/spring-test-mvc">spring-test-mvc project is still available on GitHub and can be used in conjunction with Spring Framework 3.1.x. Applications upgrading to 3.2 - should replace the spring-test-mvc dependency - with a dependency on spring-test. + should replace the spring-test-mvc dependency with + a dependency on spring-test. The spring-test module uses a different package org.springframework.test.web but otherwise is nearly identical with two exceptions. One is support for - features new in 3.2 (e.g. asynchronous web requests). The other - relates to the options for creating a MockMvc - instance. In Spring Framework 3.2, this can only be done through the - TestContext framework, which provides caching benefits for the loaded + features new in 3.2 (e.g. asynchronous web requests). The other relates + to the options for creating a MockMvc instance. + In Spring Framework 3.2, this can only be done through the TestContext + framework, which provides caching benefits for the loaded configuration. The Spring MVC Test framework provides first class JUnit support for testing client and server-side Spring MVC code through a fluent API. Typically it loads the actual Spring configuration - through the TestContext framework and always uses - the DispatcherServlet to process requests thus + through the TestContext framework and always uses the + DispatcherServlet to process requests thus approximating full integration tests without requiring a running Servlet container. - Client-side tests are RestTemplate-based - and allow tests for code that relies on the - RestTemplate without requiring a running server - to respond to the requests. + Client-side tests are RestTemplate-based and + allow tests for code that relies on the + RestTemplate without requiring a running server to + respond to the requests.
        Server-Side Tests - Before Spring Framework 3.2, the most likely way to test a - Spring MVC controller was to write a unit test that instantiates the + Before Spring Framework 3.2, the most likely way to test a Spring + MVC controller was to write a unit test that instantiates the controller, injects it with mock or stub dependencies, and then calls its methods directly, using a MockHttpServletRequest and MockHttpServletResponse where necessary. Although this is pretty easy to do, controllers have many - annotations, and much remains untested. Request mappings, data - binding, type conversion, and validation are just a few examples of - what isn't tested. Furthermore, there are other types of annotated - methods such as @InitBinder, + annotations, and much remains untested. Request mappings, data binding, + type conversion, and validation are just a few examples of what isn't + tested. Furthermore, there are other types of annotated methods such as + @InitBinder, @ModelAttribute, and @ExceptionHandler that get invoked as part of request processing. The idea behind Spring MVC Test is to be able to re-write those - controller tests by performing actual requests and generating - responses, as they would be at runtime, along the way invoking - controllers through the Spring MVC - DispatcherServlet. Controllers can still be - injected with mock dependencies, so tests can remain focused on the - web layer. + controller tests by performing actual requests and generating responses, + as they would be at runtime, along the way invoking controllers through + the Spring MVC DispatcherServlet. Controllers can + still be injected with mock dependencies, so tests can remain focused on + the web layer. Spring MVC Test builds on the familiar "mock" implementations of the Servlet API available in the spring-test - module. This allows performing requests and generating responses - without the need for running in a Servlet container. For the most part + module. This allows performing requests and generating responses without + the need for running in a Servlet container. For the most part everything should work as it does at runtime with the exception of JSP rendering, which is not available outside a Servlet container. Furthermore, if you are familiar with how the MockHttpServletResponse works, you'll know that forwards and redirects are not actually executed. Instead "forwarded" - and "redirected" URLs are saved and can be asserted in tests. This - means if you are using JSPs, you can verify the JSP page to which the - request was forwarded. + and "redirected" URLs are saved and can be asserted in tests. This means + if you are using JSPs, you can verify the JSP page to which the request + was forwarded. All other means of rendering including @ResponseBody methods and @@ -2980,18 +2923,17 @@ public class ExampleTests { The test relies on the WebApplicationContext support of the TestContext framework. It loads Spring - configuration from an XML configuration file located in the same - package as the test class (also supports JavaConfig) and injects the - created WebApplicationContext into the - test so a MockMvc instance can be created with - it. + configuration from an XML configuration file located in the same package + as the test class (also supports JavaConfig) and injects the created + WebApplicationContext into the test so a + MockMvc instance can be created with it. The MockMvc is then used to perform a request to "/accounts/1" and verify the resulting response status is 200, the response content type is - "application/json", and response content has a - JSON property called "name" with the value "Lee". JSON content is - inspected with the help of Jayway's "application/json", and response content has a JSON + property called "name" with the value "Lee". JSON content is inspected + with the help of Jayway's JsonPath project. There are lots of other options for verifying the result of the performed request and those will be discussed later. @@ -3004,13 +2946,13 @@ public class ExampleTests { MockMvcResultMatchers.*, and MockMvcBuilders.*. An easy way to find these classes is to search for types matching - "MockMvc*". If using Eclipse, be sure to add - them as "favorite static members" in the Eclipse preferences under + "MockMvc*". If using Eclipse, be sure to add them + as "favorite static members" in the Eclipse preferences under Java -> Editor -> Content Assist -> Favorites. That will allow use of content assist after - typing the first character of the static method name. Other IDEs - (e.g. IntelliJ) may not require any additional configuration. Just - check the support for code completion on static members. + typing the first character of the static method name. Other IDEs (e.g. + IntelliJ) may not require any additional configuration. Just check the + support for code completion on static members.
        @@ -3020,11 +2962,11 @@ public class ExampleTests { MockMvc that can be used to perform requests. There are two main options. - The first option is to point to Spring MVC configuration - through the TestContext framework, which loads - the Spring configuration and injects a - WebApplicationContext into the test - to use to create a MockMvc: + The first option is to point to Spring MVC configuration through + the TestContext framework, which loads the Spring + configuration and injects a + WebApplicationContext into the test to + use to create a MockMvc: @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @@ -3048,9 +2990,9 @@ public class MyWebTests { The second option is to simply register a controller instance without loading any Spring configuration. Instead basic Spring MVC configuration suitable for testing annotated controllers is - automatically created. The created configuration is comparable to - that of the MVC JavaConfig (and the MVC namespace) and can be - customized to a degree through builder-style methods: + automatically created. The created configuration is comparable to that + of the MVC JavaConfig (and the MVC namespace) and can be customized to + a degree through builder-style methods: public class MyWebTests { @@ -3069,20 +3011,20 @@ public class MyWebTests { The "webAppContextSetup" loads the actual Spring MVC configuration resulting in a more complete integration - test. Since the TestContext framework caches - the loaded Spring configuration, it helps to keep tests running fast - even as more tests get added. Furthermore, you can inject mock - services into controllers through Spring configuration, in order to - remain focused on testing the web layer. Here is an example of - declaring a mock service with Mockito: + test. Since the TestContext framework caches the + loaded Spring configuration, it helps to keep tests running fast even + as more tests get added. Furthermore, you can inject mock services + into controllers through Spring configuration, in order to remain + focused on testing the web layer. Here is an example of declaring a + mock service with Mockito: <bean id="accountService" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="org.example.AccountService"/> </bean> - Then you can inject the mock service into the test in order - set up and verify expectations: + Then you can inject the mock service into the test in order set + up and verify expectations: @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @@ -3101,19 +3043,19 @@ public class AccountTests { } - The "standaloneSetup" on the other hand - is a little closer to a unit test. It tests one controller at a - time, the controller can be injected with mock dependencies - manually, and it doesn't involve loading Spring configuration. Such - tests are more focused in style and make it easier to see which - controller is being tested, whether any specific Spring MVC - configuration is required to work, and so on. The "standaloneSetup" - is also a very convenient way to write ad-hoc tests to verify some - behavior or to debug an issue. + The "standaloneSetup" on the other hand is + a little closer to a unit test. It tests one controller at a time, the + controller can be injected with mock dependencies manually, and it + doesn't involve loading Spring configuration. Such tests are more + focused in style and make it easier to see which controller is being + tested, whether any specific Spring MVC configuration is required to + work, and so on. The "standaloneSetup" is also a very convenient way + to write ad-hoc tests to verify some behavior or to debug an + issue. - Just like with integration vs unit testing, there is no right - or wrong answer. Using the "standaloneSetup" does imply the need for - some additional "webAppContextSetup" tests to verify the Spring MVC + Just like with integration vs unit testing, there is no right or + wrong answer. Using the "standaloneSetup" does imply the need for some + additional "webAppContextSetup" tests to verify the Spring MVC configuration. Alternatively, you can decide write all tests with "webAppContextSetup" and always test against actual Spring MVC configuration. @@ -3151,22 +3093,21 @@ public class AccountTests { doesn't check the query string, as is most often the case, then it doesn't matter how parameters are added. Keep in mind though that parameters provided in the URI template will be decoded while - parameters provided through the param(...) - method are expected to be decoded. + parameters provided through the param(...) method + are expected to be decoded. - In most cases it's preferable to leave out the context path - and the Servlet path from the request URI. If you must test with the - full request URI, be sure to set the - contextPath and - servletPath accordingly so that request - mappings will work: + In most cases it's preferable to leave out the context path and + the Servlet path from the request URI. If you must test with the full + request URI, be sure to set the contextPath and + servletPath accordingly so that request mappings + will work: mockMvc.perform(get("/app/main/hotels/{id}").contextPath("/app").servletPath("/main")) - Looking at the above example, it would be cumbersome to set - the contextPath and servletPath with every performed request. That's - why you can define default request properties when building the + Looking at the above example, it would be cumbersome to set the + contextPath and servletPath with every performed request. That's why + you can define default request properties when building the MockMvc: public class MyWebTests { @@ -3185,10 +3126,10 @@ public class AccountTests { The above properties will apply to every request performed through the MockMvc. If the same property is - also specified on a given request, it will override the default - value. That is why, the HTTP method and URI don't matter, when - setting default request properties, since they must be specified on - every request. + also specified on a given request, it will override the default value. + That is why, the HTTP method and URI don't matter, when setting + default request properties, since they must be specified on every + request.
        @@ -3203,12 +3144,12 @@ public class AccountTests { MockMvcResultMatchers.* defines a number of static members, some of which return types with additional methods, - for asserting the result of the performed request. The assertions - fall in two general categories. + for asserting the result of the performed request. The assertions fall + in two general categories. The first category of assertions verify properties of the - response, i.e the response status, headers, and content. Those are - the most important things to test for. + response, i.e the response status, headers, and content. Those are the + most important things to test for. The second category of assertions go beyond the response, and allow inspecting Spring MVC specific constructs such as which @@ -3216,8 +3157,8 @@ public class AccountTests { raised and handled, what the content of the model is, what view was selected, what flash attributes were added, and so on. It is also possible to verify Servlet specific constructs such as request and - session attributes. The following test asserts that - binding/validation failed: + session attributes. The following test asserts that binding/validation + failed: mockMvc.perform(post("/persons")) @@ -3225,8 +3166,8 @@ mockMvc.perform(post("/persons")) .andExpect(model().attributeHasErrors("person")); - Many times when writing tests, it's useful to dump the result - of the performed request. This can be done as follows, where + Many times when writing tests, it's useful to dump the result of + the performed request. This can be done as follows, where print() is a static import from MockMvcResultHandlers: @@ -3235,8 +3176,8 @@ mockMvc.perform(post("/persons")) .andExpect(status().isOk()) .andExpect(model().attributeHasErrors("person")); - As long as request processing causes an unhandled exception, - the print() method will print all the available + As long as request processing causes an unhandled exception, the + print() method will print all the available result data to System.out. In some cases, you may want to get direct access to the result @@ -3247,8 +3188,8 @@ mockMvc.perform(post("/persons")) MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn(); // ... - When all tests repeat the same expectations, you can define - the common expectations once when building the + When all tests repeat the same expectations, you can define the + common expectations once when building the MockMvc: standaloneSetup(new SimpleController()) @@ -3256,8 +3197,8 @@ mockMvc.perform(post("/persons")) .alwaysExpect(content().contentType("application/json;charset=UTF-8")) .build() - Note that the expectation is always - applied and cannot be overridden without creating a separate + Note that the expectation is always applied + and cannot be overridden without creating a separate MockMvc instance. When JSON response content contains hypermedia links created @@ -3268,9 +3209,8 @@ mockMvc.perform(post("/persons")) mockMvc.perform(get("/people").accept(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.links[?(@.rel == 'self')].href").value("http://localhost:8080/people")); - When XML response content contains hypermedia links created - with Spring + When XML response content contains hypermedia links created with + Spring HATEOAS, the resulting links can be verified: Map<String, String> ns = Collections.singletonMap("ns", "http://www.w3.org/2005/Atom"); @@ -3289,8 +3229,8 @@ mockMvc.perform(get("/handle").accept(MediaType.APPLICATION_XML)) Registered filters will be invoked through MockFilterChain from - spring-test and the last filter will delegates - to the DispatcherServlet. + spring-test and the last filter will delegates to + the DispatcherServlet.
        @@ -3321,36 +3261,34 @@ mockServer.expect(requestTo("/greeting")).andRespond(withSuccess("Hello world", mockServer.verify(); - In the above example, - MockRestServiceServer -- the central class for - client-side REST tests -- configures the + In the above example, MockRestServiceServer + -- the central class for client-side REST tests -- configures the RestTemplate with a custom ClientHttpRequestFactory that asserts actual requests against expectations and returns "stub" responses. In - this case we expect a single request to "/greeting" and want to return - a 200 response with "text/plain" content. We could define as many + this case we expect a single request to "/greeting" and want to return a + 200 response with "text/plain" content. We could define as many additional requests and stub responses as necessary. Once expected requests and stub responses have been defined, the RestTemplate can be used in client-side code as usual. At the end of the tests mockServer.verify() - can be used to verify that all expected requests were - performed. + can be used to verify that all expected requests were performed.
        Static Imports - Just like with server-side tests, the fluent API for - client-side tests requires a few static imports. Those are easy to - find by searching "MockRest*". Eclipse users - should add "MockRestRequestMatchers.*" and + Just like with server-side tests, the fluent API for client-side + tests requires a few static imports. Those are easy to find by + searching "MockRest*". Eclipse users should add + "MockRestRequestMatchers.*" and "MockRestResponseCreators.*" as "favorite - static members" in the Eclipse preferences under Java - -> Editor -> Content Assist -> Favorites. That - allows using content assist after typing the first character of the - static method name. Other IDEs (e.g. IntelliJ) may not require any - additional configuration. Just check the support for code completion - on static members. + static members" in the Eclipse preferences under Java -> + Editor -> Content Assist -> Favorites. That allows + using content assist after typing the first character of the static + method name. Other IDEs (e.g. IntelliJ) may not require any additional + configuration. Just check the support for code completion on static + members.
        @@ -3368,11 +3306,10 @@ mockServer.verify(); The PetClinic application, available from the samples repository, illustrates - several features of the Spring TestContext - Framework in a JUnit 4.5+ environment. Most test - functionality is included in the - AbstractClinicTests, for which a partial listing - is shown below: + several features of the Spring TestContext Framework + in a JUnit 4.5+ environment. Most test functionality is included in the + AbstractClinicTests, for which a partial listing is + shown below: import static org.junit.Assert.assertEquals; // import ... @@ -3439,10 +3376,9 @@ public abstract class AbstractClinicTests extends Abstract The PetClinic application supports three data access technologies: JDBC, Hibernate, and JPA. By declaring - @ContextConfiguration without any - specific resource locations, the - AbstractClinicTests class will have its - application context loaded from the default location, + @ContextConfiguration without any specific + resource locations, the AbstractClinicTests class + will have its application context loaded from the default location, AbstractClinicTests-context.xml, which declares a common DataSource. Subclasses specify additional context locations that must declare a @@ -3451,8 +3387,8 @@ public abstract class AbstractClinicTests extends Abstract For example, the Hibernate implementation of the PetClinic tests contains the following implementation. For this example, - HibernateClinicTests does not contain a single - line of code: we only need to declare + HibernateClinicTests does not contain a single line + of code: we only need to declare @ContextConfiguration, and the tests are inherited from AbstractClinicTests. Because @ContextConfiguration is declared without @@ -3474,8 +3410,8 @@ public class HibernateClinicTests extends AbstractClinicTests { } typically specified in a common base class for all application-specific integration tests. Such a base class may also add useful instance variables — populated by Dependency Injection, naturally — such as a - SessionFactory in the case of an application - using Hibernate. + SessionFactory in the case of an application using + Hibernate. As far as possible, you should have exactly the same Spring configuration files in your integration tests as in the deployed @@ -3491,12 +3427,11 @@ public class HibernateClinicTests extends AbstractClinicTests { } combination like the Commons DBCP BasicDataSource and DataSourceTransactionManager or HibernateTransactionManager for them. You can - factor out this variant behavior into a single XML file, having the - choice between application server and a 'local' configuration separated - from all other configuration, which will not vary between the test and - production environments. In addition, it is advisable to use properties - files for connection settings. See the PetClinic application for an - example. + factor out this variant behavior into a single XML file, having the choice + between application server and a 'local' configuration separated from all + other configuration, which will not vary between the test and production + environments. In addition, it is advisable to use properties files for + connection settings. See the PetClinic application for an example.
        @@ -3522,8 +3457,8 @@ public class HibernateClinicTests extends AbstractClinicTests { } MockObjects.com: Web site - dedicated to mock objects, a technique for improving the design of - code within test-driven development. + dedicated to mock objects, a technique for improving the design of code + within test-driven development. @@ -3533,16 +3468,15 @@ public class HibernateClinicTests extends AbstractClinicTests { } EasyMock: Java - library that provides Mock Objects for interfaces - (and objects through the class extension) by generating them on the - fly using Java's proxy mechanism. Used by the - Spring Framework in its test suite. + library that provides Mock Objects for interfaces (and + objects through the class extension) by generating them on the fly using + Java's proxy mechanism. Used by the Spring Framework + in its test suite. JMock: Library that - supports test-driven development of Java code with mock - objects. + supports test-driven development of Java code with mock objects. From 3654a620fbbc8e5c6ae8e55064d097e7f3860744 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Sun, 10 Mar 2013 09:59:17 -0400 Subject: [PATCH 12/28] Disable AsyncTests in spring-test-mvc --- .../test/web/servlet/samples/standalone/AsyncTests.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java index f021e1355a..a3640dd6fa 100644 --- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/AsyncTests.java @@ -28,6 +28,7 @@ import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; @@ -58,6 +59,7 @@ public class AsyncTests { } @Test + @Ignore public void testCallable() throws Exception { MvcResult mvcResult = this.mockMvc.perform(get("/1").param("callable", "true")) .andDo(print()) @@ -73,6 +75,7 @@ public class AsyncTests { } @Test + @Ignore public void testDeferredResult() throws Exception { MvcResult mvcResult = this.mockMvc.perform(get("/1").param("deferredResult", "true")) .andExpect(request().asyncStarted()) From 8ab8e4f7c2023df3486cdc256fbab09bb1aae73e Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Sun, 10 Mar 2013 12:52:04 -0400 Subject: [PATCH 13/28] Make the methodParameter field of HandlerMethod final Previously the methodParameter array field was initialized lazily since it requires reflection. However, in practice the field is always used and there is not much benefit from the lazy initialization. In Spring Framework 3.2, the methodParameter field was copied when a new HandlerMethod instance (with the resolved bean) is created for performance reasons. That introduced a synchronization issue since the lazy initialization was not synchronized. Issue: SPR-10365 --- .../web/method/HandlerMethod.java | 40 +++++++++++++------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java index 9ed46d9cf2..aec22e4d5a 100644 --- a/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java +++ b/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java @@ -54,7 +54,7 @@ public class HandlerMethod { private final BeanFactory beanFactory; - private MethodParameter[] parameters; + private final MethodParameter[] parameters; private final Method bridgedMethod; @@ -69,6 +69,16 @@ public class HandlerMethod { this.beanFactory = null; this.method = method; this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); + this.parameters = initMethodParameters(); + } + + private MethodParameter[] initMethodParameters() { + int count = this.bridgedMethod.getParameterTypes().length; + MethodParameter[] result = new MethodParameter[count]; + for (int i = 0; i < count; i++) { + result[i] = new HandlerMethodParameter(i); + } + return result; } /** @@ -82,6 +92,7 @@ public class HandlerMethod { this.beanFactory = null; this.method = bean.getClass().getMethod(methodName, parameterTypes); this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); + this.parameters = initMethodParameters(); } /** @@ -99,10 +110,11 @@ public class HandlerMethod { this.beanFactory = beanFactory; this.method = method; this.bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); + this.parameters = initMethodParameters(); } /** - * Create an instance from another {@code HandlerMethod}. + * Copy constructor for use in sub-classes. */ protected HandlerMethod(HandlerMethod handlerMethod) { Assert.notNull(handlerMethod, "HandlerMethod is required"); @@ -113,6 +125,19 @@ public class HandlerMethod { this.parameters = handlerMethod.parameters; } + /** + * Re-create HandlerMethod with the resolved handler. + */ + private HandlerMethod(HandlerMethod handlerMethod, Object handler) { + Assert.notNull(handlerMethod, "handlerMethod is required"); + Assert.notNull(handler, "handler is required"); + this.bean = handler; + this.beanFactory = handlerMethod.beanFactory; + this.method = handlerMethod.method; + this.bridgedMethod = handlerMethod.bridgedMethod; + this.parameters = handlerMethod.parameters; + } + /** * Returns the bean for this handler method. */ @@ -150,13 +175,6 @@ public class HandlerMethod { * Returns the method parameters for this handler method. */ public MethodParameter[] getMethodParameters() { - if (this.parameters == null) { - int parameterCount = this.bridgedMethod.getParameterTypes().length; - this.parameters = new MethodParameter[parameterCount]; - for (int i = 0; i < parameterCount; i++) { - this.parameters[i] = new HandlerMethodParameter(i); - } - } return this.parameters; } @@ -201,9 +219,7 @@ public class HandlerMethod { String beanName = (String) this.bean; handler = this.beanFactory.getBean(beanName); } - HandlerMethod handlerMethod = new HandlerMethod(handler, this.method); - handlerMethod.parameters = getMethodParameters(); - return handlerMethod; + return new HandlerMethod(this, handler); } @Override From 5b6f149bf8aadc21c6a61bcdf35c8c04cbdd5969 Mon Sep 17 00:00:00 2001 From: Dave Syer Date: Sun, 10 Mar 2013 10:03:15 -0700 Subject: [PATCH 14/28] Fix test for daylight savings glitch --- .gitignore | 1 + .../springframework/scheduling/support/CronTriggerTests.java | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 67d798efd4..b1e4ec06c7 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ pom.xml /build buildSrc/build /spring-*/build +target/ # Eclipse artifacts, including WTP generated manifests .classpath diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java index 90acc959b3..a344774963 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java @@ -422,8 +422,8 @@ public class CronTriggerTests { @Test public void testSpecificHourSecond() throws Exception { - CronTrigger trigger = new CronTrigger("55 * 2 * * *", timeZone); - calendar.set(Calendar.HOUR_OF_DAY, 1); + CronTrigger trigger = new CronTrigger("55 * 10 * * *", timeZone); + calendar.set(Calendar.HOUR_OF_DAY, 9); calendar.set(Calendar.SECOND, 54); Date date = calendar.getTime(); TriggerContext context1 = getTriggerContext(date); From 4171646491096ceb5d11ae9ae4c878c5f552c195 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Mon, 11 Mar 2013 02:26:33 +0100 Subject: [PATCH 15/28] Document context hierarchy support in the TCF This commit updates the reference manual regarding the new support for @ContextHierarchy and hierarchy modes in @DirtiesContext. Issue: SPR-10357 --- src/reference/docbook/new-in-3.2.xml | 6 + src/reference/docbook/testing.xml | 377 +++++++++++++++++++++++---- 2 files changed, 327 insertions(+), 56 deletions(-) diff --git a/src/reference/docbook/new-in-3.2.xml b/src/reference/docbook/new-in-3.2.xml index 8d403c6ead..dc53ce9777 100644 --- a/src/reference/docbook/new-in-3.2.xml +++ b/src/reference/docbook/new-in-3.2.xml @@ -274,6 +274,12 @@ WebApplicationContext in integration tests + + Configuring context hierarchies + in integration tests + + Testing request and session scoped beans diff --git a/src/reference/docbook/testing.xml b/src/reference/docbook/testing.xml index e5bb9aafd7..bb26dc0c54 100644 --- a/src/reference/docbook/testing.xml +++ b/src/reference/docbook/testing.xml @@ -291,9 +291,9 @@ framework can be configured to reload the configuration and rebuild the application context before executing the next test. - See context management and caching with the TestContext - framework. + See and with the TestContext + framework.
        @@ -511,10 +511,9 @@ public class CustomLoaderXmlApplicationContextTests { declared by superclasses by default. - See Context - management and caching and the Javadoc for - @ContextConfiguration for further - details. + See and the + Javadoc for @ContextConfiguration for + further details. @@ -563,6 +562,50 @@ public class WebAppTests { further details. + + + @ContextHierarchy + + A class-level annotation that is used to define a hierarchy of + ApplicationContexts for integration + tests. @ContextHierarchy should be + declared with a list of one or more + @ContextConfiguration instances, each + of which defines a level in the context hierarchy. The following + examples demonstrate the use of + @ContextHierarchy within a single + test class; however, + @ContextHierarchy can also be used + within a test class hierarchy. + + @ContextHierarchy({ + @ContextConfiguration("/parent-config.xml"), + @ContextConfiguration("/child-config.xml") +}) +public class ContextHierarchyTests { + // class body... +} + + @WebAppConfiguration +@ContextHierarchy({ + @ContextConfiguration(classes = AppConfig.class), + @ContextConfiguration(classes = WebConfig.class) +}) +public class WebIntegrationTests { + // class body... +} + + If you need to merge or override the configuration for a given + level of the context hierarchy within a test class hierarchy, you + must explicitly name that level by supplying the same value to the + name attribute in + @ContextConfiguration at each + corresponding level in the class hierarchy. See and the + Javadoc for @ContextHierarchy for + further examples. + + @ActiveProfiles @@ -590,11 +633,9 @@ public class DeveloperIntegrationTests { profiles declared by superclasses by default. - See Context - configuration with environment profiles and the Javadoc for - @ActiveProfiles for examples and - further details. + See + and the Javadoc for @ActiveProfiles + for examples and further details. @@ -603,66 +644,98 @@ public class DeveloperIntegrationTests { Indicates that the underlying Spring ApplicationContext has been - dirtied (i.e., modified or corrupted in some - manner) during the execution of a test and should be closed, - regardless of whether the test passed. - @DirtiesContext is supported in the - following scenarios: + dirtied during the execution of a test (i.e., + modified or corrupted in some manner — for example, by changing the + state of a singleton bean) and should be closed, regardless of + whether the test passed. When an application context is marked + dirty, it is removed from the testing + framework's cache and closed. As a consequence, the underlying + Spring container will be rebuilt for any subsequent test that + requires a context with the same configuration metadata. + + @DirtiesContext can be used as + both a class-level and method-level annotation within the same test + class. In such scenarios, the + ApplicationContext is marked as + dirty after any such annotated method as well + as after the entire class. If the ClassMode + is set to AFTER_EACH_TEST_METHOD, the context is + marked dirty after each test method in the class. + + The following examples explain when the context would be + dirtied for various configuration scenarios: After the current test class, when declared on a class - with class mode set to AFTER_CLASS, which is - the default class mode. + with class mode set to AFTER_CLASS (i.e., the + default class mode). + + @DirtiesContext +public class ContextDirtyingTests { + // some tests that result in the Spring container being dirtied +} After each test method in the current test class, when declared on a class with class mode set to - AFTER_EACH_TEST_METHOD. + AFTER_EACH_TEST_METHOD.@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) +public class ContextDirtyingTests { + // some tests that result in the Spring container being dirtied +} After the current test, when declared on a method. - - - Use this annotation if a test has modified the context (for - example, by replacing a bean definition). Subsequent tests are - supplied a new context. - - With JUnit 4.5+ or TestNG you can use - @DirtiesContext as both a class-level - and method-level annotation within the same test class. In such - scenarios, the ApplicationContext is - marked as dirty after any such annotated method - as well as after the entire class. If the - ClassMode is set to - AFTER_EACH_TEST_METHOD, the context is marked - dirty after each test method in the class. - - @DirtiesContext -public class ContextDirtyingTests { - // some tests that result in the Spring container being dirtied -} - - @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class ContextDirtyingTests { - // some tests that result in the Spring container being dirtied -} - - @DirtiesContext + @DirtiesContext @Test public void testProcessWhichDirtiesAppCtx() { // some logic that results in the Spring container being dirtied } + + - When an application context is marked - dirty, it is removed from the testing - framework's cache and closed; thus the underlying Spring container - is rebuilt for any subsequent test that requires a context with the - same configuration metadata. + If @DirtiesContext is used in a + test whose context is configured as part of a context hierarchy via + @ContextHierarchy, the + hierarchyMode flag can be used to control how the + context cache is cleared. By default an + exhaustive algorithm will be used that clears + the context cache including not only the current level but also all + other context hierarchies that share an ancestor context common to + the current test; all + ApplicationContexts that reside in a + sub-hierarchy of the common ancestor context will be removed from + the context cache and closed. If the exhaustive + algorithm is overkill for a particular use case, the simpler + current level algorithm can be specified + instead, as seen below. + + @ContextHierarchy({ + @ContextConfiguration("/parent-config.xml"), + @ContextConfiguration("/child-config.xml") +}) +public class BaseTests { + // class body... +} + +public class ExtendedTests extends BaseTests { + + @Test + @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL) + public void test() { + // some logic that results in the child context being dirtied + } +} + + For further details regarding the + EXHAUSTIVE and + CURRENT_LEVEL algorithms see the Javadoc for + DirtiesContext.HierarchyMode. @@ -1918,7 +1991,7 @@ public class WacTests { @Configuration classes). - Default Resource Semantics + Default resource semantics @RunWith(SpringJUnit4ClassRunner.class) @@ -1945,7 +2018,7 @@ public class WacTests { locations are classpath based. - Explicit Resource Semantics + Explicit resource semantics @RunWith(SpringJUnit4ClassRunner.class) @@ -2002,7 +2075,7 @@ public class WacTests { ServletTestExecutionListener. - Injecting Mocks + Injecting mocks @WebAppConfiguration @ContextConfiguration @@ -2135,6 +2208,198 @@ public class WacTests { DirtiesContextTestExecutionListener which is enabled by default.
        + +
        + Context hierarchies + + When writing integration tests that rely on a loaded Spring + ApplicationContext, it is often + sufficient to test against a single context; however, there are times + when it is beneficial or even necessary to test against a hierarchy of + ApplicationContexts. For example, if + you are developing a Spring MVC web application you will typically + have a root WebApplicationContext + loaded via Spring's ContextLoaderListener and a + child WebApplicationContext loaded via + Spring's DispatcherServlet. This results in a + parent-child context hierarchy where shared components and + infrastructure configuration are declared in the root context and + consumed in the child context by web-specific components. Another use + case can be found in Spring Batch applications where you often have a + parent context that provides configuration for shared batch + infrastructure and a child context for the configuration of a specific + batch job. + + As of Spring Framework 3.2.2, it is possible to write + integration tests that use context hierarchies by declaring context + configuration via the @ContextHierarchy + annotation, either on an individual test class or within a test class + hierarchy. If a context hierarchy is declared on multiple classes + within a test class hierarchy it is also possible to merge or override + the context configuration for a specific, named level in the context + hierarchy. When merging configuration for a given level in the + hierarchy the configuration resource type (i.e., XML configuration + files or annotated classes) must be consistent; otherwise, it is + perfectly acceptable to have different levels in a context hierarchy + configured using different resource types. + + The following JUnit-based examples demonstrate common + configuration scenarios for integration tests that require the use of + context hierarchies. + + + Single test class with context hierarchy + + ControllerIntegrationTests represents a + typical integration testing scenario for a Spring MVC web + application by declaring a context hierarchy consisting of two + levels, one for the root WebApplicationContext + (loaded using the TestAppConfig + @Configuration class) and one for the + dispatcher servlet + WebApplicationContext (loaded using + the WebConfig + @Configuration class). The + WebApplicationContext that is + autowired into the test instance is the one for + the child context (i.e., the lowest context in the + hierarchy). + + @RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextHierarchy({ + @ContextConfiguration(classes = TestAppConfig.class), + @ContextConfiguration(classes = WebConfig.class) +}) +public class ControllerIntegrationTests { + + @Autowired + private WebApplicationContext wac; + + // ... +} + + + + Class hierarchy with implicit parent context + + The following test classes define a context hierarchy within a + test class hierarchy. AbstractWebTests + declares the configuration for a root + WebApplicationContext in a + Spring-powered web application. Note, however, that + AbstractWebTests does not declare + @ContextHierarchy; consequently, + subclasses of AbstractWebTests can optionally + participate in a context hierarchy or simply follow the standard + semantics for @ContextConfiguration. + SoapWebServiceTests and + RestWebServiceTests both extend + AbstractWebTests and define a context + hierarchy via @ContextHierarchy. The + result is that three application contexts will be loaded (one for + each declaration of + @ContextConfiguration), and the + application context loaded based on the configuration in + AbstractWebTests will be set as the parent + context for each of the contexts loaded for the concrete + subclasses. + + @RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml") +public abstract class AbstractWebTests {} + +@ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml") +public class SoapWebServiceTests extends AbstractWebTests {} + +@ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml") +public class RestWebServiceTests extends AbstractWebTests {} + + + + Class hierarchy with merged context hierarchy + configuration + + The following classes demonstrate the use of + named hierarchy levels in order to + merge the configuration for specific levels in + a context hierarchy. BaseTests defines two + levels in the hierarchy, parent and + child. ExtendedTests + extends BaseTests and instructs the Spring + TestContext Framework to merge the context configuration for the + child hierarchy level, simply by ensuring that + the names declared via + ContextConfiguration's + name attribute are both + "child". The result is that three application + contexts will be loaded: one for + "/app-config.xml", one for + "/user-config.xml", and one for + {"/user-config.xml", "/order-config.xml"}. As + with the previous example, the application context loaded from + "/app-config.xml" will be set as the parent + context for the contexts loaded from + "/user-config.xml" and + {"/user-config.xml", "/order-config.xml"}. + + @RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy({ + @ContextConfiguration(name = "parent", locations = "/app-config.xml"), + @ContextConfiguration(name = "child", locations = "/user-config.xml") +}) +public class BaseTests {} + +@ContextHierarchy( + @ContextConfiguration(name = "child", locations = "/order-config.xml") +) +public class ExtendedTests extends BaseTests {} + + + + Class hierarchy with overridden context hierarchy + configuration + + In contrast to the previous example, this example demonstrates + how to override the configuration for a given + named level in a context hierarchy by setting + ContextConfiguration's + inheritLocations flag to + false. Consequently, the application context for + ExtendedTests will be loaded only from + "/test-user-config.xml" and will have its parent + set to the context loaded from + "/app-config.xml". + + @RunWith(SpringJUnit4ClassRunner.class) +@ContextHierarchy({ + @ContextConfiguration(name = "parent", locations = "/app-config.xml"), + @ContextConfiguration(name = "child", locations = "/user-config.xml") +}) +public class BaseTests {} + +@ContextHierarchy( + @ContextConfiguration( + name = "child", + locations = "/test-user-config.xml", + inheritLocations = false +)) +public class ExtendedTests extends BaseTests {} + + + + Dirtying a context within a context hierarchy + + If @DirtiesContext is used in a + test whose context is configured as part of a context hierarchy, the + hierarchyMode flag can be used to control how the + context cache is cleared. For further details consult the discussion + of @DirtiesContext in and the Javadoc + for @DirtiesContext. + +
        From 6914aff825bfbf58291fa39a131471f312eafe04 Mon Sep 17 00:00:00 2001 From: Dave Syer Date: Sun, 10 Mar 2013 10:59:51 -0700 Subject: [PATCH 16/28] Add additional test for daylight savings glitch The problem was that clocks go forward *at* 2am, so 2am doesn't exist once a year. Users might be surprised that their cron trigger doesn't go off one night, but that is arguably correct (and what happens now). The test can be modified if we decide to change the trigger behaviour. --- .../scheduling/support/CronTriggerTests.java | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java index a344774963..261ea34bd8 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java @@ -56,7 +56,7 @@ public class CronTriggerTests { @Parameters public static List getParameters() { List list = new ArrayList(); - list.add(new Object[] { new Date(), TimeZone.getDefault() }); + list.add(new Object[] { new Date(), TimeZone.getTimeZone("PST") }); list.add(new Object[] { new Date(), TimeZone.getTimeZone("CET") }); return list; } @@ -694,6 +694,26 @@ public class CronTriggerTests { assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context3)); } + @Test + public void testDaylightSavingMissingHour() throws Exception { + // This trigger has to be somewhere in between 2am and 3am + CronTrigger trigger = new CronTrigger("0 10 2 * * *", timeZone); + calendar.set(Calendar.DAY_OF_MONTH, 31); + calendar.set(Calendar.MONTH, Calendar.MARCH); + calendar.set(Calendar.YEAR, 2013); + calendar.set(Calendar.HOUR_OF_DAY, 1); + calendar.set(Calendar.SECOND, 54); + Date date = calendar.getTime(); + TriggerContext context1 = getTriggerContext(date); + if (timeZone.equals(TimeZone.getTimeZone("CET"))) { + // Clocks go forward an hour so 2am doesn't exist in CET for this date + calendar.add(Calendar.DAY_OF_MONTH, 1); + } + calendar.add(Calendar.HOUR_OF_DAY, 1); + calendar.set(Calendar.MINUTE, 10); + calendar.set(Calendar.SECOND, 0); + assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context1)); + } private void assertMatchesNextSecond(CronTrigger trigger, Calendar calendar) { Date date = calendar.getTime(); From 0fb4b747c2f634ebcbbc2f4e37726234100e8367 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 11 Mar 2013 10:32:15 -0400 Subject: [PATCH 17/28] Fix issue with restoring included attributes Before this change the DispatcherServlet restored modified and also removed added attributes but did not restore removed attributes. Issue: SPR-10360 --- .../org/springframework/web/servlet/DispatcherServlet.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java index 6483616edb..0a2b40ca4c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java @@ -1268,6 +1268,7 @@ public class DispatcherServlet extends FrameworkServlet { * @param request current HTTP request * @param attributesSnapshot the snapshot of the request attributes before the include */ + @SuppressWarnings("unchecked") private void restoreAttributesAfterInclude(HttpServletRequest request, Map attributesSnapshot) { logger.debug("Restoring snapshot of request attributes after include"); @@ -1282,6 +1283,9 @@ public class DispatcherServlet extends FrameworkServlet { } } + // Add attributes that may have been removed + attrsToCheck.addAll((Set) attributesSnapshot.keySet()); + // Iterate over the attributes to check, restoring the original value // or removing the attribute, respectively, if appropriate. for (String attrName : attrsToCheck) { From bf6ee1631c065b26198898f59ba7c54423bd5d02 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Wed, 13 Mar 2013 13:00:57 +0100 Subject: [PATCH 18/28] Fix copy-n-paste errors in NativeWebRequest --- .../web/context/request/NativeWebRequest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java b/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java index 2b0df14d95..8554099076 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.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. @@ -56,13 +56,13 @@ public interface NativeWebRequest extends WebRequest { T getNativeRequest(Class requiredType); /** - * Return the underlying native request object, if available. + * Return the underlying native response object, if available. * @param requiredType the desired type of response object * @return the matching response object, or {@code null} if none * of that type is available - * @see javax.servlet.http.HttpServletRequest - * @see javax.portlet.ActionRequest - * @see javax.portlet.RenderRequest + * @see javax.servlet.http.HttpServletResponse + * @see javax.portlet.ActionResponse + * @see javax.portlet.RenderResponse */ T getNativeResponse(Class requiredType); From 12db8730028519d141f41fb88ae2d618458a6737 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Wed, 13 Mar 2013 14:11:08 +0100 Subject: [PATCH 19/28] Polish Javadoc in RequestAttributes --- .../web/context/request/RequestAttributes.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.java b/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.java index 8286de1beb..71568c0a47 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.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. @@ -135,14 +135,14 @@ public interface RequestAttributes { /** * Return an id for the current underlying session. - * @return the session id as String (never {@code null} + * @return the session id as String (never {@code null}) */ String getSessionId(); /** * Expose the best available mutex for the underlying session: * that is, an object to synchronize on for the underlying session. - * @return the session mutex to use (never {@code null} + * @return the session mutex to use (never {@code null}) */ Object getSessionMutex(); From 801f196de05a2d8424c30a66bede6f9a5bfa713d Mon Sep 17 00:00:00 2001 From: David Harkness Date: Tue, 12 Mar 2013 20:38:03 -0700 Subject: [PATCH 20/28] Compare Kind references before checking log levels Assuming reference comparisons are much quicker than checking likely-nested logger levels, perform the former first. Also, since the reference can match only one of the instances, use "else if" to short-circuit the search. --- .../aspectj/AspectJWeaverMessageHandler.java | 26 ++++++++----------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.java index 4505e6f330..678c87baeb 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJWeaverMessageHandler.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. @@ -51,36 +51,32 @@ public class AspectJWeaverMessageHandler implements IMessageHandler { public boolean handleMessage(IMessage message) throws AbortException { Kind messageKind = message.getKind(); - if (LOGGER.isDebugEnabled() || LOGGER.isTraceEnabled()) { - if (messageKind == IMessage.DEBUG) { + if (messageKind == IMessage.DEBUG) { + if (LOGGER.isDebugEnabled() || LOGGER.isTraceEnabled()) { LOGGER.debug(makeMessageFor(message)); return true; } } - - if (LOGGER.isInfoEnabled()) { - if ((messageKind == IMessage.INFO) || (messageKind == IMessage.WEAVEINFO)) { + else if ((messageKind == IMessage.INFO) || (messageKind == IMessage.WEAVEINFO)) { + if (LOGGER.isInfoEnabled()) { LOGGER.info(makeMessageFor(message)); return true; } } - - if (LOGGER.isWarnEnabled()) { - if (messageKind == IMessage.WARNING) { + else if (messageKind == IMessage.WARNING) { + if (LOGGER.isWarnEnabled()) { LOGGER.warn(makeMessageFor(message)); return true; } } - - if (LOGGER.isErrorEnabled()) { - if (messageKind == IMessage.ERROR) { + else if (messageKind == IMessage.ERROR) { + if (LOGGER.isErrorEnabled()) { LOGGER.error(makeMessageFor(message)); return true; } } - - if (LOGGER.isFatalEnabled()) { - if (messageKind == IMessage.ABORT) { + else if (messageKind == IMessage.ABORT) { + if (LOGGER.isFatalEnabled()) { LOGGER.fatal(makeMessageFor(message)); return true; } From fffeaee647d3f24606ca8f4c0d607b33f1b52729 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 13 Mar 2013 14:27:52 +0100 Subject: [PATCH 21/28] Minor refinements along the way of researching static CGLIB callbacks Specifically, our CallbackFilter doesn't hold an implicit reference to the containing ConfigurationClassEnhancer class anymore. Issue: SPR-10307 --- .../ConfigurationClassEnhancer.java | 76 +++++++++++-------- 1 file changed, 43 insertions(+), 33 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java index 37c74ce2a1..a74deefd07 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.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. @@ -52,25 +52,13 @@ class ConfigurationClassEnhancer { private static final Log logger = LogFactory.getLog(ConfigurationClassEnhancer.class); - private static final Class[] CALLBACK_TYPES = {BeanMethodInterceptor.class, - DisposableBeanMethodInterceptor.class, NoOp.class}; - - private static final CallbackFilter CALLBACK_FILTER = new CallbackFilter() { - public int accept(Method candidateMethod) { - // Set up the callback filter to return the index of the BeanMethodInterceptor when - // handling a @Bean-annotated method; otherwise, return index of the NoOp callback. - if (BeanAnnotationHelper.isBeanAnnotated(candidateMethod)) { - return 0; - } - if (DisposableBeanMethodInterceptor.isDestroyMethod(candidateMethod)) { - return 1; - } - return 2; - } - }; + private static final CallbackFilter CALLBACK_FILTER = new ConfigurationClassCallbackFilter(); private static final Callback DISPOSABLE_BEAN_METHOD_INTERCEPTOR = new DisposableBeanMethodInterceptor(); + private static final Class[] CALLBACK_TYPES = + {BeanMethodInterceptor.class, DisposableBeanMethodInterceptor.class, NoOp.class}; + private final Callback[] callbackInstances; @@ -109,21 +97,6 @@ class ConfigurationClassEnhancer { return enhancedClass; } - /** - * Marker interface to be implemented by all @Configuration CGLIB subclasses. - * Facilitates idempotent behavior for {@link ConfigurationClassEnhancer#enhance(Class)} - * through checking to see if candidate classes are already assignable to it, e.g. - * have already been enhanced. - *

        Also extends {@link DisposableBean}, as all enhanced - * {@code @Configuration} classes must de-register static CGLIB callbacks on - * destruction, which is handled by the (private) {@code DisposableBeanMethodInterceptor}. - *

        Note that this interface is intended for framework-internal use only, however - * must remain public in order to allow access to subclasses generated from other - * packages (i.e. user code). - */ - public interface EnhancedConfiguration extends DisposableBean { - } - /** * Creates a new CGLIB {@link Enhancer} instance. */ @@ -149,6 +122,43 @@ class ConfigurationClassEnhancer { } + + /** + * Marker interface to be implemented by all @Configuration CGLIB subclasses. + * Facilitates idempotent behavior for {@link ConfigurationClassEnhancer#enhance(Class)} + * through checking to see if candidate classes are already assignable to it, e.g. + * have already been enhanced. + *

        Also extends {@link DisposableBean}, as all enhanced + * {@code @Configuration} classes must de-register static CGLIB callbacks on + * destruction, which is handled by the (private) {@code DisposableBeanMethodInterceptor}. + *

        Note that this interface is intended for framework-internal use only, however + * must remain public in order to allow access to subclasses generated from other + * packages (i.e. user code). + */ + public interface EnhancedConfiguration extends DisposableBean { + } + + + /** + * CGLIB CallbackFilter implementation that points to BeanMethodInterceptor and + * DisposableBeanMethodInterceptor. + */ + private static class ConfigurationClassCallbackFilter implements CallbackFilter { + + public int accept(Method candidateMethod) { + // Set up the callback filter to return the index of the BeanMethodInterceptor when + // handling a @Bean-annotated method; otherwise, return index of the NoOp callback. + if (BeanAnnotationHelper.isBeanAnnotated(candidateMethod)) { + return 0; + } + if (DisposableBeanMethodInterceptor.isDestroyMethod(candidateMethod)) { + return 1; + } + return 2; + } + } + + /** * Intercepts calls to {@link FactoryBean#getObject()}, delegating to calling * {@link BeanFactory#getBean(String)} in order to respect caching / scoping. @@ -175,7 +185,7 @@ class ConfigurationClassEnhancer { /** * Intercepts the invocation of any {@link DisposableBean#destroy()} on @Configuration * class instances for the purpose of de-registering CGLIB callbacks. This helps avoid - * garbage collection issues See SPR-7901. + * garbage collection issues. See SPR-7901. * @see EnhancedConfiguration */ private static class DisposableBeanMethodInterceptor implements MethodInterceptor { From 43c1cec79b908b084de8de65d98c42a401443250 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 13 Mar 2013 14:36:09 +0100 Subject: [PATCH 22/28] Added "beforeExistingAdvisors" flag to AbstractAdvisingBeanPostProcessor Just AsyncAnnotationBeanPostProcessor switches "beforeExistingAdvisors" to "true" by default. So effectively, MethodValidation/PersistenceExceptionTranslationPostProcessor apply after existing advisors by default again, fixing the 3.1->3.2 regression. Issue: SPR-10309 --- .../AbstractAdvisingBeanPostProcessor.java | 23 ++++++++++++++++++- .../AsyncAnnotationBeanPostProcessor.java | 10 +++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java b/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java index 5d76f6c8a5..01b0fe856c 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java @@ -39,6 +39,8 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyConfig protected Advisor advisor; + protected boolean beforeExistingAdvisors = false; + private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); /** @@ -50,6 +52,19 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyConfig private final Map eligibleBeans = new ConcurrentHashMap(64); + /** + * Set whether this post-processor's advisor is supposed to apply before + * existing advisors when encountering a pre-advised object. + *

        Default is "false", applying the advisor after existing advisors, i.e. + * as close as possible to the target method. Switch this to "true" in order + * for this post-processor's advisor to wrap existing advisors as well. + *

        Note: Check the concrete post-processor's javadoc whether it possibly + * changes this flag by default, depending on the nature of its advisor. + */ + public void setBeforeExistingAdvisors(boolean beforeExistingAdvisors) { + this.beforeExistingAdvisors = beforeExistingAdvisors; + } + public void setBeanClassLoader(ClassLoader beanClassLoader) { this.beanClassLoader = beanClassLoader; } @@ -74,7 +89,13 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyConfig } if (isEligible(bean, beanName)) { if (bean instanceof Advised) { - ((Advised) bean).addAdvisor(0, this.advisor); + Advised advised = (Advised) bean; + if (this.beforeExistingAdvisors) { + advised.addAdvisor(0, this.advisor); + } + else { + advised.addAdvisor(this.advisor); + } return bean; } else { diff --git a/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessor.java index f4c7d65125..0ac2f757f0 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessor.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. @@ -38,11 +38,15 @@ import org.springframework.util.Assert; * processor will detect both Spring's {@link Async @Async} annotation as well * as the EJB 3.1 {@code javax.ejb.Asynchronous} annotation. * + *

        Note: The underlying async advisor applies before existing advisors by default, + * in order to switch to async execution as early as possible in the invocation chain. + * * @author Mark Fisher * @author Juergen Hoeller * @since 3.0 * @see Async * @see AsyncAnnotationAdvisor + * @see #setBeforeExistingAdvisors */ @SuppressWarnings("serial") public class AsyncAnnotationBeanPostProcessor extends AbstractAdvisingBeanPostProcessor @@ -53,6 +57,10 @@ public class AsyncAnnotationBeanPostProcessor extends AbstractAdvisingBeanPostPr private Executor executor; + public AsyncAnnotationBeanPostProcessor() { + setBeforeExistingAdvisors(true); + } + /** * Set the 'async' annotation type to be detected at either class or method * level. By default, both the {@link Async} annotation and the EJB 3.1 From 1f55b4f2a897144e40dad394e650012afb89d9b8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 13 Mar 2013 16:58:29 +0100 Subject: [PATCH 23/28] Extracted buildRequestAttributes template method from FrameworkServlet Also, RequestBindingInterceptor now obtains HttpServletRequest from locally passed-in request handle and delegates to buildRequestAttributes as well now. Issue: SPR-10342 --- .../web/servlet/FrameworkServlet.java | 143 +++++++++++------- 1 file changed, 89 insertions(+), 54 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java index a3f3c37547..07f2db1648 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java @@ -21,7 +21,6 @@ import java.security.Principal; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.Callable; - import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -52,7 +51,6 @@ import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; import org.springframework.web.context.request.async.WebAsyncManager; import org.springframework.web.context.request.async.WebAsyncUtils; @@ -785,6 +783,18 @@ public abstract class FrameworkServlet extends HttpServletBean { // For subclasses: do nothing by default. } + /** + * Close the WebApplicationContext of this servlet. + * @see org.springframework.context.ConfigurableApplicationContext#close() + */ + @Override + public void destroy() { + getServletContext().log("Destroying Spring FrameworkServlet '" + getServletName() + "'"); + if (this.webApplicationContext instanceof ConfigurableApplicationContext) { + ((ConfigurableApplicationContext) this.webApplicationContext).close(); + } + } + /** * Override the parent class implementation in order to intercept PATCH @@ -873,7 +883,7 @@ public abstract class FrameworkServlet extends HttpServletBean { super.doOptions(request, new HttpServletResponseWrapper(response) { @Override public void setHeader(String name, String value) { - if("Allow".equals(name)) { + if ("Allow".equals(name)) { value = (StringUtils.hasLength(value) ? value + ", " : "") + RequestMethod.PATCH.name(); } super.setHeader(name, value); @@ -915,15 +925,12 @@ public abstract class FrameworkServlet extends HttpServletBean { LocaleContext localeContext = buildLocaleContext(request); RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes(); - ServletRequestAttributes requestAttributes = null; - if (previousAttributes == null || (previousAttributes instanceof ServletRequestAttributes)) { - requestAttributes = new ServletRequestAttributes(request); - } - - initContextHolders(request, localeContext, requestAttributes); + ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); - asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), getRequestBindingInterceptor(request)); + asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor()); + + initContextHolders(request, localeContext, requestAttributes); try { doService(request, response); @@ -950,27 +957,18 @@ public abstract class FrameworkServlet extends HttpServletBean { if (logger.isDebugEnabled()) { if (failureCause != null) { this.logger.debug("Could not complete request", failureCause); - } else { + } + else { if (asyncManager.isConcurrentHandlingStarted()) { - if (logger.isDebugEnabled()) { - logger.debug("Leaving response open for concurrent processing"); - } + logger.debug("Leaving response open for concurrent processing"); } else { this.logger.debug("Successfully completed request"); } } } - if (this.publishEvents) { - // Whether or not we succeeded, publish an event. - long processingTime = System.currentTimeMillis() - startTime; - this.webApplicationContext.publishEvent( - new ServletRequestHandledEvent(this, - request.getRequestURI(), request.getRemoteAddr(), - request.getMethod(), getServletConfig().getServletName(), - WebUtils.getSessionId(request), getUsernameForRequest(request), - processingTime, failureCause)); - } + + publishRequestHandledEvent(request, startTime, failureCause); } } @@ -978,18 +976,43 @@ public abstract class FrameworkServlet extends HttpServletBean { * Build a LocaleContext for the given request, exposing the request's * primary locale as current locale. * @param request current HTTP request - * @return the corresponding LocaleContext + * @return the corresponding LocaleContext, or {@code null} if none to bind + * @see LocaleContextHolder#setLocaleContext */ protected LocaleContext buildLocaleContext(HttpServletRequest request) { return new SimpleLocaleContext(request.getLocale()); } - private void initContextHolders(HttpServletRequest request, - LocaleContext localeContext, RequestAttributes attributes) { + /** + * Build ServletRequestAttributes for the given request (potentially also + * holding a reference to the response), taking pre-bound attributes + * (and their type) into consideration. + * @param request current HTTP request + * @param response current HTTP response + * @param previousAttributes pre-bound RequestAttributes instance, if any + * @return the ServletRequestAttributes to bind, or {@code null} to preserve + * the previously bound instance (or not binding any, if none bound before) + * @see RequestContextHolder#setRequestAttributes + */ + protected ServletRequestAttributes buildRequestAttributes( + HttpServletRequest request, HttpServletResponse response, RequestAttributes previousAttributes) { - LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable); - if (attributes != null) { - RequestContextHolder.setRequestAttributes(attributes, this.threadContextInheritable); + if (previousAttributes == null || previousAttributes instanceof ServletRequestAttributes) { + return new ServletRequestAttributes(request); + } + else { + return null; // preserve the pre-bound RequestAttributes instance + } + } + + private void initContextHolders( + HttpServletRequest request, LocaleContext localeContext, RequestAttributes requestAttributes) { + + if (localeContext != null) { + LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable); + } + if (requestAttributes != null) { + RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable); } if (logger.isTraceEnabled()) { logger.trace("Bound request context to thread: " + request); @@ -1006,17 +1029,17 @@ public abstract class FrameworkServlet extends HttpServletBean { } } - private CallableProcessingInterceptor getRequestBindingInterceptor(final HttpServletRequest request) { - return new CallableProcessingInterceptorAdapter() { - @Override - public void preProcess(NativeWebRequest webRequest, Callable task) { - initContextHolders(request, buildLocaleContext(request), new ServletRequestAttributes(request)); - } - @Override - public void postProcess(NativeWebRequest webRequest, Callable task, Object concurrentResult) { - resetContextHolders(request, null, null); - } - }; + private void publishRequestHandledEvent(HttpServletRequest request, long startTime, Throwable failureCause) { + if (this.publishEvents) { + // Whether or not we succeeded, publish an event. + long processingTime = System.currentTimeMillis() - startTime; + this.webApplicationContext.publishEvent( + new ServletRequestHandledEvent(this, + request.getRequestURI(), request.getRemoteAddr(), + request.getMethod(), getServletConfig().getServletName(), + WebUtils.getSessionId(request), getUsernameForRequest(request), + processingTime, failureCause)); + } } /** @@ -1032,6 +1055,7 @@ public abstract class FrameworkServlet extends HttpServletBean { return (userPrincipal != null ? userPrincipal.getName() : null); } + /** * Subclasses must implement this method to do the work of request handling, * receiving a centralized callback for GET, POST, PUT and DELETE. @@ -1049,19 +1073,6 @@ public abstract class FrameworkServlet extends HttpServletBean { throws Exception; - /** - * Close the WebApplicationContext of this servlet. - * @see org.springframework.context.ConfigurableApplicationContext#close() - */ - @Override - public void destroy() { - getServletContext().log("Destroying Spring FrameworkServlet '" + getServletName() + "'"); - if (this.webApplicationContext instanceof ConfigurableApplicationContext) { - ((ConfigurableApplicationContext) this.webApplicationContext).close(); - } - } - - /** * ApplicationListener endpoint that receives events from this servlet's WebApplicationContext * only, delegating to {@code onApplicationEvent} on the FrameworkServlet instance. @@ -1073,4 +1084,28 @@ public abstract class FrameworkServlet extends HttpServletBean { } } + + /** + * CallableProcessingInterceptor implementation that initializes and resets + * FrameworkServlet's context holders, i.e. LocaleContextHolder and RequestContextHolder. + */ + private class RequestBindingInterceptor extends CallableProcessingInterceptorAdapter { + + @Override + public void preProcess(NativeWebRequest webRequest, Callable task) { + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); + if (request != null) { + HttpServletResponse response = webRequest.getNativeRequest(HttpServletResponse.class); + initContextHolders(request, buildLocaleContext(request), buildRequestAttributes(request, response, null)); + } + } + @Override + public void postProcess(NativeWebRequest webRequest, Callable task, Object concurrentResult) { + HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); + if (request != null) { + resetContextHolders(request, null, null); + } + } + } + } From c75eba79b3818b2fb72d859b392bf3263c6b6bf5 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 13 Mar 2013 16:58:51 +0100 Subject: [PATCH 24/28] Polishing --- .../org/springframework/web/servlet/DispatcherServlet.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java index 0a2b40ca4c..fbe27e3a46 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.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 java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; - import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -36,6 +35,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -810,13 +810,13 @@ public class DispatcherServlet extends FrameworkServlet { return context.getAutowireCapableBeanFactory().createBean(clazz); } + /** * Exposes the DispatcherServlet-specific request attributes and delegates to {@link #doDispatch} * for the actual dispatching. */ @Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception { - if (logger.isDebugEnabled()) { String requestUri = urlPathHelper.getRequestUri(request); String resumed = WebAsyncUtils.getAsyncManager(request).hasConcurrentResult() ? " resumed" : ""; From d9540ff34233bb36794da5490a21c7eaa632f1dd Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Wed, 13 Mar 2013 12:26:09 -0400 Subject: [PATCH 25/28] Remove Tiles 3 configuration method Issue: SPR-10361 --- .../web/servlet/view/tiles3/TilesConfigurer.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java b/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java index d23ac0033b..5b43420b19 100644 --- a/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java +++ b/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java @@ -373,12 +373,6 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D private class SpringCompleteAutoloadTilesContainerFactory extends CompleteAutoloadTilesContainerFactory { - @Override - protected AttributeEvaluatorFactory createAttributeEvaluatorFactory( - ApplicationContext applicationContext, LocaleResolver resolver) { - return new BasicAttributeEvaluatorFactory(new DirectAttributeEvaluator()); - } - @Override public TilesContainer createContainer(ApplicationContext applicationContext) { CachingTilesContainer cachingContainer = (CachingTilesContainer) super.createContainer(applicationContext); From 457ee07352a229b4375bcc84cea5771adb2da802 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 13 Mar 2013 17:37:30 +0100 Subject: [PATCH 26/28] Final preparations for 3.2.2 --- src/dist/changelog.txt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 3d29e95e6e..2e605b0d96 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -3,19 +3,23 @@ SPRING FRAMEWORK CHANGELOG http://www.springsource.org -Changes in version 3.2.2 (2013-03-11) +Changes in version 3.2.2 (2013-03-14) -------------------------------------- * official support for Hibernate 4.2 (SPR-10255) * fixed missing inter-dependencies in module POMs (SPR-10218) * marked spring-web module as 'distributable' in order for session replication to work on Tomcat (SPR-10219) * DefaultListableBeanFactory caches target type per bean definition and allows for specifying it in advance (SPR-10335) +* DefaultListableBeanFactory clears by-type matching cache on runtime register/destroySingleton calls (SPR-10326) * ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM (SPR-10249) * ConfigurationClassPostProcessor detects covariant return type mismatch, avoiding infinite recursion (SPR-10261) * ConfigurationClassPostProcessor allows for overriding of scoped-proxy bean definitions (SPR-10265) * "depends-on" attribute on lang namespace element actually respected at runtime now (SPR-8625) -* allow for ordering of mixed AspectJ before/after advices (SPR-9438) +* added locale-independent "commonMessages" property to AbstractMessageSource (SPR-10291) * added "maximumAutoGrowSize" property to SpelParserConfiguration (SPR-10229) +* allow for ordering of mixed AspectJ before/after advices (SPR-9438) +* added "beforeExistingAdvisors" flag to AbstractAdvisingBeanPostProcessor (SPR-10309) +* MethodValidation/PersistenceExceptionTranslationPostProcessor apply after existing advisors by default (SPR-10309) * fixed regression in SpringValidatorAdapter's retrieval of invalid values (SPR-10243) * support 'unless' expression for cache veto (SPR-8871) * @Async's qualifier works for target class annotations behind a JDK proxy as well (SPR-10274) @@ -37,10 +41,13 @@ Changes in version 3.2.2 (2013-03-11) * added "entityResolver", "classDescriptorResolver", "doctypes" and further properties to CastorMarshaller (SPR-8470) * deprecated CastorMarshaller's "object" property in favor of "rootObject" (SPR-8470) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) +* DispatcherServlet allows for customizing its RequestAttributes exposure in subclasses (SPR-10342) * AbstractCachingViewResolver does not use global lock for accessing existing View instances anymore (SPR-3145) * MappingJackson(2)JsonView allows subclasses to access the ObjectMapper and to override content writing (SPR-7619) +* Tiles 3 TilesConfigurer preserves standard EL support for "completeAutoload" mode as well (SPR-10361) * Log4jWebConfigurer supports resolving placeholders against ServletContext init-parameters as well (SPR-10284) * consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks (SPR-10224) +* several MockMvcBuilder refinements (SPR-10277, SPR-10279, SPR-10280) * introduced support for context hierarchies in the TestContext framework (SPR-5613) * introduced support for WebApplicationContext hierarchies in the TestContext framework (SPR-9863) From 5730b8d316e796c0b4a20c7ae51ced84905ff157 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 12 Mar 2013 22:11:23 -0700 Subject: [PATCH 27/28] Document @Bean 'lite' mode vs @Configuration Rework the reference documentation to better distinguish the differences between @Bean methods used in @Comonent vs @Configuration classes. The 'Using the @Bean annotation' section now only covers concepts applicable when using @Bean methods in @Configuration _or_ @Component classes. Information only applicable to @Configuration classes has been moved to a new 'Using the @Configuration annotation' section. An additional sidebar section attempts to explain the differences between the two approaches. Issue: SPR-9425 --- src/reference/docbook/beans-java.xml | 807 ++++++++++++++------------- 1 file changed, 425 insertions(+), 382 deletions(-) diff --git a/src/reference/docbook/beans-java.xml b/src/reference/docbook/beans-java.xml index 8db15fb834..2a76971104 100644 --- a/src/reference/docbook/beans-java.xml +++ b/src/reference/docbook/beans-java.xml @@ -10,21 +10,46 @@ Java-based container configuration

        - Basic concepts: <literal>@Configuration</literal> and - <literal>@Bean</literal> + Basic concepts: <literal>@Bean</literal> and <literal>@Configuration</literal> - The central artifact in Spring's new Java-configuration support is the - @Configuration-annotated class. These - classes consist principally of - @Bean-annotated methods that define - instantiation, configuration, and initialization logic for objects to be - managed by the Spring IoC container. + + Full @Configuration vs 'lite' @Beans mode? + When @Bean methods are declared within + classes that are not annotated with + @Configuration they are referred to as being + processed in a 'lite' mode. For example, bean methods declared in a + @Component or even in a plain old + class will be considered 'lite'. + Unlike full @Configuration, lite + @Bean methods cannot easily declare inter-bean + dependencies. Usually one @Bean method should not + invoke another @Bean method when operating in + 'lite' mode. + Only using @Bean methods within + @Configuration classes is a recommended approach + of ensuring that 'full' mode is always used. This will prevent the same + @Bean method from accidentally being invoked + multiple times and helps to reduce subtle bugs that can be hard to track down + when operating in 'lite' mode. + - Annotating a class with the - @Configuration indicates that the class can - be used by the Spring IoC container as a source of bean definitions. The - simplest possible @Configuration class - would read as follows: + The central artifacts in Spring's new Java-configuration support are + @Configuration-annotated classes and + @Bean-annotated methods. + The @Bean annotation is used to indicate that a + method instantiates, configures and initializes a new object to be managed by + the Spring IoC container. For those familiar with Spring's + <beans/> XML configuration the @Bean + annotation plays the same role as the <bean/> + element. You can use @Bean annotated methods with + any Spring @Component, however, they are most + often used with @Configuration beans. + Annotating a class with @Configuration + indicates that its primary purpose is as a source of bean definitions. Furthermore, + @Configuration classes allow inter-bean + dependencies to be defined by simply calling other @Bean + methods in the same class. The simplest possible + @Configuration class would read as follows: @Configuration public class AppConfig { @Bean @@ -33,16 +58,15 @@ public class AppConfig { } } - For those more familiar with Spring <beans/> - XML, the AppConfig class above would be equivalent to: + The AppConfig class above would be equivalent to the + following Spring <beans/> XML: <beans> <bean id="myService" class="com.acme.services.MyServiceImpl"/> </beans> - As you can see, the @Bean annotation plays the same - role as the <bean/> element. The - @Bean annotation will be discussed in depth in the - sections below. First, however, we'll cover the various ways of creating a - spring container using Java-based configuration. + The @Bean and @Configuration + annotations will be discussed in depth in the sections below. First, however, we'll + cover the various ways of creating a spring container using Java-based + configuration.
        @@ -218,6 +242,387 @@ public class AppConfig {
        +
        + Using the <interfacename>@Bean</interfacename> annotation + + @Bean is a method-level annotation and + a direct analog of the XML <bean/> element. The + annotation supports some of the attributes offered by + <bean/>, such as: init-method, destroy-method, autowiring and + name. + + You can use the @Bean annotation in a + @Configuration-annotated or in a + @Component-annotated class. + +
        + Declaring a bean + + To declare a bean, simply annotate a method with the + @Bean annotation. You use this method to + register a bean definition within an ApplicationContext of + the type specified as the method's return value. By default, the bean + name will be the same as the method name. The following is a simple + example of a @Bean method declaration: + @Configuration +public class AppConfig { + + @Bean + public TransferService transferService() { + return new TransferServiceImpl(); + } + +} + + The preceding configuration is exactly equivalent to the following + Spring XML: + <beans> + <bean id="transferService" class="com.acme.TransferServiceImpl"/> +</beans> + + Both declarations make a bean named transferService + available in the ApplicationContext, bound to an object + instance of type TransferServiceImpl: + +transferService -> com.acme.TransferServiceImpl + +
        + +
        + Receiving lifecycle callbacks + + Any classes defined with the + @Bean annotation support + the regular lifecycle callbacks and can use the + @PostConstruct and @PreDestroy + annotations from JSR-250, see JSR-250 + annotations for further details. + + The regular Spring lifecycle callbacks are fully supported as well. If a bean + implements InitializingBean, DisposableBean, + or Lifecycle, their respective methods are called by the + container. + + The standard set of *Aware interfaces such as + BeanFactoryAware, + BeanNameAware, + MessageSourceAware, ApplicationContextAware, and + so on are also fully supported. + + The @Bean annotation supports + specifying arbitrary initialization and destruction callback methods, + much like Spring XML's init-method and + destroy-method attributes on the bean element: + public class Foo { + public void init() { + // initialization logic + } +} + +public class Bar { + public void cleanup() { + // destruction logic + } +} + +@Configuration +public class AppConfig { + @Bean(initMethod = "init") + public Foo foo() { + return new Foo(); + } + @Bean(destroyMethod = "cleanup") + public Bar bar() { + return new Bar(); + } +} + + + Of course, in the case of Foo above, it would be + equally as valid to call the init() method directly during + construction: + @Configuration +public class AppConfig { + @Bean + public Foo foo() { + Foo foo = new Foo(); + foo.init(); + return foo; + } + + // ... +} + + + When you work directly in Java, you can do anything you like with + your objects and do not always need to rely on the container + lifecycle! + +
        + +
        + Specifying bean scope + +
        + Using the <interfacename>@Scope</interfacename> + annotation + + + + You can specify that your beans defined with the + @Bean annotation should have a specific + scope. You can use any of the standard scopes specified in the Bean Scopes section. + + The default scope is singleton, but you can + override this with the @Scope + annotation: + @Configuration +public class MyConfiguration { + @Bean + @Scope("prototype") + public Encryptor encryptor() { + // ... + } +} +
        + +
        + <code>@Scope and scoped-proxy</code> + + Spring offers a convenient way of working with scoped dependencies + through scoped + proxies. The easiest way to create such a proxy when using the + XML configuration is the <aop:scoped-proxy/> + element. Configuring your beans in Java with a @Scope annotation + offers equivalent support with the proxyMode attribute. The default is + no proxy (ScopedProxyMode.NO), but you can specify + ScopedProxyMode.TARGET_CLASS or + ScopedProxyMode.INTERFACES. + + If you port the scoped proxy example from the XML reference + documentation (see preceding link) to our + @Bean using Java, it would look like + the following: + // an HTTP Session-scoped bean exposed as a proxy +@Bean +@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) +public UserPreferences userPreferences() { + return new UserPreferences(); +} + +@Bean +public Service userService() { + UserService service = new SimpleUserService(); + // a reference to the proxied userPreferences bean + service.setUserPreferences(userPreferences()); + return service; +} +
        +
        + +
        + Customizing bean naming + + By default, configuration classes use a + @Bean method's name as the name of the + resulting bean. This functionality can be overridden, however, with the + name attribute. + @Configuration +public class AppConfig { + + @Bean(name = "myFoo") + public Foo foo() { + return new Foo(); + } + +} +
        + +
        + Bean aliasing + + As discussed in , it is sometimes + desirable to give a single bean multiple names, otherwise known as + bean aliasing. The name + attribute of the @Bean annotation accepts a String + array for this purpose. + @Configuration +public class AppConfig { + + @Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" }) + public DataSource dataSource() { + // instantiate, configure and return DataSource bean... + } + +} +
        +
        + +
        + Using the <interfacename>@Configuration</interfacename> annotation + @Configuration is a class-level annotation + indicating that an object is a source of bean definitions. + @Configuration classes declare beans via + public @Bean annotated methods. Calls to + @Bean methods on + @Configuration classes can also be used to + define inter-bean dependencies. See for + a general introduction. + +
        + Injecting inter-bean dependencies + + When @Beans have dependencies on one + another, expressing that dependency is as simple as having one bean + method call another: + @Configuration +public class AppConfig { + + @Bean + public Foo foo() { + return new Foo(bar()); + } + + @Bean + public Bar bar() { + return new Bar(); + } + +} + + In the example above, the foo bean receives a reference + to bar via constructor injection. + + + This method of declaring inter-bean dependencies only works when + the @Bean method is declared within a + @Configuration class. You cannot declare + inter-bean dependencies using plain @Component + classes. + +
        + +
        + Lookup method injection + + As noted earlier, lookup method injection is an advanced feature that you should + use rarely. It is useful in cases where a singleton-scoped bean has a + dependency on a prototype-scoped bean. Using Java for this type of + configuration provides a natural means for implementing this pattern. + public abstract class CommandManager { + public Object process(Object commandState) { + // grab a new instance of the appropriate Command interface + Command command = createCommand(); + + // set the state on the (hopefully brand new) Command instance + command.setState(commandState); + return command.execute(); + } + + // okay... but where is the implementation of this method? + protected abstract Command createCommand(); +} + + Using Java-configuration support , you can create a subclass of + CommandManager where the abstract + createCommand() method is overridden in such a way that + it looks up a new (prototype) command object: + @Bean +@Scope("prototype") +public AsyncCommand asyncCommand() { + AsyncCommand command = new AsyncCommand(); + // inject dependencies here as required + return command; +} + +@Bean +public CommandManager commandManager() { + // return new anonymous implementation of CommandManager with command() overridden + // to return a new prototype Command object + return new CommandManager() { + protected Command createCommand() { + return asyncCommand(); + } + } +} +
        + +
        + Further information about how Java-based configuration works + internally + + The following example shows a @Bean annotated + method being called twice: + + +@Configuration +public class AppConfig { + + @Bean + public ClientService clientService1() { + ClientServiceImpl clientService = new ClientServiceImpl(); + clientService.setClientDao(clientDao()); + return clientService; + } + @Bean + public ClientService clientService2() { + ClientServiceImpl clientService = new ClientServiceImpl(); + clientService.setClientDao(clientDao()); + return clientService; + } + + @Bean + public ClientDao clientDao() { + return new ClientDaoImpl(); + } +} + + clientDao() has been called once in + clientService1() and once in + clientService2(). Since this method creates a new + instance of ClientDaoImpl and returns it, you would + normally expect having 2 instances (one for each service). That definitely + would be problematic: in Spring, instantiated beans have a + singleton scope by default. This is where the magic + comes in: All @Configuration classes are subclassed at + startup-time with CGLIB. In the subclass, the child + method checks the container first for any cached (scoped) beans before it + calls the parent method and creates a new instance. Note that as of Spring + 3.2, it is no longer necessary to add CGLIB to your classpath because + CGLIB classes have been repackaged under org.springframework and included + directly within the spring-core JAR. + + The behavior could be different according to the scope of your + bean. We are talking about singletons here. + + + There are a few restrictions due to the fact that CGLIB dynamically + adds features at startup-time: + + Configuration classes should not be final + + + They should have a constructor with no arguments + + + +
        +
        + + + +
        Composing Java-based configurations @@ -547,366 +952,4 @@ jdbc.password=
        - -
        - Using the <interfacename>@Bean</interfacename> annotation - - @Bean is a method-level annotation and - a direct analog of the XML <bean/> element. The - annotation supports some of the attributes offered by - <bean/>, such as: init-method, destroy-method, autowiring and - name. - - You can use the @Bean annotation in a - @Configuration-annotated or in a - @Component-annotated class. - -
        - Declaring a bean - - To declare a bean, simply annotate a method with the - @Bean annotation. You use this method to - register a bean definition within an ApplicationContext of - the type specified as the method's return value. By default, the bean - name will be the same as the method name. The following is a simple - example of a @Bean method declaration: - @Configuration -public class AppConfig { - - @Bean - public TransferService transferService() { - return new TransferServiceImpl(); - } - -} - - The preceding configuration is exactly equivalent to the following - Spring XML: - <beans> - <bean id="transferService" class="com.acme.TransferServiceImpl"/> -</beans> - - Both declarations make a bean named transferService - available in the ApplicationContext, bound to an object - instance of type TransferServiceImpl: - -transferService -> com.acme.TransferServiceImpl - -
        - -
        - Injecting dependencies - - When @Beans have dependencies on one - another, expressing that dependency is as simple as having one bean - method call another: - @Configuration -public class AppConfig { - - @Bean - public Foo foo() { - return new Foo(bar()); - } - - @Bean - public Bar bar() { - return new Bar(); - } - -} - - In the example above, the foo bean receives a reference - to bar via constructor injection. -
        - -
        - Receiving lifecycle callbacks - - Beans declared in a - @Configuration-annotated class support - the regular lifecycle callbacks. Any classes defined with the - @Bean annotation can use the - @PostConstruct and @PreDestroy - annotations from JSR-250, see JSR-250 - annotations for further details. - - The regular Spring lifecycle callbacks are fully supported as well. If a bean - implements InitializingBean, DisposableBean, - or Lifecycle, their respective methods are called by the - container. - - The standard set of *Aware interfaces such as - BeanFactoryAware, - BeanNameAware, - MessageSourceAware, ApplicationContextAware, and - so on are also fully supported. - - The @Bean annotation supports - specifying arbitrary initialization and destruction callback methods, - much like Spring XML's init-method and - destroy-method attributes on the bean element: - public class Foo { - public void init() { - // initialization logic - } -} - -public class Bar { - public void cleanup() { - // destruction logic - } -} - -@Configuration -public class AppConfig { - @Bean(initMethod = "init") - public Foo foo() { - return new Foo(); - } - @Bean(destroyMethod = "cleanup") - public Bar bar() { - return new Bar(); - } -} - - - Of course, in the case of Foo above, it would be - equally as valid to call the init() method directly during - construction: - @Configuration -public class AppConfig { - @Bean - public Foo foo() { - Foo foo = new Foo(); - foo.init(); - return foo; - } - - // ... -} - - - When you work directly in Java, you can do anything you like with - your objects and do not always need to rely on the container - lifecycle! - -
        - -
        - Specifying bean scope - -
        - Using the <interfacename>@Scope</interfacename> - annotation - - - - You can specify that your beans defined with the - @Bean annotation should have a specific - scope. You can use any of the standard scopes specified in the Bean Scopes section. - - The default scope is singleton, but you can - override this with the @Scope - annotation: - @Configuration -public class MyConfiguration { - @Bean - @Scope("prototype") - public Encryptor encryptor() { - // ... - } -} -
        - -
        - <code>@Scope and scoped-proxy</code> - - Spring offers a convenient way of working with scoped dependencies - through scoped - proxies. The easiest way to create such a proxy when using the - XML configuration is the <aop:scoped-proxy/> - element. Configuring your beans in Java with a @Scope annotation - offers equivalent support with the proxyMode attribute. The default is - no proxy (ScopedProxyMode.NO), but you can specify - ScopedProxyMode.TARGET_CLASS or - ScopedProxyMode.INTERFACES. - - If you port the scoped proxy example from the XML reference - documentation (see preceding link) to our - @Bean using Java, it would look like - the following: - // an HTTP Session-scoped bean exposed as a proxy -@Bean -@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) -public UserPreferences userPreferences() { - return new UserPreferences(); -} - -@Bean -public Service userService() { - UserService service = new SimpleUserService(); - // a reference to the proxied userPreferences bean - service.setUserPreferences(userPreferences()); - return service; -} -
        - -
        - Lookup method injection - - As noted earlier, lookup method injection is an advanced feature that you should - use rarely. It is useful in cases where a singleton-scoped bean has a - dependency on a prototype-scoped bean. Using Java for this type of - configuration provides a natural means for implementing this pattern. - public abstract class CommandManager { - public Object process(Object commandState) { - // grab a new instance of the appropriate Command interface - Command command = createCommand(); - - // set the state on the (hopefully brand new) Command instance - command.setState(commandState); - return command.execute(); - } - - // okay... but where is the implementation of this method? - protected abstract Command createCommand(); -} - - Using Java-configuration support , you can create a subclass of - CommandManager where the abstract - createCommand() method is overridden in such a way that - it looks up a new (prototype) command object: - @Bean -@Scope("prototype") -public AsyncCommand asyncCommand() { - AsyncCommand command = new AsyncCommand(); - // inject dependencies here as required - return command; -} - -@Bean -public CommandManager commandManager() { - // return new anonymous implementation of CommandManager with command() overridden - // to return a new prototype Command object - return new CommandManager() { - protected Command createCommand() { - return asyncCommand(); - } - } -} -
        -
        - -
        - Customizing bean naming - - By default, configuration classes use a - @Bean method's name as the name of the - resulting bean. This functionality can be overridden, however, with the - name attribute. - @Configuration -public class AppConfig { - - @Bean(name = "myFoo") - public Foo foo() { - return new Foo(); - } - -} -
        - - - - -
        - Bean aliasing - - As discussed in , it is sometimes - desirable to give a single bean multiple names, otherwise known as - bean aliasing. The name - attribute of the @Bean annotation accepts a String - array for this purpose. - @Configuration -public class AppConfig { - - @Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" }) - public DataSource dataSource() { - // instantiate, configure and return DataSource bean... - } - -} -
        -
        - -
        - Further information about how Java-based configuration works - internally - - The following example shows a @Bean annotated - method being called twice: - - -@Configuration -public class AppConfig { - - @Bean - public ClientService clientService1() { - ClientServiceImpl clientService = new ClientServiceImpl(); - clientService.setClientDao(clientDao()); - return clientService; - } - @Bean - public ClientService clientService2() { - ClientServiceImpl clientService = new ClientServiceImpl(); - clientService.setClientDao(clientDao()); - return clientService; - } - - @Bean - public ClientDao clientDao() { - return new ClientDaoImpl(); - } -} - - clientDao() has been called once in - clientService1() and once in - clientService2(). Since this method creates a new - instance of ClientDaoImpl and returns it, you would - normally expect having 2 instances (one for each service). That definitely - would be problematic: in Spring, instantiated beans have a - singleton scope by default. This is where the magic - comes in: All @Configuration classes are subclassed at - startup-time with CGLIB. In the subclass, the child - method checks the container first for any cached (scoped) beans before it - calls the parent method and creates a new instance. Note that as of Spring - 3.2, it is no longer necessary to add CGLIB to your classpath because - CGLIB classes have been repackaged under org.springframework and included - directly within the spring-core JAR. - - The behavior could be different according to the scope of your - bean. We are talking about singletons here. - - - There are a few restrictions due to the fact that CGLIB dynamically - adds features at startup-time: - - Configuration classes should not be final - - - They should have a constructor with no arguments - - - -
        From f62f697550453ad22b0fad13f250913072541140 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 13 Mar 2013 11:13:01 -0700 Subject: [PATCH 28/28] Hide 'doc' changes from jdiff reports --- gradle/jdiff.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/jdiff.gradle b/gradle/jdiff.gradle index 4806550339..cc07e3f71b 100644 --- a/gradle/jdiff.gradle +++ b/gradle/jdiff.gradle @@ -45,7 +45,7 @@ task jdiff { destdir: outputDir, verbose: "off", stats: "on", - docchanges: "on") { + docchanges: "off") { old(name: "Spring Framework ${oldVersion}") { oldVersionRoot.eachDirMatch( { def candidate = new File(it)