language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java
@@ -40,6 +40,7 @@ import org.springframework.http.MediaType; import org.springframework.http.MockHttpInputMessage; import org.springframework.http.MockHttpOutputMessage; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; @@ -55,7 +56,7 @@ public class FormHttpMessageConverterTests { @Before public void setUp() { - converter = new XmlAwareFormHttpMessageConverter(); + converter = new AllEncompassingFormHttpMessageConverter(); } @Test
true
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
@@ -39,6 +39,7 @@ import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; @@ -413,7 +414,7 @@ private ManagedList<?> getMessageConverters(Element element, Object source, Pars messageConverters.add(createConverterBeanDefinition(ResourceHttpMessageConverter.class, source)); messageConverters.add(createConverterBeanDefinition(SourceHttpMessageConverter.class, source)); - messageConverters.add(createConverterBeanDefinition(XmlAwareFormHttpMessageConverter.class, source)); + messageConverters.add(createConverterBeanDefinition(AllEncompassingFormHttpMessageConverter.class, source)); if (romePresent) { messageConverters.add(createConverterBeanDefinition(AtomFeedHttpMessageConverter.class, source)); messageConverters.add(createConverterBeanDefinition(RssChannelHttpMessageConverter.class, source));
true
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
@@ -46,6 +46,7 @@ import org.springframework.http.converter.feed.RssChannelHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; @@ -531,7 +532,7 @@ protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<? messageConverters.add(stringConverter); messageConverters.add(new ResourceHttpMessageConverter()); messageConverters.add(new SourceHttpMessageConverter<Source>()); - messageConverters.add(new XmlAwareFormHttpMessageConverter()); + messageConverters.add(new AllEncompassingFormHttpMessageConverter()); if (romePresent) { messageConverters.add(new AtomFeedHttpMessageConverter()); messageConverters.add(new RssChannelHttpMessageConverter());
true
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java
@@ -37,6 +37,7 @@ import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.web.accept.ContentNegotiationManager; @@ -104,7 +105,7 @@ public ExceptionHandlerExceptionResolver() { this.messageConverters.add(new ByteArrayHttpMessageConverter()); this.messageConverters.add(stringHttpMessageConverter); this.messageConverters.add(new SourceHttpMessageConverter<Source>()); - this.messageConverters.add(new XmlAwareFormHttpMessageConverter()); + this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); } /**
true
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
@@ -45,6 +45,7 @@ import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.SourceHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.ui.ModelMap; @@ -181,7 +182,7 @@ public RequestMappingHandlerAdapter() { this.messageConverters.add(new ByteArrayHttpMessageConverter()); this.messageConverters.add(stringHttpMessageConverter); this.messageConverters.add(new SourceHttpMessageConverter<Source>()); - this.messageConverters.add(new XmlAwareFormHttpMessageConverter()); + this.messageConverters.add(new AllEncompassingFormHttpMessageConverter()); } /**
true
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java
@@ -41,6 +41,7 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.util.LinkedMultiValueMap; @@ -102,7 +103,7 @@ public static void startServer() throws Exception { @Before public void setUp() { - XmlAwareFormHttpMessageConverter converter = new XmlAwareFormHttpMessageConverter(); + AllEncompassingFormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter(); converter.setPartConverters(Arrays.<HttpMessageConverter<?>>asList( new ResourceHttpMessageConverter(), new MappingJacksonHttpMessageConverter()));
true
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java
@@ -32,6 +32,7 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; @@ -119,7 +120,7 @@ public void resolveArgumentRawTypeFromParameterizedType() throws Exception { this.servletRequest.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE); List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(); - converters.add(new XmlAwareFormHttpMessageConverter()); + converters.add(new AllEncompassingFormHttpMessageConverter()); RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters); @SuppressWarnings("unchecked")
true
Other
spring-projects
spring-framework
85a552daed9766ff9f9c5de05181dd5fa5ec7214.json
Fix package cycle among http message converters This change introduces a new AllEncompassingFormHttpMessageConverter class that adds JSON and XML converters for individual mime parts of a multi-part request. The new converter is used in place of the previously used XmlAwareFormHttpMessageConverter. Issue: SPR-10055
src/dist/changelog.txt
@@ -105,7 +105,7 @@ Changes in version 3.2 RC1 (2012-11-04) * use concurrent cache to improve performance of GenericTypeResolver (SPR-8701) * cache and late resolve annotations on bean properties to improve performance (SPR-9166) * allow PropertyResolver implementations to ignore unresolvable ${placeholders} (SPR-9569) -* FormHttpMessageConverter now adds Jackson JSON converters if available on the classpath (SPR-10055) +* AllEncompassingFormHttpMessageConverter now adds XML/JSON converters for individual mime parts (SPR-10055) Changes in version 3.2 M2 (2012-09-11) --------------------------------------
true
Other
spring-projects
spring-framework
3643d92cb8f8d7ba3bee8d19db300c557e2e85a8.json
Fix issue with creating ServletRequestAttributes Prevously the FrameworkServlet created a new ServletRequestAttributes instance for every request, unless the RequestContextHolder already contained an instance whose type is not ServletRequestAttributes. The main intent was that if RequestContextHolder contains a PortletRequestAttributes, it should be left in place. This change does an "instanceof" check against the request in RequestContextHolder instead of an "equals" check on the type. It still leaves PortletRequestAttributes in place but also allows the previous request to be any sub-class of ServletRequestAttributes. Issue: SPR-10025
build.gradle
@@ -518,7 +518,10 @@ project('spring-webmvc-tiles3') { compile("javax.servlet.jsp:jsp-api:2.1", provided) compile("org.apache.tiles:tiles-request-api:1.0.1", optional) compile("org.apache.tiles:tiles-api:3.0.1", optional) - compile("org.apache.tiles:tiles-core:3.0.1", optional) + compile("org.apache.tiles:tiles-core:3.0.1") { dep -> + optional dep + exclude group: 'org.slf4j', module: 'jcl-over-slf4j' + } compile("org.apache.tiles:tiles-servlet:3.0.1", optional) compile("org.apache.tiles:tiles-jsp:3.0.1", optional) compile("org.apache.tiles:tiles-el:3.0.1", optional) @@ -586,16 +589,6 @@ project('spring-test-mvc') { compile("org.hamcrest:hamcrest-core:1.3", optional) compile("com.jayway.jsonpath:json-path:0.8.1", optional) compile("xmlunit:xmlunit:1.2", optional) - testCompile("org.slf4j:jcl-over-slf4j:${slf4jVersion}") - testCompile("org.slf4j:slf4j-log4j12:${slf4jVersion}") { - exclude group: 'log4j', module: 'log4j' - } - testCompile("log4j:log4j:1.2.15") { - exclude group: 'javax.mail', module: 'mail' - exclude group: 'javax.jms', module: 'jms' - exclude group: 'com.sun.jdmk', module: 'jmxtools' - exclude group: 'com.sun.jmx', module: 'jmxri' - } testCompile "javax.servlet:jstl:1.2" testCompile "org.hibernate:hibernate-validator:4.3.0.Final" testCompile "org.codehaus.jackson:jackson-mapper-asl:1.4.2" @@ -607,7 +600,9 @@ project('spring-test-mvc') { testCompile "org.easymock:easymockclassextension:${easymockVersion}" testCompile "org.apache.tiles:tiles-request-api:1.0.1" testCompile "org.apache.tiles:tiles-api:3.0.1" - testCompile "org.apache.tiles:tiles-core:3.0.1" + testCompile("org.apache.tiles:tiles-core:3.0.1") { + exclude group: 'org.slf4j', module: 'jcl-over-slf4j' + } testCompile "org.apache.tiles:tiles-servlet:3.0.1" } }
true
Other
spring-projects
spring-framework
3643d92cb8f8d7ba3bee8d19db300c557e2e85a8.json
Fix issue with creating ServletRequestAttributes Prevously the FrameworkServlet created a new ServletRequestAttributes instance for every request, unless the RequestContextHolder already contained an instance whose type is not ServletRequestAttributes. The main intent was that if RequestContextHolder contains a PortletRequestAttributes, it should be left in place. This change does an "instanceof" check against the request in RequestContextHolder instead of an "equals" check on the type. It still leaves PortletRequestAttributes in place but also allows the previous request to be any sub-class of ServletRequestAttributes. Issue: SPR-10025
spring-test-mvc/src/test/java/org/springframework/test/web/servlet/Spr10025Tests.java
@@ -0,0 +1,94 @@ +/* + * 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.web.servlet; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import org.junit.Assert; +import org.junit.Before; +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.mock.web.MockHttpServletRequest; +import org.springframework.stereotype.Controller; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Test for SPR-10025. + * + * @author Rossen Stoyanchev + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration +public class Spr10025Tests { + + @Autowired + private WebApplicationContext wac; + + @Autowired + private MockHttpServletRequest servletRequest; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = webAppContextSetup(this.wac).build(); + } + + @Test + public void test() throws Exception { + this.servletRequest.setAttribute("foo1", "bar"); + this.mockMvc.perform(get("/myUrl").requestAttr("foo2", "bar")).andExpect(status().isOk()); + } + + + @Configuration + @EnableWebMvc + static class WebConfig extends WebMvcConfigurerAdapter { + + @Bean + public MyController myController() { + return new MyController(); + } + } + + @Controller + private static class MyController { + + @RequestMapping("/myUrl") + @ResponseBody + public void handle() { + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + Assert.assertNull(attributes.getAttribute("foo1", RequestAttributes.SCOPE_REQUEST)); + Assert.assertNotNull(attributes.getAttribute("foo2", RequestAttributes.SCOPE_REQUEST)); + } + } + +}
true
Other
spring-projects
spring-framework
3643d92cb8f8d7ba3bee8d19db300c557e2e85a8.json
Fix issue with creating ServletRequestAttributes Prevously the FrameworkServlet created a new ServletRequestAttributes instance for every request, unless the RequestContextHolder already contained an instance whose type is not ServletRequestAttributes. The main intent was that if RequestContextHolder contains a PortletRequestAttributes, it should be left in place. This change does an "instanceof" check against the request in RequestContextHolder instead of an "equals" check on the type. It still leaves PortletRequestAttributes in place but also allows the previous request to be any sub-class of ServletRequestAttributes. Issue: SPR-10025
spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java
@@ -904,7 +904,7 @@ protected final void processRequest(HttpServletRequest request, HttpServletRespo RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes requestAttributes = null; - if (previousAttributes == null || previousAttributes.getClass().equals(ServletRequestAttributes.class)) { + if (previousAttributes == null || (previousAttributes instanceof ServletRequestAttributes)) { requestAttributes = new ServletRequestAttributes(request); }
true
Other
spring-projects
spring-framework
9cc4bd892a6bb3aca9fea4b2423369181cebea9a.json
Fix issue with suffix pattern match Spring Framework 3.2 M2 added the ability to map requests using only file extensions registered through the configured through a ContentNeotiationManager, as opposed to allowing any file extension (i.e. ".*"). The MVC namespace the MVC Java config automatically register extensions such as ".json" and ".xml" depending on libraries found on the classpath. That in turn causes issues in cases where additional extensions are in use but not registered (e.g. ".html"). This change ensures that matching with registered file extensions only works only if explicitly enabled through a property on RequestMappingHandlerMapping. Issue: SPR-10061, SPR-8474
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java
@@ -50,21 +50,47 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi private boolean useSuffixPatternMatch = true; + private boolean useRegisteredSuffixPatternMatch = false; + private boolean useTrailingSlashMatch = true; private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager(); - private final List<String> contentNegotiationFileExtensions = new ArrayList<String>(); + private final List<String> fileExtensions = new ArrayList<String>(); /** * Whether to use suffix pattern match (".*") when matching patterns to * requests. If enabled a method mapped to "/users" also matches to "/users.*". * <p>The default value is {@code true}. + * <p>Also see {@link #setUseRegisteredSuffixPatternMatch(boolean)} for + * more fine-grained control over specific suffices to allow. */ public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch) { this.useSuffixPatternMatch = useSuffixPatternMatch; } + /** + * Whether to use suffix pattern match for registered file extensions only + * when matching patterns to requests. + * + * <p>If enabled, a controller method mapped to "/users" also matches to + * "/users.json" assuming ".json" is a file extension registered with the + * provided {@link #setContentNegotiationManager(ContentNegotiationManager) + * contentNegotiationManager}. This can be useful for allowing only specific + * URL extensions to be used as well as in cases where a "." in the URL path + * can lead to ambiguous interpretation of path variable content, (e.g. given + * "/users/{user}" and incoming URLs such as "/users/john.j.joe" and + * "/users/john.j.joe.json"). + * + * <p>If enabled, this flag also enables + * {@link #setUseSuffixPatternMatch(boolean) useSuffixPatternMatch}. The + * default value is {@code false}. + */ + public void setUseRegisteredSuffixPatternMatch(boolean useRegsiteredSuffixPatternMatch) { + this.useRegisteredSuffixPatternMatch = useRegsiteredSuffixPatternMatch; + this.useSuffixPatternMatch = useRegsiteredSuffixPatternMatch ? true : this.useSuffixPatternMatch; + } + /** * Whether to match to URLs irrespective of the presence of a trailing slash. * If enabled a method mapped to "/users" also matches to "/users/". @@ -81,7 +107,6 @@ public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) { public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { Assert.notNull(contentNegotiationManager); this.contentNegotiationManager = contentNegotiationManager; - this.contentNegotiationFileExtensions.addAll(contentNegotiationManager.getAllFileExtensions()); } /** @@ -90,6 +115,14 @@ public void setContentNegotiationManager(ContentNegotiationManager contentNegoti public boolean useSuffixPatternMatch() { return this.useSuffixPatternMatch; } + + /** + * Whether to use registered suffixes for pattern matching. + */ + public boolean useRegisteredSuffixPatternMatch() { + return useRegisteredSuffixPatternMatch; + } + /** * Whether to match to URLs irrespective of the presence of a trailing slash. */ @@ -105,10 +138,18 @@ public ContentNegotiationManager getContentNegotiationManager() { } /** - * Return the known file extensions for content negotiation. + * Return the file extensions to use for suffix pattern matching. */ - public List<String> getContentNegotiationFileExtensions() { - return this.contentNegotiationFileExtensions; + public List<String> getFileExtensions() { + return fileExtensions; + } + + @Override + public void afterPropertiesSet() { + super.afterPropertiesSet(); + if (this.useRegisteredSuffixPatternMatch) { + this.fileExtensions.addAll(contentNegotiationManager.getAllFileExtensions()); + } } /** @@ -187,7 +228,7 @@ protected RequestCondition<?> getCustomMethodCondition(Method method) { private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition<?> customCondition) { return new RequestMappingInfo( new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), - this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.contentNegotiationFileExtensions), + this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions), new RequestMethodsRequestCondition(annotation.method()), new ParamsRequestCondition(annotation.params()), new HeadersRequestCondition(annotation.headers()),
true
Other
spring-projects
spring-framework
9cc4bd892a6bb3aca9fea4b2423369181cebea9a.json
Fix issue with suffix pattern match Spring Framework 3.2 M2 added the ability to map requests using only file extensions registered through the configured through a ContentNeotiationManager, as opposed to allowing any file extension (i.e. ".*"). The MVC namespace the MVC Java config automatically register extensions such as ".json" and ".xml" depending on libraries found on the classpath. That in turn causes issues in cases where additional extensions are in use but not registered (e.g. ".html"). This change ensures that matching with registered file extensions only works only if explicitly enabled through a property on RequestMappingHandlerMapping. Issue: SPR-10061, SPR-8474
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java
@@ -0,0 +1,81 @@ +/* + * 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.web.servlet.mvc.method.annotation; + +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.http.MediaType; +import org.springframework.web.accept.ContentNegotiationManager; +import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; +import org.springframework.web.context.support.StaticWebApplicationContext; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +/** + * Tests for {@link RequestMappingHandlerMapping}. + * + * @author Rossen Stoyanchev + */ +public class RequestMappingHandlerMappingTests { + + private RequestMappingHandlerMapping handlerMapping; + + @Before + public void setup() { + this.handlerMapping = new RequestMappingHandlerMapping(); + this.handlerMapping.setApplicationContext(new StaticWebApplicationContext()); + } + + @Test + public void useRegsiteredSuffixPatternMatch() { + assertTrue(this.handlerMapping.useSuffixPatternMatch()); + assertFalse(this.handlerMapping.useRegisteredSuffixPatternMatch()); + + Map<String, MediaType> fileExtensions = Collections.singletonMap("json", MediaType.APPLICATION_JSON); + PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(fileExtensions); + ContentNegotiationManager manager = new ContentNegotiationManager(strategy); + + this.handlerMapping.setContentNegotiationManager(manager); + this.handlerMapping.setUseRegisteredSuffixPatternMatch(true); + this.handlerMapping.afterPropertiesSet(); + + assertTrue(this.handlerMapping.useSuffixPatternMatch()); + assertTrue(this.handlerMapping.useRegisteredSuffixPatternMatch()); + assertEquals(Arrays.asList("json"), this.handlerMapping.getFileExtensions()); + } + + @Test + public void useSuffixPatternMatch() { + assertTrue(this.handlerMapping.useSuffixPatternMatch()); + + this.handlerMapping.setUseSuffixPatternMatch(false); + assertFalse(this.handlerMapping.useSuffixPatternMatch()); + + this.handlerMapping.setUseRegisteredSuffixPatternMatch(false); + assertFalse("'false' registeredSuffixPatternMatch shouldn't impact suffixPatternMatch", + this.handlerMapping.useSuffixPatternMatch()); + + this.handlerMapping.setUseRegisteredSuffixPatternMatch(true); + assertTrue("'true' registeredSuffixPatternMatch should enable suffixPatternMatch", + this.handlerMapping.useSuffixPatternMatch()); + } + +}
true
Other
spring-projects
spring-framework
fb05c7b33c469d5a7826ff8efe3168329617b6b5.json
Replace SLF4J with ACL TilesConfigurer for Tiles 3 Replace the use of SLF4J LoggerFactory and Logger classes with Apache commons-logging LogFactory and Log. Issue: SPR-10077
spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java
@@ -28,6 +28,8 @@ import javax.servlet.ServletContext; import javax.servlet.jsp.JspFactory; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.tiles.TilesContainer; import org.apache.tiles.TilesException; import org.apache.tiles.access.TilesAccess; @@ -53,8 +55,6 @@ import org.apache.tiles.request.ApplicationResource; import org.apache.tiles.startup.DefaultTilesInitializer; import org.apache.tiles.startup.TilesInitializer; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.PropertyAccessorFactory; @@ -106,7 +106,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D ClassUtils.isPresent("javax.servlet.jsp.JspApplicationContext", TilesConfigurer.class.getClassLoader()) && ClassUtils.isPresent("org.apache.tiles.el.ELAttributeEvaluator", TilesConfigurer.class.getClassLoader()); - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final Log logger = LogFactory.getLog(getClass()); private TilesInitializer tilesInitializer;
false
Other
spring-projects
spring-framework
31dfffde52baaff5c9539c9d11653f3776d10de4.json
Update TODOs with new JIRA issue Issue: SPR-8116, SPR-10074
spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java
@@ -437,7 +437,7 @@ public void testConstructor() throws Exception { @Test @Ignore("passes under Eclipse, but fails under Gradle with https://gist.github.com/1664133") - // TODO SPR-8116 passes under Eclipse, but fails under Gradle with + // TODO [SPR-10074] passes under Eclipse, but fails under Gradle with // https://gist.github.com/1664133 public void testContainerPrivileges() throws Exception { AccessControlContext acc = provider.getAccessControlContext();
true
Other
spring-projects
spring-framework
31dfffde52baaff5c9539c9d11653f3776d10de4.json
Update TODOs with new JIRA issue Issue: SPR-8116, SPR-10074
spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java
@@ -23,8 +23,8 @@ * * @author Ramnivas Laddad */ -// TODO SPR-8116 this test causes gradle to hang. -// when run independently e.g. `./gradlew :spring-orm:test -Dtest.single=OpenJpaEntity...` +// TODO [SPR-10074] this test causes gradle to hang. +// When run independently e.g. `./gradlew :spring-orm:test -Dtest.single=OpenJpaEntity...` // it works fine. When run together with all other tests e.g. `./gradlew :spring-orm:test` // it hangs on the 'testCanSerializeProxies' test method. Note that this test DOES pass in // Eclipse, even when the entire 'spring-orm' module is run. Run gradle with '-i' to
true
Other
spring-projects
spring-framework
31dfffde52baaff5c9539c9d11653f3776d10de4.json
Update TODOs with new JIRA issue Issue: SPR-8116, SPR-10074
spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java
@@ -27,7 +27,7 @@ * * @author Costin Leau */ -// TODO SPR-8116 this test causes gradle to hang. See OJEMFWAJWIT. +// TODO [SPR-10074] this test causes gradle to hang. See OJEMFWAJWIT. @Ignore("this test causes gradle to hang. See OJEMFWAJWIT.") public class TopLinkMultiEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests {
true
Other
spring-projects
spring-framework
31dfffde52baaff5c9539c9d11653f3776d10de4.json
Update TODOs with new JIRA issue Issue: SPR-8116, SPR-10074
spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java
@@ -40,7 +40,7 @@ * @author Juergen Hoeller * @since 2.5 */ -// TODO SPR-8116 - see https://gist.github.com/1150858 +// TODO [SPR-10074] see https://gist.github.com/1150858 @Ignore("see https://gist.github.com/1150858") public class JaxWsSupportTests {
true
Other
spring-projects
spring-framework
a8589bf0359850214400904f6254972f64a8f717.json
Replace dependency to aspectjrt with aspectjweaver Replace the gradle dependency on aspectjrt with aspectjweaver since aspectjrt is a subset of aspectjweaver and the full jar is required by Spring. SPR-8896 fixed the original code issue, this change just relates to the generated maven pom. Issue: SPR-10072
build.gradle
@@ -645,7 +645,7 @@ project('spring-aspects') { compile(project(":spring-orm"), optional) // for JPA exception translation support aspects project(":spring-orm") ajc "org.aspectj:aspectjtools:${aspectjVersion}" - compile "org.aspectj:aspectjrt:${aspectjVersion}" + compile "org.aspectj:aspectjweaver:${aspectjVersion}" testCompile project(":spring-core") // for CodeStyleAspect compile project(":spring-beans") // for 'p' namespace visibility testCompile project(":spring-test")
false
Other
spring-projects
spring-framework
da034eb020d29fdc29856e16a0bd6d4d32cb0bae.json
Replace references to SimpleJdbcTemplate in docs Rework JDBC section of the manual to remove references to the now deprecated SimpleJdbcTemplate class. Issue: SPR-10317
src/reference/docbook/jdbc.xml
@@ -159,19 +159,12 @@ parameters for an SQL statement.</para> </listitem> - <listitem> - <para><emphasis role="bold">SimpleJdbcTemplate</emphasis> combines - the most frequently used operations of JdbcTemplate and - NamedParameterJdbcTemplate.</para> - </listitem> - <listitem> <para><emphasis role="bold">SimpleJdbcInsert and SimpleJdbcCall</emphasis> optimize database metadata to limit the amount of necessary configuration. This approach simplifies coding so that you only need to provide the name of the table or procedure - and provide a map of parameters matching the column names. <!--Revise preceding to clarify: You *must* use this approach w/ SimpleJdbcTemplate, it is *recommended*, or you *can*? -TR: OK. I removed the sentence since it isn;t entirely accurate. The implementation uses a plain JdbcTemplate internally.--> + and provide a map of parameters matching the column names. This only works if the database provides adequate metadata. If the database doesn't provide this metadata, you will have to provide explicit configuration of the parameters.</para> @@ -201,8 +194,7 @@ TR: OK. I removed the sentence since it isn;t entirely accurate. The implementat contains the <classname>JdbcTemplate</classname> class and its various callback interfaces, plus a variety of related classes. A subpackage named <literal>org.springframework.jdbc.core.simple</literal> contains - the <classname>SimpleJdbcTemplate</classname> class and the related - <classname>SimpleJdbcInsert</classname> and + the <classname>SimpleJdbcInsert</classname> and <classname>SimpleJdbcCall</classname> classes. Another subpackage named <literal>org.springframework.jdbc.core.namedparam</literal> contains the <classname>NamedParameterJdbcTemplate</classname> class and the related @@ -434,8 +426,6 @@ private static final class ActorMapper implements RowMapper&lt;Actor&gt; { <para>A common practice when using the <classname>JdbcTemplate</classname> class (and the associated <link - linkend="jdbc-SimpleJdbcTemplate"><classname>SimpleJdbcTemplate</classname></link> - and <link linkend="jdbc-NamedParameterJdbcTemplate"><classname>NamedParameterJdbcTemplate</classname></link> classes) is to configure a <interfacename>DataSource</interfacename> in your Spring configuration file, and then dependency-inject that @@ -693,107 +683,6 @@ public int countOfActors(Actor exampleActor) { of an application.</para> </section> - <section xml:id="jdbc-SimpleJdbcTemplate"> - <title><classname>SimpleJdbcTemplate</classname></title> - - <para>The <classname>SimpleJdbcTemplate</classname> class wraps the - classic <classname>JdbcTemplate</classname> and leverages Java 5 - language features such as varargs and autoboxing.</para> - - <note> - <para>In Spring 3.0, the original <classname>JdbcTemplate</classname> - also supports Java 5-enhanced syntax with generics and varargs. - However, the <classname>SimpleJdbcTemplate</classname> provides a - simpler API that works best when you do not need access to all the - methods that the JdbcTemplate offers. Also, because the - <classname>SimpleJdbcTemplate</classname> was designed for Java 5, it - has more methods that take advantage of varargs due to different - ordering of the parameters.</para> - </note> - - <para>The value-add of the <classname>SimpleJdbcTemplate</classname> - class in the area of syntactic-sugar is best illustrated with a - before-and-after example. The next code snippet shows data access code - that uses the classic <classname>JdbcTemplate</classname>, followed by a - code snippet that does the same job with the - <classname>SimpleJdbcTemplate</classname>.</para> - - <programlisting language="java"><lineannotation>// classic JdbcTemplate-style...</lineannotation> -private JdbcTemplate jdbcTemplate; - -public void setDataSource(DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); -} -<!--How is the code shown below different from the code shown in the next example? It seems like they're the same.--> -public Actor findActor(String specialty, int age) { - - String sql = "select id, first_name, last_name from T_ACTOR" + - " where specialty = ? and age = ?"; - - RowMapper&lt;Actor&gt; mapper = new RowMapper&lt;Actor&gt;() { - public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { - Actor actor = new Actor(); - actor.setId(rs.getLong("id")); - actor.setFirstName(rs.getString("first_name")); - actor.setLastName(rs.getString("last_name")); - return actor; - } - }; - - - <lineannotation>// notice the wrapping up of the arguments in an array</lineannotation> - return (Actor) jdbcTemplate.queryForObject(sql, new Object[] {specialty, age}, mapper); -}</programlisting> - - <para>Here is the same method, with the - <classname>SimpleJdbcTemplate</classname>.<!--The code shown above is the same as the code shown below. What is the difference? -TR: difference is in the way the parameters are passed in on the last line; no need to use an Objcet[].--></para> - - <programlisting language="java"><lineannotation>// SimpleJdbcTemplate-style...</lineannotation> -private SimpleJdbcTemplate simpleJdbcTemplate; - -public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); -} - -public Actor findActor(String specialty, int age) { - - String sql = "select id, first_name, last_name from T_ACTOR" + - " where specialty = ? and age = ?"; - RowMapper&lt;Actor&gt; mapper = new RowMapper&lt;Actor&gt;() { - public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { - Actor actor = new Actor(); - actor.setId(rs.getLong("id")); - actor.setFirstName(rs.getString("first_name")); - actor.setLastName(rs.getString("last_name")); - return actor; - } - }; - - <lineannotation>// notice the use of varargs since the parameter values now come - // after the RowMapper parameter</lineannotation> - return this.simpleJdbcTemplate.queryForObject(sql, mapper, specialty, age); -}</programlisting> - - <para>See <xref linkend="jdbc-JdbcTemplate-idioms" /> for guidelines on - how to use the <classname>SimpleJdbcTemplate</classname> class in the - context of an application.</para> - - <note> - <para>The <classname>SimpleJdbcTemplate</classname> class only offers - a subset of the methods exposed on the - <classname>JdbcTemplate</classname> class. If you need to use a method - from the <classname>JdbcTemplate</classname> that is not defined on - the <classname>SimpleJdbcTemplate</classname>, you can always access - the underlying <classname>JdbcTemplate</classname> by calling the - <methodname>getJdbcOperations()</methodname> method on the - <classname>SimpleJdbcTemplate</classname>, which then allows you to - invoke the method that you want. The only downside is that the methods - on the <interfacename>JdbcOperations</interfacename> interface are not - generic, so you are back to casting and so on.</para> - </note> - </section> - <section xml:id="jdbc-SQLExceptionTranslator"> <title><interfacename>SQLExceptionTranslator</interfacename></title> @@ -1370,9 +1259,7 @@ dataSource.setPassword("");</programlisting> <para>Most JDBC drivers provide improved performance if you batch multiple calls to the same prepared statement. By grouping updates into batches you - limit the number of round trips to the database. This section covers batch - processing using both the <classname>JdbcTemplate</classname> and the - <classname>SimpleJdbcTemplate</classname>.</para> + limit the number of round trips to the database.</para> <section xml:id="jdbc-batch-classic"> <title>Basic batch operations with the JdbcTemplate</title> @@ -1579,11 +1466,11 @@ TR: Revised, please review.-->For this example, the initializing method is the you will see examples of multiple ones later.</para> <programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource).withTableName("t_actor"); } @@ -1618,11 +1505,11 @@ TR: Revised, please review.-->For this example, the initializing method is the <classname>usingGeneratedKeyColumns</classname> method.</para> <para><programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1658,11 +1545,11 @@ TR: Revised, please review.-->For this example, the initializing method is the column names with the <classname>usingColumns</classname> method:</para> <para><programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1697,11 +1584,11 @@ TR: Revised, please review.-->For this example, the initializing method is the to extract the parameter values. Here is an example:</para> <para><programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1721,11 +1608,11 @@ TR: Revised, please review.-->For this example, the initializing method is the can be chained.</para> <para><programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1786,11 +1673,11 @@ END;</programlisting>The <code>in_id</code> parameter contains the procedure.<!--Indicate what the purpose of this example is (what it does) and identify the name of procedure. Also see next query. TR: Revised, please review.--></para> <para><programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcCall procReadActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.procReadActor = new SimpleJdbcCall(dataSource) .withProcedureName("read_actor"); @@ -2004,11 +1891,11 @@ END;</programlisting></para> method.</para> <para><programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcCall funcGetActorName; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.setResultsMapCaseInsensitive(true); this.funcGetActorName = @@ -2062,11 +1949,9 @@ END;</programlisting>To call this procedure you declare the <classname>newInstance</classname> method.</para> <para><programlisting language="java">public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; private SimpleJdbcCall procReadAllActors; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.setResultsMapCaseInsensitive(true); this.procReadAllActors = @@ -2679,7 +2564,7 @@ clobReader.close();]]></programlisting> or you need to generate the SQL string dynamically once you know how many placeholders are required. The named parameter support provided in the <classname>NamedParameterJdbcTemplate</classname> and - <classname>SimpleJdbcTemplate</classname> takes the latter approach. + <classname>JdbcTemplate</classname> takes the latter approach. Pass in the values as a <classname>java.util.List</classname> of primitive objects. This list will be used to insert the required placeholders and pass in the values during the statement
false
Other
spring-projects
spring-framework
009d2a5efd456a37c29fd984be3087f09082c325.json
Remove unnecessary null check in SysEnvPropSource Remove unnecessary null check and dead code from SystemEnvironmentPropertySource. Issue: SPR-10318
spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java
@@ -88,10 +88,6 @@ public boolean containsProperty(String name) { public Object getProperty(String name) { Assert.notNull(name, "property name must not be null"); String actualName = resolvePropertyName(name); - if (actualName == null) { - // at this point we know the property does not exist - return null; - } if (logger.isDebugEnabled() && !name.equals(actualName)) { logger.debug(String.format( "PropertySource [%s] does not contain '%s', but found equivalent '%s'",
false
Other
spring-projects
spring-framework
720714b43456d3216f12fa679546cf29bb4b2c65.json
Add JdbcTestUtils.deleteRowsInTableWhere method Issue: SPR-10302
spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.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,13 +23,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.EncodedResource; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameterValue; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.util.StringUtils; @@ -103,6 +103,39 @@ public static int deleteFromTables(JdbcTemplate jdbcTemplate, String... tableNam return totalRowCount; } + /** + * Delete rows from the given table, using the provided {@code WHERE} clause. + * <p>If the provided {@code WHERE} clause contains text, it will be prefixed + * with {@code " WHERE "} and then appended to the generated {@code DELETE} + * statement. For example, if the provided table name is {@code "person"} and + * the provided where clause is {@code "name = 'Bob' and age > 25"}, the + * resulting SQL statement to execute will be + * {@code "DELETE FROM person WHERE name = 'Bob' and age > 25"}. + * <p>As an alternative to hard-coded values, the {@code "?"} placeholder can + * be used within the {@code WHERE} clause, binding to the given arguments. + * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations + * @param tableName the name of the table to delete rows in + * @param whereClause the {@code WHERE} clause to append to the query + * @param args arguments to bind to the query (leaving it to the PreparedStatement + * to guess the corresponding SQL type); may also contain {@link SqlParameterValue} + * objects which indicate not only the argument value but also the SQL type and + * optionally the scale. + * @return the number of rows deleted from the table + */ + public static int deleteFromTableWhere(JdbcTemplate jdbcTemplate, String tableName, + String whereClause, Object... args) { + String sql = "DELETE FROM " + tableName; + if(StringUtils.hasText(whereClause)) { + sql += " WHERE " + whereClause; + } + int rowCount = (args != null && args.length > 0 ? jdbcTemplate.update(sql, args) + : jdbcTemplate.update(sql)); + if (logger.isInfoEnabled()) { + logger.info("Deleted " + rowCount + " rows from table " + tableName); + } + return rowCount; + } + /** * Drop the specified tables. * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations
true
Other
spring-projects
spring-framework
720714b43456d3216f12fa679546cf29bb4b2c65.json
Add JdbcTestUtils.deleteRowsInTableWhere method Issue: SPR-10302
spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.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,25 +16,38 @@ package org.springframework.test.jdbc; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.equalTo; +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 java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.EncodedResource; +import org.springframework.jdbc.core.JdbcTemplate; /** * Unit tests for {@link JdbcTestUtils}. * * @author Thomas Risberg * @author Sam Brannen + * @author Phillip Webb * @since 2.5.4 */ +@RunWith(MockitoJUnitRunner.class) public class JdbcTestUtilsTests { + @Mock + private JdbcTemplate jdbcTemplate; + @Test public void containsDelimiters() { assertTrue("test with ';' is wrong", !JdbcTestUtils.containsSqlScriptDelimiters("select 1\n select ';'", ';')); @@ -104,4 +117,26 @@ public void readAndSplitScriptContainingComments() throws Exception { assertEquals("statement 4 not split correctly", statement4, statements.get(3)); } + @Test + public void testDeleteNoWhere() throws Exception { + given(jdbcTemplate.update("DELETE FROM person")).willReturn(10); + int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", null); + assertThat(deleted, equalTo(10)); + } + + @Test + public void testDeleteWhere() throws Exception { + given(jdbcTemplate.update("DELETE FROM person WHERE name = 'Bob' and age > 25")).willReturn(10); + int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", "name = 'Bob' and age > 25"); + assertThat(deleted, equalTo(10)); + } + + @Test + public void deleteWhereAndArguments() throws Exception { + given(jdbcTemplate.update("DELETE FROM person WHERE name = ? and age > ?", "Bob", 25)).willReturn(10); + int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", "name = ? and age > ?", "Bob", 25); + assertThat(deleted, equalTo(10)); + } + + }
true
Other
spring-projects
spring-framework
5b7969e726edf9080e999730f53f6d449172279d.json
Fix UriComponents.equals() method Fix HierarchicalUriComponents and OpaqueUriComponents .equals() methods. Issue: SPR-10313
spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java
@@ -39,6 +39,7 @@ * Extension of {@link UriComponents} for hierarchical URIs. * * @author Arjen Poutsma + * @author Phillip Webb * @since 3.1.3 * @see <a href="http://tools.ietf.org/html/rfc3986#section-1.2.3">Hierarchical URIs</a> */ @@ -430,28 +431,15 @@ public boolean equals(Object obj) { return false; } HierarchicalUriComponents other = (HierarchicalUriComponents) obj; - if (ObjectUtils.nullSafeEquals(getScheme(), other.getScheme())) { - return false; - } - if (ObjectUtils.nullSafeEquals(getUserInfo(), other.getUserInfo())) { - return false; - } - if (ObjectUtils.nullSafeEquals(getHost(), other.getHost())) { - return false; - } - if (this.port != other.port) { - return false; - } - if (!this.path.equals(other.path)) { - return false; - } - if (!this.queryParams.equals(other.queryParams)) { - return false; - } - if (ObjectUtils.nullSafeEquals(getFragment(), other.getFragment())) { - return false; - } - return true; + boolean rtn = true; + rtn &= ObjectUtils.nullSafeEquals(getScheme(), other.getScheme()); + rtn &= ObjectUtils.nullSafeEquals(getUserInfo(), other.getUserInfo()); + rtn &= ObjectUtils.nullSafeEquals(getHost(), other.getHost()); + rtn &= getPort() == other.getPort(); + rtn &= this.path.equals(other.path); + rtn &= this.queryParams.equals(other.queryParams); + rtn &= ObjectUtils.nullSafeEquals(getFragment(), other.getFragment()); + return rtn; } @Override
true
Other
spring-projects
spring-framework
5b7969e726edf9080e999730f53f6d449172279d.json
Fix UriComponents.equals() method Fix HierarchicalUriComponents and OpaqueUriComponents .equals() methods. Issue: SPR-10313
spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.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. @@ -30,6 +30,7 @@ * Extension of {@link UriComponents} for opaque URIs. * * @author Arjen Poutsma + * @author Phillip Webb * @since 3.2 * @see <a href="http://tools.ietf.org/html/rfc3986#section-1.2.3">Hierarchical vs Opaque URIs</a> */ @@ -145,18 +146,11 @@ public boolean equals(Object obj) { } OpaqueUriComponents other = (OpaqueUriComponents) obj; - - if (ObjectUtils.nullSafeEquals(getScheme(), other.getScheme())) { - return false; - } - if (ObjectUtils.nullSafeEquals(this.ssp, other.ssp)) { - return false; - } - if (ObjectUtils.nullSafeEquals(getFragment(), other.getFragment())) { - return false; - } - - return true; + boolean rtn = true; + rtn &= ObjectUtils.nullSafeEquals(getScheme(), other.getScheme()); + rtn &= ObjectUtils.nullSafeEquals(this.ssp, other.ssp); + rtn &= ObjectUtils.nullSafeEquals(getFragment(), other.getFragment()); + return rtn; } @Override
true
Other
spring-projects
spring-framework
5b7969e726edf9080e999730f53f6d449172279d.json
Fix UriComponents.equals() method Fix HierarchicalUriComponents and OpaqueUriComponents .equals() methods. Issue: SPR-10313
spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java
@@ -26,9 +26,14 @@ import org.junit.Test; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; import static org.junit.Assert.*; -/** @author Arjen Poutsma */ +/** + * @author Arjen Poutsma + * @author Phillip Webb + */ public class UriComponentsTests { @Test @@ -92,4 +97,26 @@ public void serializable() throws Exception { assertThat(uriComponents.toString(), equalTo(readObject.toString())); } + @Test + public void equalsHierarchicalUriComponents() throws Exception { + UriComponents uriComponents1 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bar={baz}").build(); + UriComponents uriComponents2 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bar={baz}").build(); + UriComponents uriComponents3 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bin={baz}").build(); + assertThat(uriComponents1, instanceOf(HierarchicalUriComponents.class)); + assertThat(uriComponents1, equalTo(uriComponents1)); + assertThat(uriComponents1, equalTo(uriComponents2)); + assertThat(uriComponents1, not(equalTo(uriComponents3))); + } + + @Test + public void equalsOpaqueUriComponents() throws Exception { + UriComponents uriComponents1 = UriComponentsBuilder.fromUriString("http:example.com/foo/bar").build(); + UriComponents uriComponents2 = UriComponentsBuilder.fromUriString("http:example.com/foo/bar").build(); + UriComponents uriComponents3 = UriComponentsBuilder.fromUriString("http:example.com/foo/bin").build(); + assertThat(uriComponents1, instanceOf(OpaqueUriComponents.class)); + assertThat(uriComponents1, equalTo(uriComponents1)); + assertThat(uriComponents1, equalTo(uriComponents2)); + assertThat(uriComponents1, not(equalTo(uriComponents3))); + } + }
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java
@@ -441,10 +441,8 @@ protected String determineEncoding(HttpServletRequest request) { * @return the updated URI string */ public String removeSemicolonContent(String requestUri) { - if (this.removeSemicolonContent) { - return removeSemicolonContentInternal(requestUri); - } - return removeJsessionid(requestUri); + return this.removeSemicolonContent ? + removeSemicolonContentInternal(requestUri) : removeJsessionid(requestUri); } private String removeSemicolonContentInternal(String requestUri) {
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
@@ -154,7 +154,6 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { handlerMappingDef.setSource(source); handlerMappingDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); handlerMappingDef.getPropertyValues().add("order", 0); - handlerMappingDef.getPropertyValues().add("removeSemicolonContent", false); handlerMappingDef.getPropertyValues().add("contentNegotiationManager", contentNegotiationManager); String methodMappingName = parserContext.getReaderContext().registerWithGeneratedName(handlerMappingDef);
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
@@ -192,7 +192,6 @@ public void setApplicationContext(ApplicationContext applicationContext) throws public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping(); handlerMapping.setOrder(0); - handlerMapping.setRemoveSemicolonContent(false); handlerMapping.setInterceptors(getInterceptors()); handlerMapping.setContentNegotiationManager(mvcContentNegotiationManager()); return handlerMapping;
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java
@@ -127,6 +127,7 @@ public void setUrlDecode(boolean urlDecode) { /** * Set if ";" (semicolon) content should be stripped from the request URI. + * <p>The default value is {@code false}. * @see org.springframework.web.util.UrlPathHelper#setRemoveSemicolonContent(boolean) */ public void setRemoveSemicolonContent(boolean removeSemicolonContent) {
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java
@@ -37,6 +37,7 @@ import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.HandlerMethodSelector; import org.springframework.web.servlet.HandlerMapping; +import org.springframework.web.util.UrlPathHelper; /** * Abstract base class for {@link HandlerMapping} implementations that define a @@ -61,6 +62,12 @@ private final MultiValueMap<String, T> urlMap = new LinkedMultiValueMap<String, T>(); + public AbstractHandlerMethodMapping() { + UrlPathHelper pathHelper = new UrlPathHelper(); + pathHelper.setRemoveSemicolonContent(false); + setUrlPathHelper(pathHelper); + } + /** * Whether to detect handler methods in beans in ancestor ApplicationContexts. * <p>Default is "false": Only beans in the current ApplicationContext are
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java
@@ -42,9 +42,16 @@ */ public final class PatternsRequestCondition extends AbstractRequestCondition<PatternsRequestCondition> { + private static UrlPathHelper pathHelperNoSemicolonContent; + + static { + pathHelperNoSemicolonContent = new UrlPathHelper(); + pathHelperNoSemicolonContent.setRemoveSemicolonContent(true); + } + private final Set<String> patterns; - private final UrlPathHelper urlPathHelper; + private final UrlPathHelper pathHelper; private final PathMatcher pathMatcher; @@ -105,7 +112,7 @@ private PatternsRequestCondition(Collection<String> patterns, UrlPathHelper urlP List<String> fileExtensions) { this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns)); - this.urlPathHelper = urlPathHelper != null ? urlPathHelper : new UrlPathHelper(); + this.pathHelper = urlPathHelper != null ? urlPathHelper : new UrlPathHelper(); this.pathMatcher = pathMatcher != null ? pathMatcher : new AntPathMatcher(); this.useSuffixPatternMatch = useSuffixPatternMatch; this.useTrailingSlashMatch = useTrailingSlashMatch; @@ -179,7 +186,7 @@ else if (!other.patterns.isEmpty()) { else { result.add(""); } - return new PatternsRequestCondition(result, this.urlPathHelper, this.pathMatcher, this.useSuffixPatternMatch, + return new PatternsRequestCondition(result, this.pathHelper, this.pathMatcher, this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions); } @@ -206,17 +213,24 @@ public PatternsRequestCondition getMatchingCondition(HttpServletRequest request) if (this.patterns.isEmpty()) { return this; } - String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); + + String lookupPath = this.pathHelper.getLookupPathForRequest(request); + String lookupPathNoSemicolonContent = (lookupPath.indexOf(';') != -1) ? + pathHelperNoSemicolonContent.getLookupPathForRequest(request) : null; + List<String> matches = new ArrayList<String>(); for (String pattern : patterns) { String match = getMatchingPattern(pattern, lookupPath); + if (match == null && lookupPathNoSemicolonContent != null) { + match = getMatchingPattern(pattern, lookupPathNoSemicolonContent); + } if (match != null) { matches.add(match); } } Collections.sort(matches, this.pathMatcher.getPatternComparator(lookupPath)); return matches.isEmpty() ? null : - new PatternsRequestCondition(matches, this.urlPathHelper, this.pathMatcher, this.useSuffixPatternMatch, + new PatternsRequestCondition(matches, this.pathHelper, this.pathMatcher, this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions); } @@ -225,7 +239,7 @@ private String getMatchingPattern(String pattern, String lookupPath) { return pattern; } if (this.useSuffixPatternMatch) { - if (useSmartSuffixPatternMatch(pattern, lookupPath)) { + if (!this.fileExtensions.isEmpty() && lookupPath.indexOf('.') != -1) { for (String extension : this.fileExtensions) { if (this.pathMatcher.match(pattern + extension, lookupPath)) { return pattern + extension; @@ -251,14 +265,6 @@ private String getMatchingPattern(String pattern, String lookupPath) { return null; } - /** - * Whether to match by known file extensions. Return "true" if file extensions - * are configured, and the lookup path has a suffix. - */ - private boolean useSmartSuffixPatternMatch(String pattern, String lookupPath) { - return (!this.fileExtensions.isEmpty() && lookupPath.indexOf('.') != -1) ; - } - /** * Compare the two conditions based on the URL patterns they contain. * Patterns are compared one at a time, from top to bottom via @@ -272,7 +278,7 @@ private boolean useSmartSuffixPatternMatch(String pattern, String lookupPath) { * the best matches on top. */ public int compareTo(PatternsRequestCondition other, HttpServletRequest request) { - String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); + String lookupPath = this.pathHelper.getLookupPathForRequest(request); Comparator<String> patternComparator = this.pathMatcher.getPatternComparator(lookupPath); Iterator<String> iterator = patterns.iterator();
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java
@@ -27,6 +27,7 @@ import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; +import org.springframework.web.util.UrlPathHelper; /** * @author Rossen Stoyanchev @@ -185,6 +186,16 @@ public void matchPatternContainsExtension() { assertNull(match); } + @Test + public void matchIgnorePathParams() { + UrlPathHelper pathHelper = new UrlPathHelper(); + pathHelper.setRemoveSemicolonContent(false); + PatternsRequestCondition condition = new PatternsRequestCondition(new String[] {"/foo/bar"}, pathHelper, null, true, true); + PatternsRequestCondition match = condition.getMatchingCondition(new MockHttpServletRequest("GET", "/foo;q=1/bar;s=1")); + + assertNotNull(match); + } + @Test public void compareEqualPatterns() { PatternsRequestCondition c1 = new PatternsRequestCondition("/foo*");
true
Other
spring-projects
spring-framework
5b1165b1029263ff0020562da95bd30380f303e4.json
Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java
@@ -90,7 +90,6 @@ public void setUp() throws Exception { this.handlerMapping = new TestRequestMappingInfoHandlerMapping(); this.handlerMapping.registerHandler(testController); - this.handlerMapping.setRemoveSemicolonContent(false); } @Test
true
Other
spring-projects
spring-framework
b47d97c23a24a10305c8a82ba4acc823ce52f088.json
Improve error message for JSON path expressions Issue: SPR-SPR-10275
spring-test-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java
@@ -17,7 +17,8 @@ package org.springframework.test.util; import static org.springframework.test.util.AssertionErrors.assertEquals; -import static org.springframework.test.util.AssertionErrors.*; +import static org.springframework.test.util.AssertionErrors.assertTrue; +import static org.springframework.test.util.AssertionErrors.fail; import static org.springframework.test.util.MatcherAssertionErrors.assertThat; import java.text.ParseException; @@ -96,6 +97,10 @@ public void assertValue(String responseContent, Object expectedValue) throws Par } actualValue = actualValueList.get(0); } + else if (actualValue != null && expectedValue != null) { + assertEquals("For JSON path " + this.expression + " type of value", + expectedValue.getClass(), actualValue.getClass()); + } assertEquals("JSON path" + this.expression, expectedValue, actualValue); }
true
Other
spring-projects
spring-framework
b47d97c23a24a10305c8a82ba4acc823ce52f088.json
Improve error message for JSON path expressions Issue: SPR-SPR-10275
spring-test-mvc/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java
@@ -0,0 +1,45 @@ +/* + * Copyright 2004-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.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; + + +/** + * Test fixture for {@link JsonPathExpectationsHelper}. + * + * @author Rossen Stoyanchev + */ +public class JsonPathExpectationsHelperTests { + + + @Test + public void test() throws Exception { + try { + new JsonPathExpectationsHelper("$.nr").assertValue("{ \"nr\" : 5 }", "5"); + fail("Expected exception"); + } + catch (AssertionError ex) { + assertEquals("For JSON path $.nr type of value expected:<class java.lang.String> but was:<class java.lang.Integer>", + ex.getMessage()); + } + } + +}
true
Other
spring-projects
spring-framework
92ad66bf10b570dde25af44d8ff3f958dfec2a9d.json
Add setOutputStreaming option for HTTP factory Add setOutputStreaming on SimpleClientHttpRequestFactory to allow the disabling of 'output streaming' mode on the underlying connection so that authentication and redirection can be handled automatically. Issue: SPR-9617
spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,9 +39,12 @@ final class SimpleBufferingClientHttpRequest extends AbstractBufferingClientHttp private final HttpURLConnection connection; + private final boolean outputStreaming; - SimpleBufferingClientHttpRequest(HttpURLConnection connection) { + + SimpleBufferingClientHttpRequest(HttpURLConnection connection, boolean outputStreaming) { this.connection = connection; + this.outputStreaming = outputStreaming; } @@ -67,7 +70,7 @@ protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] buffere } } - if (this.connection.getDoOutput()) { + if (this.connection.getDoOutput() && this.outputStreaming) { this.connection.setFixedLengthStreamingMode(bufferedOutput.length); } this.connection.connect();
true
Other
spring-projects
spring-framework
92ad66bf10b570dde25af44d8ff3f958dfec2a9d.json
Add setOutputStreaming option for HTTP factory Add setOutputStreaming on SimpleClientHttpRequestFactory to allow the disabling of 'output streaming' mode on the underlying connection so that authentication and redirection can be handled automatically. Issue: SPR-9617
spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.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. @@ -50,6 +50,8 @@ public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory private int readTimeout = -1; + private boolean outputStreaming = true; + /** * Set the {@link Proxy} to use for this request factory. @@ -104,15 +106,31 @@ public void setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; } + /** + * Set if the underlying URLConnection can be set to 'output streaming' mode. When + * output streaming is enabled, authentication and redirection cannot be handled + * automatically. If output streaming is disabled the + * {@link HttpURLConnection#setFixedLengthStreamingMode(int) + * setFixedLengthStreamingMode} and + * {@link HttpURLConnection#setChunkedStreamingMode(int) setChunkedStreamingMode} + * methods of the underlying connection will never be called. + * <p>Default is {@code true}. + * @param outputStreaming if output streaming is enabled + */ + public void setOutputStreaming(boolean outputStreaming) { + this.outputStreaming = outputStreaming; + } + public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { HttpURLConnection connection = openConnection(uri.toURL(), this.proxy); prepareConnection(connection, httpMethod.name()); if (this.bufferRequestBody) { - return new SimpleBufferingClientHttpRequest(connection); + return new SimpleBufferingClientHttpRequest(connection, this.outputStreaming); } else { - return new SimpleStreamingClientHttpRequest(connection, this.chunkSize); + return new SimpleStreamingClientHttpRequest(connection, this.chunkSize, + this.outputStreaming); } }
true
Other
spring-projects
spring-framework
92ad66bf10b570dde25af44d8ff3f958dfec2a9d.json
Add setOutputStreaming option for HTTP factory Add setOutputStreaming on SimpleClientHttpRequestFactory to allow the disabling of 'output streaming' mode on the underlying connection so that authentication and redirection can be handled automatically. Issue: SPR-9617
spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java
@@ -44,10 +44,14 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest { private OutputStream body; + private final boolean outputStreaming; - SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize) { + + SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize, + boolean outputStreaming) { this.connection = connection; this.chunkSize = chunkSize; + this.outputStreaming = outputStreaming; } public HttpMethod getMethod() { @@ -66,12 +70,14 @@ public URI getURI() { @Override protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException { if (this.body == null) { - int contentLength = (int) headers.getContentLength(); - if (contentLength >= 0) { - this.connection.setFixedLengthStreamingMode(contentLength); - } - else { - this.connection.setChunkedStreamingMode(this.chunkSize); + if(this.outputStreaming) { + int contentLength = (int) headers.getContentLength(); + if (contentLength >= 0) { + this.connection.setFixedLengthStreamingMode(contentLength); + } + else { + this.connection.setChunkedStreamingMode(this.chunkSize); + } } writeHeaders(headers); this.connection.connect();
true
Other
spring-projects
spring-framework
92ad66bf10b570dde25af44d8ff3f958dfec2a9d.json
Add setOutputStreaming option for HTTP factory Add setOutputStreaming on SimpleClientHttpRequestFactory to allow the disabling of 'output streaming' mode on the underlying connection so that authentication and redirection can be handled automatically. Issue: SPR-9617
spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java
@@ -0,0 +1,29 @@ +/* + * 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.http.client; + + +public class NoOutputStreamingBufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { + + @Override + protected ClientHttpRequestFactory createRequestFactory() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setOutputStreaming(false); + return factory; + } + +}
true
Other
spring-projects
spring-framework
92ad66bf10b570dde25af44d8ff3f958dfec2a9d.json
Add setOutputStreaming option for HTTP factory Add setOutputStreaming on SimpleClientHttpRequestFactory to allow the disabling of 'output streaming' mode on the underlying connection so that authentication and redirection can be handled automatically. Issue: SPR-9617
spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingStreamingSimpleHttpRequestFactoryTests.java
@@ -0,0 +1,29 @@ +/* + * 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.http.client; + + +public class NoOutputStreamingStreamingSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { + + @Override + protected ClientHttpRequestFactory createRequestFactory() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setBufferRequestBody(false); + factory.setOutputStreaming(false); + return factory; + } +}
true
Other
spring-projects
spring-framework
24ed325c0cc8fb0758a166608b7b6ff834e40fa9.json
Add HttpPutFormContentFilter note to documentation Update reference guide to include a note about the use of HttpPutFormContentFilter in combination with @RequestBody MultiValueMap and HttpEntity. Issue: SPR-8415
src/reference/docbook/mvc.xml
@@ -2157,6 +2157,14 @@ public class EditPetForm { available through the <literal>ServletRequest.getParameter*()</literal> family of methods.</para> + + <note> + <para>As <classname>HttpPutFormContentFilter</classname> consumes the body of the + request, it should not be configured for PUT or PATCH URLs that rely on other + converters for <literal>application/x-www-form-urlencoded</literal>. This includes + <literal>@RequestBody MultiValueMap&lt;String, String&gt;</literal> and + <literal>HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt;</literal>.</para> + </note> </section> <section xml:id="mvc-ann-cookievalue">
false
Other
spring-projects
spring-framework
19eecb151b8a0e2b2dad1aa4baf4c552587342fb.json
Add @Ignored Test case to reproduce SPR-10243 Issue: SPR-10243
spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java
@@ -35,13 +35,15 @@ import javax.validation.constraints.NotNull; import org.hibernate.validator.HibernateValidator; +import org.junit.Ignore; import org.junit.Test; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.*; /** @@ -102,6 +104,22 @@ public void testSimpleValidationWithClassLevel() throws Exception { assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid); } + @Test + @Ignore + public void testSpringValidationFieldType() throws Exception { + LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); + validator.afterPropertiesSet(); + ValidPerson person = new ValidPerson(); + person.setName("Phil"); + person.getAddress().setStreet("Phil's Street"); + BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); + validator.validate(person, errors); + assertEquals(1, errors.getErrorCount()); + assertThat("Field/Value type missmatch", + errors.getFieldError("address").getRejectedValue(), + instanceOf(ValidAddress.class)); + } + @Test public void testSpringValidation() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); @@ -289,8 +307,13 @@ public void initialize(NameAddressValid constraintAnnotation) { } @Override - public boolean isValid(ValidPerson value, ConstraintValidatorContext constraintValidatorContext) { - return (value.name == null || !value.address.street.contains(value.name)); + public boolean isValid(ValidPerson value, ConstraintValidatorContext context) { + boolean valid = (value.name == null || !value.address.street.contains(value.name)); + if (!valid && "Phil".equals(value.name)) { + context.buildConstraintViolationWithTemplate( + context.getDefaultConstraintMessageTemplate()).addNode("address").addConstraintViolation().disableDefaultConstraintViolation(); + } + return valid; } }
false
Other
spring-projects
spring-framework
0b6101478e705f5fff1fa7e1cd2b1159ac60280c.json
Use bridge methods in ReflectiveMethodResolver Fix failing test Issue: SPR-10210
spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java
@@ -24,7 +24,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList;
true
Other
spring-projects
spring-framework
0b6101478e705f5fff1fa7e1cd2b1159ac60280c.json
Use bridge methods in ReflectiveMethodResolver Fix failing test Issue: SPR-10210
spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java
@@ -20,4 +20,8 @@ import org.springframework.expression.spel.spr10210.infra.C; abstract class A extends B<C> { + + public void bridgetMethod() { + } + }
true
Other
spring-projects
spring-framework
634284e1fdd9a32b7356117055bc62b64d6e0add.json
Use bridge methods in ReflectiveMethodResolver Update ReflectiveMethodResolver to consider bridge methods. Issue: SPR-10210
spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.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,13 +19,16 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.springframework.core.BridgeMethodResolver; import org.springframework.core.MethodParameter; import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; @@ -37,7 +40,6 @@ import org.springframework.expression.TypeConverter; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; -import org.springframework.util.CollectionUtils; /** * Reflection-based {@link MethodResolver} used by default in @@ -92,42 +94,38 @@ public MethodExecutor resolve(EvaluationContext context, Object targetObject, St try { TypeConverter typeConverter = context.getTypeConverter(); Class<?> type = (targetObject instanceof Class ? (Class<?>) targetObject : targetObject.getClass()); - Method[] methods = getMethods(type, targetObject); + List<Method> methods = new ArrayList<Method>(Arrays.asList(getMethods(type, targetObject))); // If a filter is registered for this type, call it MethodFilter filter = (this.filters != null ? this.filters.get(type) : null); if (filter != null) { - List<Method> methodsForFiltering = new ArrayList<Method>(); - for (Method method: methods) { - methodsForFiltering.add(method); - } - List<Method> methodsFiltered = filter.filter(methodsForFiltering); - if (CollectionUtils.isEmpty(methodsFiltered)) { - methods = NO_METHODS; - } - else { - methods = methodsFiltered.toArray(new Method[methodsFiltered.size()]); - } + methods = filter.filter(methods); } - Arrays.sort(methods, new Comparator<Method>() { + // Sort methods into a sensible order + Collections.sort(methods, new Comparator<Method>() { public int compare(Method m1, Method m2) { int m1pl = m1.getParameterTypes().length; int m2pl = m2.getParameterTypes().length; return (new Integer(m1pl)).compareTo(m2pl); } }); + // Resolve any bridge methods + for (int i = 0; i < methods.size(); i++) { + methods.set(i, BridgeMethodResolver.findBridgedMethod(methods.get(i))); + } + + // Remove duplicate methods (possible due to resolved bridge methods) + methods = new ArrayList<Method>(new LinkedHashSet<Method>(methods)); + Method closeMatch = null; int closeMatchDistance = Integer.MAX_VALUE; int[] argsToConvert = null; Method matchRequiringConversion = null; boolean multipleOptions = false; for (Method method : methods) { - if (method.isBridge()) { - continue; - } if (method.getName().equals(name)) { Class<?>[] paramTypes = method.getParameterTypes(); List<TypeDescriptor> paramDescriptors = new ArrayList<TypeDescriptor>(paramTypes.length);
true
Other
spring-projects
spring-framework
634284e1fdd9a32b7356117055bc62b64d6e0add.json
Use bridge methods in ReflectiveMethodResolver Update ReflectiveMethodResolver to consider bridge methods. Issue: SPR-10210
spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java
@@ -24,6 +24,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; @@ -1736,6 +1737,14 @@ public void SPR_10125() throws Exception { assertThat(fromClass, is("interfaceValue")); } + @Test + public void SPR_10210() throws Exception { + StandardEvaluationContext context = new StandardEvaluationContext(); + context.setVariable("bridgeExample", new org.springframework.expression.spel.spr10210.D()); + Expression parseExpression = parser.parseExpression("#bridgeExample.bridgetMethod()"); + parseExpression.getValue(context); + } + public static class BooleanHolder { private Boolean simpleProperty = true; @@ -1796,4 +1805,5 @@ public static class StaticFinalImpl1 extends AbstractStaticFinal implements Stat public static class StaticFinalImpl2 extends AbstractStaticFinal { } + }
true
Other
spring-projects
spring-framework
634284e1fdd9a32b7356117055bc62b64d6e0add.json
Use bridge methods in ReflectiveMethodResolver Update ReflectiveMethodResolver to consider bridge methods. Issue: SPR-10210
spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java
@@ -0,0 +1,23 @@ +/* + * 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.expression.spel.spr10210; + +import org.springframework.expression.spel.spr10210.comp.B; +import org.springframework.expression.spel.spr10210.infra.C; + +abstract class A extends B<C> { +}
true
Other
spring-projects
spring-framework
634284e1fdd9a32b7356117055bc62b64d6e0add.json
Use bridge methods in ReflectiveMethodResolver Update ReflectiveMethodResolver to consider bridge methods. Issue: SPR-10210
spring-expression/src/test/java/org/springframework/expression/spel/spr10210/D.java
@@ -0,0 +1,20 @@ +/* + * 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.expression.spel.spr10210; + +public class D extends A { +}
true
Other
spring-projects
spring-framework
634284e1fdd9a32b7356117055bc62b64d6e0add.json
Use bridge methods in ReflectiveMethodResolver Update ReflectiveMethodResolver to consider bridge methods. Issue: SPR-10210
spring-expression/src/test/java/org/springframework/expression/spel/spr10210/comp/B.java
@@ -0,0 +1,24 @@ +/* + * 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.expression.spel.spr10210.comp; + +import java.io.Serializable; + +import org.springframework.expression.spel.spr10210.infra.C; + +public class B<T extends C> implements Serializable { +}
true
Other
spring-projects
spring-framework
634284e1fdd9a32b7356117055bc62b64d6e0add.json
Use bridge methods in ReflectiveMethodResolver Update ReflectiveMethodResolver to consider bridge methods. Issue: SPR-10210
spring-expression/src/test/java/org/springframework/expression/spel/spr10210/infra/C.java
@@ -0,0 +1,20 @@ +/* + * 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.expression.spel.spr10210.infra; + +public interface C { +}
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
build.gradle
@@ -69,7 +69,7 @@ configure(allprojects) { project -> testCompile("junit:junit:${junitVersion}") testCompile("org.hamcrest:hamcrest-all:1.3") testCompile("org.mockito:mockito-core:1.9.5") - if (project.name in ["spring", "spring-jms", + if (project.name in ["spring", "spring-orm-hibernate4", "spring-oxm", "spring-struts", "spring-test", "spring-test-mvc", "spring-tx", "spring-web", "spring-webmvc", "spring-webmvc-portlet", "spring-webmvc-tiles3"]) {
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java
@@ -16,20 +16,28 @@ package org.springframework.jms.config; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; + import javax.jms.ConnectionFactory; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.parsing.ComponentDefinition; import org.springframework.beans.factory.parsing.CompositeComponentDefinition; @@ -42,14 +50,15 @@ import org.springframework.jca.endpoint.GenericMessageEndpointManager; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.jms.listener.endpoint.JmsMessageEndpointManager; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ErrorHandler; /** * @author Mark Fisher * @author Juergen Hoeller * @author Christian Dupuis */ -public class JmsNamespaceHandlerTests extends TestCase { +public class JmsNamespaceHandlerTests { private static final String DEFAULT_CONNECTION_FACTORY = "connectionFactory"; @@ -58,17 +67,18 @@ public class JmsNamespaceHandlerTests extends TestCase { private ToolingTestApplicationContext context; - @Override - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { this.context = new ToolingTestApplicationContext("jmsNamespaceHandlerTests.xml", getClass()); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { this.context.close(); } + @Test public void testBeansCreated() { Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class); assertEquals("Context should contain 3 JMS listener containers", 3, containers.size()); @@ -77,6 +87,7 @@ public void testBeansCreated() { assertEquals("Context should contain 3 JCA endpoint containers", 3, containers.size()); } + @Test public void testContainerConfiguration() throws Exception { Map<String, DefaultMessageListenerContainer> containers = context.getBeansOfType(DefaultMessageListenerContainer.class); ConnectionFactory defaultConnectionFactory = context.getBean(DEFAULT_CONNECTION_FACTORY, ConnectionFactory.class); @@ -102,6 +113,7 @@ else if (container.getConnectionFactory().equals(explicitConnectionFactory)) { assertEquals("2 containers should have the explicit connectionFactory", 2, explicitConnectionFactoryCount); } + @Test public void testListeners() throws Exception { TestBean testBean1 = context.getBean("testBean1", TestBean.class); TestBean testBean2 = context.getBean("testBean2", TestBean.class); @@ -111,36 +123,28 @@ public void testListeners() throws Exception { assertNull(testBean2.getName()); assertNull(testBean3.message); - MockControl control1 = MockControl.createControl(TextMessage.class); - TextMessage message1 = (TextMessage) control1.getMock(); - control1.expectAndReturn(message1.getText(), "Test1"); - control1.replay(); + TextMessage message1 = mock(TextMessage.class); + given(message1.getText()).willReturn("Test1"); MessageListener listener1 = getListener("listener1"); listener1.onMessage(message1); assertEquals("Test1", testBean1.getName()); - control1.verify(); - MockControl control2 = MockControl.createControl(TextMessage.class); - TextMessage message2 = (TextMessage) control2.getMock(); - control2.expectAndReturn(message2.getText(), "Test2"); - control2.replay(); + TextMessage message2 = mock(TextMessage.class); + given(message2.getText()).willReturn("Test2"); MessageListener listener2 = getListener("listener2"); listener2.onMessage(message2); assertEquals("Test2", testBean2.getName()); - control2.verify(); - MockControl control3 = MockControl.createControl(TextMessage.class); - TextMessage message3 = (TextMessage) control3.getMock(); - control3.replay(); + TextMessage message3 = mock(TextMessage.class); MessageListener listener3 = getListener(DefaultMessageListenerContainer.class.getName() + "#0"); listener3.onMessage(message3); assertSame(message3, testBean3.message); - control3.verify(); } + @Test public void testErrorHandlers() { ErrorHandler expected = this.context.getBean("testErrorHandler", ErrorHandler.class); ErrorHandler errorHandler1 = getErrorHandler("listener1"); @@ -151,6 +155,7 @@ public void testErrorHandlers() { assertNull(defaultErrorHandler); } + @Test public void testPhases() { int phase1 = getPhase("listener1"); int phase2 = getPhase("listener2"); @@ -182,6 +187,7 @@ public int getPhase(String containerBeanName) { return ((Phased) container).getPhase(); } + @Test public void testComponentRegistration() { assertTrue("Parser should have registered a component named 'listener1'", context.containsComponentDefinition("listener1")); assertTrue("Parser should have registered a component named 'listener2'", context.containsComponentDefinition("listener2")); @@ -192,6 +198,7 @@ public void testComponentRegistration() { context.containsComponentDefinition(JmsMessageEndpointManager.class.getName() + "#0")); } + @Test public void testSourceExtraction() { Iterator iterator = context.getRegisteredComponents(); while (iterator.hasNext()) {
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,14 @@ package org.springframework.jms.connection; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -30,9 +38,8 @@ import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Test; import org.springframework.jms.StubQueue; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.JmsTemplate102; @@ -50,30 +57,23 @@ * @author Juergen Hoeller * @since 26.07.2004 */ -public class JmsTransactionManagerTests extends TestCase { +public class JmsTransactionManagerTests { + + @After + public void verifyTransactionSynchronizationManager() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + } + + @Test public void testTransactionCommit() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -87,33 +87,19 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test public void testTransactionRollback() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.rollback(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -127,33 +113,19 @@ public Object doInJms(Session sess) { }); tm.rollback(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).rollback(); + verify(session).close(); + verify(con).close(); } + @Test public void testParticipatingTransactionWithCommit() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -180,33 +152,19 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test public void testParticipatingTransactionWithRollbackOnly() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.rollback(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -240,39 +198,21 @@ public Object doInJms(Session sess) { // expected } - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).rollback(); + verify(session).close(); + verify(con).close(); } + @Test public void testSuspendedTransaction() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 2); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - con.createSession(false, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session2, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - session2.close(); - session2Control.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(2); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + final ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + final Session session2 = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(con.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session2); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -307,41 +247,21 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(session2).close(); + verify(con, times(2)).close(); } + @Test public void testTransactionSuspension() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 2); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session2, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session2.commit(); - session2Control.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - session2.close(); - session2Control.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(2); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + final ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + final Session session2 = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session, session2); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -376,48 +296,27 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session2).commit(); + verify(session).close(); + verify(session2).close(); + verify(con, times(2)).close(); } + @Test public void testTransactionCommitWithMessageProducer() throws JMSException { Destination dest = new StubQueue(); - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl producerControl = MockControl.createControl(MessageProducer.class); - MessageProducer producer = (MessageProducer) producerControl.getMock(); - MockControl messageControl = MockControl.createControl(Message.class); - final Message message = (Message) messageControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.createProducer(dest); - sessionControl.setReturnValue(producer, 1); - producer.send(message); - producerControl.setVoidCallable(1); - session.getTransacted(); - sessionControl.setReturnValue(true, 1); - session.commit(); - sessionControl.setVoidCallable(1); - producer.close(); - producerControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - producerControl.replay(); - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + Session session = mock(Session.class); + MessageProducer producer = mock(MessageProducer.class); + final Message message = mock(Message.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(session.createProducer(dest)).willReturn(producer); + given(session.getTransacted()).willReturn(true); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -430,34 +329,22 @@ public Message createMessage(Session session) throws JMSException { }); tm.commit(ts); - producerControl.verify(); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(producer).send(message); + verify(session).commit(); + verify(producer).close(); + verify(session).close(); + verify(con).close(); } + @Test + @Deprecated public void testTransactionCommit102WithQueue() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) sessionControl.getMock(); - - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + final QueueSession session = mock(QueueSession.class); + + given(cf.createQueueConnection()).willReturn(con); + given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager102(cf, false); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -471,33 +358,20 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test + @Deprecated public void testTransactionCommit102WithTopic() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(TopicSession.class); - final TopicSession session = (TopicSession) sessionControl.getMock(); - - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + final TopicSession session = mock(TopicSession.class); + + given(cf.createTopicConnection()).willReturn(con); + given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager102(cf, true); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -511,15 +385,8 @@ public Object doInJms(Session sess) { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } - - @Override - protected void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - } - }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,14 @@ package org.springframework.jms.connection; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.ExceptionListener; @@ -28,27 +36,17 @@ import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.Test; /** * @author Juergen Hoeller * @since 26.07.2004 */ -public class SingleConnectionFactoryTests extends TestCase { +public class SingleConnectionFactoryTests { + @Test public void testWithConnection() throws JMSException { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(Connection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); Connection con1 = scf.createConnection(); @@ -61,21 +59,15 @@ public void testWithConnection() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithQueueConnection() throws JMSException { - MockControl conControl = MockControl.createControl(QueueConnection.class); - Connection con = (QueueConnection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(QueueConnection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); QueueConnection con1 = scf.createQueueConnection(); @@ -88,21 +80,15 @@ public void testWithQueueConnection() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithTopicConnection() throws JMSException { - MockControl conControl = MockControl.createControl(TopicConnection.class); - Connection con = (TopicConnection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(TopicConnection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); TopicConnection con1 = scf.createTopicConnection(); @@ -115,26 +101,18 @@ public void testWithTopicConnection() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithConnectionFactory() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -145,27 +123,18 @@ public void testWithConnectionFactory() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithQueueConnectionFactoryAndJms11Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -176,27 +145,18 @@ public void testWithQueueConnectionFactoryAndJms11Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithQueueConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); - - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + + given(cf.createQueueConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createQueueConnection(); @@ -207,27 +167,18 @@ public void testWithQueueConnectionFactoryAndJms102Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -238,27 +189,18 @@ public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); - - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + + given(cf.createTopicConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createTopicConnection(); @@ -269,29 +211,18 @@ public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithConnectionFactoryAndClientId() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.setClientID("myId"); - conControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setClientId("myId"); @@ -303,32 +234,21 @@ public void testWithConnectionFactoryAndClientId() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).setClientID("myId"); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithConnectionFactoryAndExceptionListener() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); ExceptionListener listener = new ChainedExceptionListener(); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.setExceptionListener(listener); - conControl.setVoidCallable(1); - con.getExceptionListener(); - conControl.setReturnValue(listener, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.getExceptionListener()).willReturn(listener); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); @@ -343,18 +263,18 @@ public void testWithConnectionFactoryAndExceptionListener() throws JMSException con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).setExceptionListener(listener); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test public void testWithConnectionFactoryAndReconnectOnException() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); TestConnection con = new TestConnection(); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setReconnectOnException(true); @@ -366,21 +286,18 @@ public void testWithConnectionFactoryAndReconnectOnException() throws JMSExcepti con2.start(); scf.destroy(); // should trigger actual close - cfControl.verify(); assertEquals(2, con.getStartCount()); assertEquals(2, con.getCloseCount()); } + @Test public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); TestConnection con = new TestConnection(); - TestExceptionListener listener = new TestExceptionListener(); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + TestExceptionListener listener = new TestExceptionListener(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); scf.setReconnectOnException(true); @@ -392,29 +309,17 @@ public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException con2.start(); scf.destroy(); // should trigger actual close - cfControl.verify(); assertEquals(2, con.getStartCount()); assertEquals(2, con.getCloseCount()); assertEquals(1, listener.getCount()); } + @Test public void testConnectionFactory102WithQueue() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); - - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + + given(cf.createQueueConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory102(cf, false); QueueConnection con1 = scf.createQueueConnection(); @@ -425,27 +330,18 @@ public void testConnectionFactory102WithQueue() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testConnectionFactory102WithTopic() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); - - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + + given(cf.createTopicConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory102(cf, true); TopicConnection con1 = scf.createTopicConnection(); @@ -456,45 +352,23 @@ public void testConnectionFactory102WithTopic() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testCachingConnectionFactory() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txSessionControl = MockControl.createControl(Session.class); - Session txSession = (Session) txSessionControl.getMock(); - MockControl nonTxSessionControl = MockControl.createControl(Session.class); - Session nonTxSession = (Session) nonTxSessionControl.getMock(); - - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(txSession, 1); - txSession.getTransacted(); - txSessionControl.setReturnValue(true, 1); - txSession.commit(); - txSessionControl.setVoidCallable(1); - txSession.close(); - txSessionControl.setVoidCallable(1); - con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - conControl.setReturnValue(nonTxSession, 1); - nonTxSession.close(); - nonTxSessionControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + Session txSession = mock(Session.class); + Session nonTxSession = mock(Session.class); + + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -516,47 +390,25 @@ public void testCachingConnectionFactory() throws JMSException { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).commit(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); - MockControl txSessionControl = MockControl.createControl(QueueSession.class); - QueueSession txSession = (QueueSession) txSessionControl.getMock(); - MockControl nonTxSessionControl = MockControl.createControl(QueueSession.class); - QueueSession nonTxSession = (QueueSession) nonTxSessionControl.getMock(); - - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(txSession, 1); - txSession.getTransacted(); - txSessionControl.setReturnValue(true, 1); - txSession.rollback(); - txSessionControl.setVoidCallable(1); - txSession.close(); - txSessionControl.setVoidCallable(1); - con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); - conControl.setReturnValue(nonTxSession, 1); - nonTxSession.close(); - nonTxSessionControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + QueueSession txSession = mock(QueueSession.class); + QueueSession nonTxSession = mock(QueueSession.class); + + given(cf.createQueueConnection()).willReturn(con); + given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -578,45 +430,25 @@ public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).rollback(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); - MockControl txSessionControl = MockControl.createControl(TopicSession.class); - TopicSession txSession = (TopicSession) txSessionControl.getMock(); - MockControl nonTxSessionControl = MockControl.createControl(TopicSession.class); - TopicSession nonTxSession = (TopicSession) nonTxSessionControl.getMock(); - - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(txSession, 1); - txSession.getTransacted(); - txSessionControl.setReturnValue(true, 2); - txSession.close(); - txSessionControl.setVoidCallable(1); - con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE); - conControl.setReturnValue(nonTxSession, 1); - nonTxSession.close(); - nonTxSessionControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + TopicSession txSession = mock(TopicSession.class); + TopicSession nonTxSession = mock(TopicSession.class); + + given(cf.createTopicConnection()).willReturn(con); + given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -638,10 +470,11 @@ public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java
@@ -16,6 +16,15 @@ package org.springframework.jms.core; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; @@ -39,9 +48,8 @@ import javax.naming.Context; import javax.naming.NamingException; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.InvalidClientIDException; import org.springframework.jms.InvalidDestinationException; import org.springframework.jms.InvalidSelectorException; @@ -65,105 +73,54 @@ * @author Andre Biryukov * @author Mark Pollack */ -public class JmsTemplate102Tests extends TestCase { - - private Context mockJndiContext; - private MockControl mockJndiControl; - - private MockControl queueConnectionFactoryControl; - private QueueConnectionFactory mockQueueConnectionFactory; - - private MockControl queueConnectionControl; - private QueueConnection mockQueueConnection; - - private MockControl queueSessionControl; - private QueueSession mockQueueSession; - - private MockControl queueControl; - private Queue mockQueue; - - private MockControl topicConnectionFactoryControl; - private TopicConnectionFactory mockTopicConnectionFactory; - - private MockControl topicConnectionControl; - private TopicConnection mockTopicConnection; - - private MockControl topicSessionControl; - private TopicSession mockTopicSession; - - private MockControl topicControl; - private Topic mockTopic; +public class JmsTemplate102Tests { + + private Context jndiContext; + private QueueConnectionFactory queueConnectionFactory; + private QueueConnection queueConnection; + private QueueSession queueSession; + private Queue queue; + private TopicConnectionFactory topicConnectionFactory; + private TopicConnection topicConnection; + private TopicSession topicSession; + private Topic topic; private int deliveryMode = DeliveryMode.PERSISTENT; private int priority = 9; private int timeToLive = 10000; - /** - * Create the mock objects for testing. - */ - @Override - protected void setUp() throws Exception { - mockJndiControl = MockControl.createControl(Context.class); - mockJndiContext = (Context) this.mockJndiControl.getMock(); - + @Before + public void setUpMocks() throws Exception { + jndiContext = mock(Context.class); createMockForQueues(); createMockForTopics(); - - mockJndiContext.close(); - mockJndiControl.replay(); } private void createMockForTopics() throws JMSException, NamingException { - topicConnectionFactoryControl = MockControl.createControl(TopicConnectionFactory.class); - mockTopicConnectionFactory = (TopicConnectionFactory) topicConnectionFactoryControl.getMock(); - - topicConnectionControl = MockControl.createControl(TopicConnection.class); - mockTopicConnection = (TopicConnection) topicConnectionControl.getMock(); + topicConnectionFactory = mock(TopicConnectionFactory.class); + topicConnection = mock(TopicConnection.class); + topic = mock(Topic.class); + topicSession = mock(TopicSession.class); - topicControl = MockControl.createControl(Topic.class); - mockTopic = (Topic) topicControl.getMock(); - - topicSessionControl = MockControl.createControl(TopicSession.class); - mockTopicSession = (TopicSession) topicSessionControl.getMock(); - - mockTopicConnectionFactory.createTopicConnection(); - topicConnectionFactoryControl.setReturnValue(mockTopicConnection); - topicConnectionFactoryControl.replay(); - - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - topicConnectionControl.setReturnValue(mockTopicSession); - mockTopicSession.getTransacted(); - topicSessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testTopic"); - mockJndiControl.setReturnValue(mockTopic); + given(topicConnectionFactory.createTopicConnection()).willReturn(topicConnection); + given(topicConnection.createTopicSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(topicSession); + given(topicSession.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testTopic")).willReturn(topic); } private void createMockForQueues() throws JMSException, NamingException { - queueConnectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class); - mockQueueConnectionFactory = (QueueConnectionFactory) queueConnectionFactoryControl.getMock(); - - queueConnectionControl = MockControl.createControl(QueueConnection.class); - mockQueueConnection = (QueueConnection) queueConnectionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - queueSessionControl = MockControl.createControl(QueueSession.class); - mockQueueSession = (QueueSession) queueSessionControl.getMock(); - - mockQueueConnectionFactory.createQueueConnection(); - queueConnectionFactoryControl.setReturnValue(mockQueueConnection); - queueConnectionFactoryControl.replay(); + queueConnectionFactory = mock(QueueConnectionFactory.class); + queueConnection = mock(QueueConnection.class); + queue = mock(Queue.class); + queueSession = mock(QueueSession.class); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - queueConnectionControl.setReturnValue(mockQueueSession); - mockQueueSession.getTransacted(); - queueSessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testQueue"); - mockJndiControl.setReturnValue(mockQueue); + given(queueConnectionFactory.createQueueConnection()).willReturn(queueConnection); + given(queueConnection.createQueueSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(queueSession); + given(queueSession.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testQueue")).willReturn(queue); } private JmsTemplate102 createTemplate() { @@ -172,7 +129,7 @@ private JmsTemplate102 createTemplate() { destMan.setJndiTemplate(new JndiTemplate() { @Override protected Context createInitialContext() { - return mockJndiContext; + return jndiContext; } }); template.setDestinationResolver(destMan); @@ -189,21 +146,13 @@ protected boolean useTransactedTemplate() { } + @Test public void testTopicSessionCallback() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicSessionControl.replay(); - topicConnectionControl.replay(); - template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { @@ -212,39 +161,24 @@ public Object doInJms(Session session) throws JMSException { } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the execute(ProducerCallback) using a topic. */ + @Test public void testTopicProducerCallback() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); + TopicPublisher topicPublisher = mock(TopicPublisher.class); - mockTopicSession.createPublisher(null); - topicSessionControl.setReturnValue(mockTopicPublisher); - - mockTopicPublisher.getPriority(); - topicPublisherControl.setReturnValue(4); - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicPublisherControl.replay(); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(null)).willReturn(topicPublisher); + given(topicPublisher.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -255,45 +189,27 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the execute(ProducerCallback) using a topic. */ + @Test public void testTopicProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); - - mockTopicSession.createPublisher(null); - topicSessionControl.setReturnValue(mockTopicPublisher); + TopicPublisher topicPublisher = mock(TopicPublisher.class); - mockTopicPublisher.setDisableMessageID(true); - topicPublisherControl.setVoidCallable(1); - mockTopicPublisher.setDisableMessageTimestamp(true); - topicPublisherControl.setVoidCallable(1); - mockTopicPublisher.getPriority(); - topicPublisherControl.setReturnValue(4); - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicPublisherControl.replay(); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(null)).willReturn(topicPublisher); + given(topicPublisher.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -304,30 +220,24 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicPublisher).setDisableMessageID(true); + verify(topicPublisher).setDisableMessageTimestamp(true); + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the method execute(SessionCallback action) with using the * point to point domain as specified by the value of isPubSubDomain = false. */ + @Test public void testQueueSessionCallback() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSessionControl.replay(); - queueConnectionControl.replay(); - template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { @@ -336,39 +246,24 @@ public Object doInJms(Session session) throws JMSException { } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSession).close(); + verify(queueConnection).close(); } /** * Test the method execute(ProducerCallback) with a Queue. */ + @Test public void testQueueProducerCallback() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain. - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - - mockQueueSession.createSender(null); - queueSessionControl.setReturnValue(mockQueueSender); - - mockQueueSender.getPriority(); - queueSenderControl.setReturnValue(4); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); + QueueSender queueSender = mock(QueueSender.class); - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(queueSession.createSender(null)).willReturn(queueSender); + given(queueSender.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -380,42 +275,24 @@ public Object doInJms(Session session, MessageProducer producer) } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } + @Test public void testQueueProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain. - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); template.afterPropertiesSet(); - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); - mockQueueSession.createSender(null); - queueSessionControl.setReturnValue(mockQueueSender); - - mockQueueSender.setDisableMessageID(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.setDisableMessageTimestamp(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.getPriority(); - queueSenderControl.setReturnValue(4); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(queueSession.createSender(null)).willReturn(queueSender); + given(queueSender.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -426,19 +303,22 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSender).setDisableMessageID(true); + verify(queueSender).setDisableMessageTimestamp(true); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } /** * Test the setting of the JmsTemplate properties. */ + @Test public void testBeanProperties() throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); - assertTrue("connection factory ok", template.getConnectionFactory() == mockQueueConnectionFactory); + assertTrue("connection factory ok", template.getConnectionFactory() == queueConnectionFactory); JmsTemplate102 s102 = createTemplate(); try { @@ -452,7 +332,7 @@ public void testBeanProperties() throws Exception { // The default is for the JmsTemplate102 to send to queues. // Test to make sure exeception is thrown and has reasonable message. s102 = createTemplate(); - s102.setConnectionFactory(mockTopicConnectionFactory); + s102.setConnectionFactory(topicConnectionFactory); try { s102.afterPropertiesSet(); fail("IllegalArgumentException not thrown. Mismatch of Destination and ConnectionFactory types."); @@ -462,7 +342,7 @@ public void testBeanProperties() throws Exception { } s102 = createTemplate(); - s102.setConnectionFactory(mockQueueConnectionFactory); + s102.setConnectionFactory(queueConnectionFactory); s102.setPubSubDomain(true); try { s102.afterPropertiesSet(); @@ -477,6 +357,7 @@ public void testBeanProperties() throws Exception { * Test the method send(String destination, MessgaeCreator c) using * a queue and default QOS values. */ + @Test public void testSendStringQueue() throws Exception { sendQueue(true, false, false, true); } @@ -485,20 +366,23 @@ public void testSendStringQueue() throws Exception { * Test the method send(String destination, MessageCreator c) when * explicit QOS parameters are enabled, using a queue. */ + @Test public void testSendStringQueueWithQOS() throws Exception { sendQueue(false, false, false, false); } /** * Test the method send(MessageCreator c) using default QOS values. */ + @Test public void testSendDefaultDestinationQueue() throws Exception { sendQueue(true, false, true, true); } /** * Test the method send(MessageCreator c) using explicit QOS values. */ + @Test public void testSendDefaultDestinationQueueWithQOS() throws Exception { sendQueue(false, false, true, false); } @@ -507,6 +391,7 @@ public void testSendDefaultDestinationQueueWithQOS() throws Exception { * Test the method send(String destination, MessageCreator c) using * a topic and default QOS values. */ + @Test public void testSendStringTopic() throws Exception { sendTopic(true, false); } @@ -515,6 +400,7 @@ public void testSendStringTopic() throws Exception { * Test the method send(String destination, MessageCreator c) using explicit * QOS values. */ + @Test public void testSendStringTopicWithQOS() throws Exception { sendTopic(false, false); } @@ -523,6 +409,7 @@ public void testSendStringTopicWithQOS() throws Exception { * Test the method send(Destination queue, MessgaeCreator c) using * a queue and default QOS values. */ + @Test public void testSendQueue() throws Exception { sendQueue(true, false, false, true); } @@ -531,6 +418,7 @@ public void testSendQueue() throws Exception { * Test the method send(Destination queue, MessageCreator c) sing explicit * QOS values. */ + @Test public void testSendQueueWithQOS() throws Exception { sendQueue(false, false, false, false); } @@ -539,6 +427,7 @@ public void testSendQueueWithQOS() throws Exception { * Test the method send(Destination queue, MessgaeCreator c) using * a topic and default QOS values. */ + @Test public void testSendTopic() throws Exception { sendTopic(true, false); } @@ -547,6 +436,7 @@ public void testSendTopic() throws Exception { * Test the method send(Destination queue, MessageCreator c) using explicity * QOS values. */ + @Test public void testSendTopicWithQOS() throws Exception { sendQueue(false, false, false, true); } @@ -560,62 +450,30 @@ private void sendQueue( throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); if (useDefaultDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } if (disableIdAndTimestamp) { template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); } - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); + TextMessage message = mock(TextMessage.class); - if (disableIdAndTimestamp) { - mockQueueSender.setDisableMessageID(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.setDisableMessageTimestamp(true); - queueSenderControl.setVoidCallable(1); - } - mockQueueSession.createSender(this.mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("just testing"); - queueSessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); - } + given(queueSession.createSender(this.queue)).willReturn(queueSender); + given(queueSession.createTextMessage("just testing")).willReturn(message); - if (ignoreQOS) { - mockQueueSender.send(mockMessage); - } - else { + if (!ignoreQOS) { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockQueueSender.send(mockMessage, deliveryMode, priority, timeToLive); } - queueSenderControl.setVoidCallable(1); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); if (useDefaultDestination) { template.send(new MessageCreator() { @@ -627,7 +485,7 @@ public Message createMessage(Session session) throws JMSException { } else { if (explicitQueue) { - template.send(mockQueue, new MessageCreator() { + template.send(queue, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("just testing"); @@ -645,61 +503,54 @@ public Message createMessage(Session session) } } - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); - queueSenderControl.verify(); + if (disableIdAndTimestamp) { + verify(queueSender).setDisableMessageID(true); + verify(queueSender).setDisableMessageTimestamp(true); + } + + if (useTransactedTemplate()) { + verify(queueSession).commit(); + } + + if (ignoreQOS) { + verify(queueSender).send(message); + } + else { + verify(queueSender).send(message, deliveryMode, priority, timeToLive); + } + + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } private void sendTopic(boolean ignoreQOS, boolean explicitTopic) throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); - - mockTopicSession.createPublisher(this.mockTopic); - topicSessionControl.setReturnValue(mockTopicPublisher); - mockTopicSession.createTextMessage("just testing"); - topicSessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockTopicSession.commit(); - topicSessionControl.setVoidCallable(1); - } - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - + TopicPublisher topicPublisher = mock(TopicPublisher.class); + TextMessage message = mock(TextMessage.class); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(this.topic)).willReturn(topicPublisher); + given(topicSession.createTextMessage("just testing")).willReturn(message); if (ignoreQOS) { - mockTopicPublisher.publish(mockMessage); + topicPublisher.publish(message); } else { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockTopicPublisher.publish(mockMessage, deliveryMode, priority, timeToLive); + topicPublisher.publish(message, deliveryMode, priority, timeToLive); } - topicPublisherControl.replay(); template.setPubSubDomain(true); if (explicitTopic) { - template.send(mockTopic, new MessageCreator() { + template.send(topic, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { @@ -717,163 +568,175 @@ public Message createMessage(Session session) }); } - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); - topicPublisherControl.verify(); + if (useTransactedTemplate()) { + verify(topicSession).commit(); + } + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); + verify(jndiContext).close(); } + @Test public void testConverter() throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); + TextMessage message = mock(TextMessage.class); - mockQueueSession.createSender(this.mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("Hello world"); - queueSessionControl.setReturnValue(mockMessage); + given(queueSession.createSender(this.queue)).willReturn(queueSender); + given(queueSession.createTextMessage("Hello world")).willReturn(message); + + template.convertAndSend(queue, s); if (useTransactedTemplate()) { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); + verify(queueSession).commit(); } - - mockQueueSender.send(mockMessage); - queueSenderControl.setVoidCallable(1); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); - - template.convertAndSend(mockQueue, s); - - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); - queueSenderControl.verify(); + verify(queueSender).send(message); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } + @Test public void testQueueReceiveDefaultDestination() throws Exception { doTestReceive(false, false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveDestination() throws Exception { doTestReceive(false, true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(false, true, false, false, true, false, false, 1000); } + @Test public void testQueueReceiveStringDestination() throws Exception { doTestReceive(false, false, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(false, false, true, false, false, true, true, 1000); } + @Test public void testQueueReceiveDestinationWithSelector() throws Exception { doTestReceive(false, true, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(false, true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveStringDestinationWithSelector() throws Exception { doTestReceive(false, false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(false, false, true, true, false, false, false, 1000); } + @Test public void testQueueReceiveAndConvertStringDestination() throws Exception { doTestReceive(false, false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDestination() throws Exception { doTestReceive(false, true, false, true, false, false, true, 1000); } + @Test public void testQueueReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(false, false, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveAndConvertStringDestinationWithSelector() throws Exception { doTestReceive(false, false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(false, true, false, true, false, true, false, 1000); } + @Test public void testTopicReceiveDefaultDestination() throws Exception { doTestReceive(true, false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveDestination() throws Exception { doTestReceive(true, true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(true, true, false, false, true, false, false, 1000); } + @Test public void testTopicReceiveStringDestination() throws Exception { doTestReceive(true, false, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testTopicReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(true, false, true, false, false, true, true, 1000); } + @Test public void testTopicReceiveDestinationWithSelector() throws Exception { doTestReceive(true, true, false, false, false, true, false, 1000); } + @Test public void testTopicReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(true, true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveStringDestinationWithSelector() throws Exception { doTestReceive(true, false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(true, false, true, true, false, false, false, 1000); } + @Test public void testTopicReceiveAndConvertStringDestination() throws Exception { doTestReceive(true, false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDestination() throws Exception { doTestReceive(true, true, false, true, false, false, true, 1000); } + @Test public void testTopicReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(true, false, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testTopicReceiveAndConvertStringDestinationWithSelector() throws Exception { doTestReceive(true, false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(true, true, false, true, false, true, false, 1000); } @@ -886,41 +749,38 @@ private void doTestReceive( JmsTemplate102 template = createTemplate(); template.setPubSubDomain(pubSub); - if (pubSub) { - template.setConnectionFactory(mockTopicConnectionFactory); - } - else { - template.setConnectionFactory(mockQueueConnectionFactory); - } + template.setConnectionFactory(pubSub ? topicConnectionFactory : queueConnectionFactory); // Override the default settings for client ack used in the test setup. // Can't use Session.getAcknowledgeMode() if (pubSub) { - topicConnectionControl.reset(); + reset(topicConnection); if (clientAcknowledge) { template.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE); + given(topicConnection.createTopicSession( + useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE)).willReturn(topicSession); } else { template.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); + given(topicConnection.createTopicSession( + useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE)).willReturn(topicSession); } - topicConnectionControl.setReturnValue(mockTopicSession); } else { - queueConnectionControl.reset(); + reset(queueConnection); if (clientAcknowledge) { template.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE); + given(queueConnection.createQueueSession( + useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE)).willReturn(queueSession); } else { template.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); + given(queueConnection.createQueueSession( + useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE)).willReturn(queueSession); } - queueConnectionControl.setReturnValue(mockQueueSession); } - Destination dest = pubSub ? (Destination) mockTopic : (Destination) mockQueue; + Destination dest = pubSub ? (Destination) topic : (Destination) queue; if (useDefaultDestination) { template.setDefaultDestination(dest); @@ -930,94 +790,38 @@ private void doTestReceive( } template.setReceiveTimeout(timeout); - if (pubSub) { - mockTopicConnection.start(); - topicConnectionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - } - else { - mockQueueConnection.start(); - queueConnectionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - } String selectorString = "selector"; - MockControl messageConsumerControl = null; - MessageConsumer mockMessageConsumer = null; - - if (pubSub) { - messageConsumerControl = MockControl.createControl(TopicSubscriber.class); - TopicSubscriber mockTopicSubscriber = (TopicSubscriber) messageConsumerControl.getMock(); - mockMessageConsumer = mockTopicSubscriber; - mockTopicSession.createSubscriber(mockTopic, messageSelector ? selectorString : null, noLocal); - topicSessionControl.setReturnValue(mockTopicSubscriber); - } - else { - messageConsumerControl = MockControl.createControl(QueueReceiver.class); - QueueReceiver mockQueueReceiver = (QueueReceiver) messageConsumerControl.getMock(); - mockMessageConsumer = mockQueueReceiver; - mockQueueSession.createReceiver(mockQueue, messageSelector ? selectorString : null); - queueSessionControl.setReturnValue(mockQueueReceiver); - } - - if (useTransactedTemplate()) { - if (pubSub) { - mockTopicSession.commit(); - topicSessionControl.setVoidCallable(1); - } - else { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); - } - } + MessageConsumer messageConsumer = null; if (pubSub) { - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); + TopicSubscriber topicSubscriber = mock(TopicSubscriber.class); + messageConsumer = topicSubscriber; + given(topicSession.createSubscriber(topic, + messageSelector ? selectorString : null, noLocal)).willReturn(topicSubscriber); } else { - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); + QueueReceiver queueReceiver = mock(QueueReceiver.class); + messageConsumer = queueReceiver; + given(queueSession.createReceiver(queue, + messageSelector ? selectorString : null)).willReturn(queueReceiver); } - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + TextMessage textMessage = mock(TextMessage.class); if (testConverter) { - mockMessage.getText(); - messageControl.setReturnValue("Hello World!"); - } - if (!useTransactedSession() && clientAcknowledge) { - mockMessage.acknowledge(); - messageControl.setVoidCallable(1); - } - - if (pubSub) { - topicSessionControl.replay(); - topicConnectionControl.replay(); - } - else { - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(textMessage.getText()).willReturn("Hello World!"); } - messageControl.replay(); if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) { - mockMessageConsumer.receiveNoWait(); + given(messageConsumer.receiveNoWait()).willReturn(textMessage); } else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { - mockMessageConsumer.receive(); + given(messageConsumer.receive()).willReturn(textMessage); } else { - mockMessageConsumer.receive(timeout); + given(messageConsumer.receive(timeout)).willReturn(textMessage); } - messageConsumerControl.setReturnValue(mockMessage); - mockMessageConsumer.close(); - messageConsumerControl.setVoidCallable(1); - - messageConsumerControl.replay(); Message message = null; String textFromMessage = null; @@ -1056,112 +860,123 @@ else if (explicitDestination) { } } - if (pubSub) { - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + if (testConverter) { + assertEquals("Message text should be equal", "Hello World!", textFromMessage); } else { - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + assertEquals("Messages should refer to the same object", message, textMessage); } - messageConsumerControl.verify(); - messageControl.verify(); - if (testConverter) { - assertEquals("Message text should be equal", "Hello World!", textFromMessage); + if (pubSub) { + verify(topicConnection).start(); + verify(topicConnection).close(); + verify(topicSession).close(); } else { - assertEquals("Messages should refer to the same object", message, mockMessage); + verify(queueConnection).start(); + verify(queueConnection).close(); + verify(queueSession).close(); + } + + + if (useTransactedTemplate()) { + if (pubSub) { + verify(topicSession).commit(); + } + else { + verify(queueSession).commit(); + } + } + + if (!useTransactedSession() && clientAcknowledge) { + verify(textMessage).acknowledge(); } + + verify(messageConsumer).close(); } + @Test public void testIllegalStateException() throws Exception { doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class); } + @Test public void testInvalidClientIDException() throws Exception { doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class); } + @Test public void testInvalidDestinationException() throws Exception { doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class); } + @Test public void testInvalidSelectorException() throws Exception { doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class); } + @Test public void testJmsSecurityException() throws Exception { doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class); } + @Test public void testMessageEOFException() throws Exception { doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class); } + @Test public void testMessageFormatException() throws Exception { doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class); } + @Test public void testMessageNotReadableException() throws Exception { doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class); } + @Test public void testMessageNotWriteableException() throws Exception { doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class); } + @Test public void testResourceAllocationException() throws Exception { doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class); } + @Test public void testTransactionInProgressException() throws Exception { doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class); } + @Test public void testTransactionRolledBackException() throws Exception { doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class); } + @Test public void testUncategorizedJmsException() throws Exception { doTestJmsException(new javax.jms.JMSException(""), UncategorizedJmsException.class); } protected void doTestJmsException(JMSException original, Class thrownExceptionClass) throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); - - queueSessionControl.reset(); - mockQueueSession.createSender(mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("Hello world"); - queueSessionControl.setReturnValue(mockMessage); - - mockQueueSender.send(mockMessage); - queueSenderControl.setThrowable(original, 1); - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); + QueueSender queueSender = mock(QueueSender.class); + TextMessage textMessage = mock(TextMessage.class); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); + reset(queueSession); + given(queueSession.createSender(queue)).willReturn(queueSender); + given(queueSession.createTextMessage("Hello world")).willReturn(textMessage); - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + willThrow(original).given(queueSender).send(textMessage); try { - template.convertAndSend(mockQueue, s); + template.convertAndSend(queue, s); fail("Should have thrown JmsException"); } catch (JmsException wrappedEx) { @@ -1170,10 +985,9 @@ protected void doTestJmsException(JMSException original, Class thrownExceptionCl assertEquals(original, wrappedEx.getCause()); } - queueSenderControl.verify(); - queueSessionControl.verify(); - queueConnectionControl.verify(); - queueConnectionFactoryControl.verify(); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java
@@ -16,6 +16,16 @@ package org.springframework.jms.core; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; @@ -32,11 +42,9 @@ import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; -import javax.naming.NamingException; - -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.InvalidClientIDException; import org.springframework.jms.InvalidDestinationException; import org.springframework.jms.InvalidSelectorException; @@ -66,22 +74,13 @@ * @author Andre Biryukov * @author Mark Pollack */ -public class JmsTemplateTests extends TestCase { - - private Context mockJndiContext; - private MockControl mockJndiControl; - - private MockControl connectionFactoryControl; - private ConnectionFactory mockConnectionFactory; - - private MockControl connectionControl; - private Connection mockConnection; +public class JmsTemplateTests { - private MockControl sessionControl; - private Session mockSession; - - private MockControl queueControl; - private Destination mockQueue; + private Context jndiContext; + private ConnectionFactory connectionFactory; + private Connection connection; + private Session session; + private Destination queue; private int deliveryMode = DeliveryMode.PERSISTENT; private int priority = 9; @@ -91,41 +90,19 @@ public class JmsTemplateTests extends TestCase { /** * Create the mock objects for testing. */ - @Override - protected void setUp() throws Exception { - mockJndiControl = MockControl.createControl(Context.class); - mockJndiContext = (Context) this.mockJndiControl.getMock(); - - createMockforDestination(); - - mockJndiContext.close(); - mockJndiControl.replay(); - } - - private void createMockforDestination() throws JMSException, NamingException { - connectionFactoryControl = MockControl.createControl(ConnectionFactory.class); - mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock(); + @Before + public void setupMocks() throws Exception { + jndiContext = mock(Context.class); + connectionFactory = mock(ConnectionFactory.class); + connection = mock(Connection.class); + session = mock(Session.class); + queue = mock(Queue.class); - connectionControl = MockControl.createControl(Connection.class); - mockConnection = (Connection) connectionControl.getMock(); - - sessionControl = MockControl.createControl(Session.class); - mockSession = (Session) sessionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - mockConnectionFactory.createConnection(); - connectionFactoryControl.setReturnValue(mockConnection); - connectionFactoryControl.replay(); - - mockConnection.createSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - connectionControl.setReturnValue(mockSession); - mockSession.getTransacted(); - sessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testDestination"); - mockJndiControl.setReturnValue(mockQueue); + given(connectionFactory.createConnection()).willReturn(connection); + given(connection.createSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(session.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testDestination")).willReturn(queue); } private JmsTemplate createTemplate() { @@ -134,7 +111,7 @@ private JmsTemplate createTemplate() { destMan.setJndiTemplate(new JndiTemplate() { @Override protected Context createInitialContext() { - return mockJndiContext; + return jndiContext; } }); template.setDestinationResolver(destMan); @@ -151,6 +128,7 @@ protected boolean useTransactedTemplate() { } + @Test public void testExceptionStackTrace() { JMSException jmsEx = new JMSException("could not connect"); Exception innerEx = new Exception("host not found"); @@ -163,29 +141,14 @@ public void testExceptionStackTrace() { assertTrue("inner jms exception not found", trace.indexOf("host not found") > 0); } + @Test public void testProducerCallback() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - - mockSession.createProducer(null); - sessionControl.setReturnValue(mockMessageProducer); - - mockMessageProducer.getPriority(); - messageProducerControl.setReturnValue(4); - - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); + MessageProducer messageProducer = mock(MessageProducer.class); + given(session.createProducer(null)).willReturn(messageProducer); + given(messageProducer.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -196,40 +159,21 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } + @Test public void testProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - - mockSession.createProducer(null); - sessionControl.setReturnValue(mockMessageProducer); - - mockMessageProducer.setDisableMessageID(true); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.setDisableMessageTimestamp(true); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.getPriority(); - messageProducerControl.setReturnValue(4); - - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); + MessageProducer messageProducer = mock(MessageProducer.class); + given(session.createProducer(null)).willReturn(messageProducer); + given(messageProducer.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -240,26 +184,20 @@ public Object doInJms(Session session, MessageProducer producer) throws JMSExcep } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(messageProducer).setDisableMessageID(true); + verify(messageProducer).setDisableMessageTimestamp(true); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } /** * Test the method execute(SessionCallback action). */ + @Test public void testSessionCallback() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); - - mockSession.close(); - sessionControl.setVoidCallable(1); - - mockConnection.close(); - connectionControl.setVoidCallable(1); - - sessionControl.replay(); - connectionControl.replay(); + template.setConnectionFactory(connectionFactory); template.execute(new SessionCallback() { @Override @@ -269,35 +207,16 @@ public Object doInJms(Session session) throws JMSException { } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(session).close(); + verify(connection).close(); } + @Test public void testSessionCallbackWithinSynchronizedTransaction() throws Exception { - SingleConnectionFactory scf = new SingleConnectionFactory(mockConnectionFactory); + SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); JmsTemplate template = createTemplate(); template.setConnectionFactory(scf); - mockConnection.start(); - connectionControl.setVoidCallable(1); - // We're gonna call getTransacted 3 times, i.e. 2 more times. - mockSession.getTransacted(); - sessionControl.setReturnValue(useTransactedSession(), 2); - if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); - } - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.stop(); - connectionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - sessionControl.replay(); - connectionControl.replay(); - TransactionSynchronizationManager.initSynchronization(); try { template.execute(new SessionCallback() { @@ -315,8 +234,8 @@ public Object doInJms(Session session) throws JMSException { } }); - assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, null, false)); - assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)); + assertSame(session, ConnectionFactoryUtils.getTransactionalSession(scf, null, false)); + assertSame(session, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)); TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf); Connection tac = tacf.createConnection(); @@ -339,15 +258,20 @@ public Object doInJms(Session session) throws JMSException { } assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(connection).start(); + if (useTransactedTemplate()) { + verify(session).commit(); + } + verify(session).close(); + verify(connection).stop(); + verify(connection).close(); } /** * Test sending to a destination using the method * send(Destination d, MessageCreator messageCreator) */ + @Test public void testSendDestination() throws Exception { doTestSendDestination(true, false, true, false); } @@ -356,6 +280,7 @@ public void testSendDestination() throws Exception { * Test seding to a destination using the method * send(String d, MessageCreator messageCreator) */ + @Test public void testSendDestinationName() throws Exception { doTestSendDestination(false, false, true, false); } @@ -364,6 +289,7 @@ public void testSendDestinationName() throws Exception { * Test sending to a destination using the method * send(Destination d, MessageCreator messageCreator) using QOS parameters. */ + @Test public void testSendDestinationWithQOS() throws Exception { doTestSendDestination(true, false, false, true); } @@ -372,34 +298,39 @@ public void testSendDestinationWithQOS() throws Exception { * Test sending to a destination using the method * send(String d, MessageCreator messageCreator) using QOS parameters. */ + @Test public void testSendDestinationNameWithQOS() throws Exception { doTestSendDestination(false, false, false, true); } /** * Test sending to the default destination. */ + @Test public void testSendDefaultDestination() throws Exception { doTestSendDestination(true, true, true, true); } /** * Test sending to the default destination name. */ + @Test public void testSendDefaultDestinationName() throws Exception { doTestSendDestination(false, true, true, true); } /** * Test sending to the default destination using explicit QOS parameters. */ + @Test public void testSendDefaultDestinationWithQOS() throws Exception { doTestSendDestination(true, true, false, false); } /** * Test sending to the default destination name using explicit QOS parameters. */ + @Test public void testSendDefaultDestinationNameWithQOS() throws Exception { doTestSendDestination(false, true, false, false); } @@ -414,13 +345,13 @@ private void doTestSendDestination( boolean ignoreQOS, boolean disableIdAndTimestamp) throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); String destinationName = "testDestination"; if (useDefaultDestination) { if (explicitDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } else { template.setDefaultDestinationName(destinationName); @@ -431,51 +362,18 @@ private void doTestSendDestination( template.setMessageTimestampEnabled(false); } - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - mockSession.createProducer(mockQueue); - sessionControl.setReturnValue(mockMessageProducer); - mockSession.createTextMessage("just testing"); - sessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); - } - - if (disableIdAndTimestamp) { - mockMessageProducer.setDisableMessageID(true); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.setDisableMessageTimestamp(true); - messageProducerControl.setVoidCallable(1); - } + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("just testing")).willReturn(textMessage); - if (ignoreQOS) { - mockMessageProducer.send(mockMessage); - } - else { + if (!ignoreQOS) { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockMessageProducer.send(mockMessage, deliveryMode, priority, timeToLive); } - messageProducerControl.setVoidCallable(1); - - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); if (useDefaultDestination) { template.send(new MessageCreator() { @@ -487,7 +385,7 @@ public Message createMessage(Session session) throws JMSException { } else { if (explicitDestination) { - template.send(mockQueue, new MessageCreator() { + template.send(queue, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("just testing"); @@ -504,119 +402,131 @@ public Message createMessage(Session session) throws JMSException { } } - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); - messageProducerControl.verify(); + if (useTransactedTemplate()) { + verify(session).commit(); + } + + if (disableIdAndTimestamp) { + verify(messageProducer).setDisableMessageID(true); + verify(messageProducer).setDisableMessageTimestamp(true); + } + + if (ignoreQOS) { + verify(messageProducer).send(textMessage); + } + else { + verify(messageProducer).send(textMessage, deliveryMode, priority, timeToLive); + } + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } + @Test public void testConverter() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - mockSession.createProducer(mockQueue); - sessionControl.setReturnValue(mockMessageProducer); - mockSession.createTextMessage("Hello world"); - sessionControl.setReturnValue(mockMessage); + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("Hello world")).willReturn(textMessage); - mockMessageProducer.send(mockMessage); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); + template.convertAndSend(queue, s); + verify(messageProducer).send(textMessage); + verify(messageProducer).close(); if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); + verify(session).commit(); } - - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); - - template.convertAndSend(mockQueue, s); - - messageProducerControl.verify(); - sessionControl.verify(); - connectionControl.verify(); - connectionFactoryControl.verify(); + verify(session).close(); + verify(connection).close(); } + @Test public void testReceiveDefaultDestination() throws Exception { doTestReceive(true, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDefaultDestinationName() throws Exception { doTestReceive(false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestination() throws Exception { doTestReceive(true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(true, false, false, true, false, false, 1000); } + @Test public void testReceiveDestinationName() throws Exception { doTestReceive(false, false, false, false, false, true, 1000); } + @Test public void testReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(true, true, false, false, true, true, 1000); } + @Test public void testReceiveDefaultDestinationNameWithSelector() throws Exception { doTestReceive(false, true, false, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveDestinationWithSelector() throws Exception { doTestReceive(true, false, false, false, true, false, 1000); } + @Test public void testReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestinationNameWithSelector() throws Exception { doTestReceive(false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(true, true, true, false, false, false, 1000); } + @Test public void testReceiveAndConvertDefaultDestinationName() throws Exception { doTestReceive(false, true, true, false, false, false, 1000); } + @Test public void testReceiveAndConvertDestinationName() throws Exception { doTestReceive(false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveAndConvertDestination() throws Exception { doTestReceive(true, false, true, false, false, true, 1000); } + @Test public void testReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(true, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveAndConvertDestinationNameWithSelector() throws Exception { doTestReceive(false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(true, false, true, false, true, false, 1000); } @@ -627,13 +537,13 @@ private void doTestReceive( throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); String destinationName = "testDestination"; if (useDefaultDestination) { if (explicitDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } else { template.setDefaultDestinationName(destinationName); @@ -644,67 +554,34 @@ private void doTestReceive( } template.setReceiveTimeout(timeout); - mockConnection.start(); - connectionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - MockControl messageConsumerControl = MockControl.createControl(MessageConsumer.class); - MessageConsumer mockMessageConsumer = (MessageConsumer) messageConsumerControl.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); String selectorString = "selector"; - mockSession.createConsumer(mockQueue, messageSelector ? selectorString : null); - sessionControl.setReturnValue(mockMessageConsumer); + given(session.createConsumer(queue, + messageSelector ? selectorString : null)).willReturn(messageConsumer); - if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); - } - else if (!useTransactedSession()) { - mockSession.getAcknowledgeMode(); - if (clientAcknowledge) { - sessionControl.setReturnValue(Session.CLIENT_ACKNOWLEDGE, 1); - } - else { - sessionControl.setReturnValue(Session.AUTO_ACKNOWLEDGE, 1); - } + if (!useTransactedTemplate() && !useTransactedSession()) { + given(session.getAcknowledgeMode()).willReturn( + clientAcknowledge ? Session.CLIENT_ACKNOWLEDGE + : Session.AUTO_ACKNOWLEDGE); } - mockSession.close(); - sessionControl.setVoidCallable(1); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + TextMessage textMessage = mock(TextMessage.class); if (testConverter) { - mockMessage.getText(); - messageControl.setReturnValue("Hello World!"); - } - if (!useTransactedSession() && clientAcknowledge) { - mockMessage.acknowledge(); - messageControl.setVoidCallable(1); + given(textMessage.getText()).willReturn("Hello World!"); } - sessionControl.replay(); - connectionControl.replay(); - messageControl.replay(); - if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) { - mockMessageConsumer.receiveNoWait(); + given(messageConsumer.receiveNoWait()).willReturn(textMessage); } else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { - mockMessageConsumer.receive(); + given(messageConsumer.receive()).willReturn(textMessage); } else { - mockMessageConsumer.receive(timeout); + given(messageConsumer.receive(timeout)).willReturn(textMessage); } - messageConsumerControl.setReturnValue(mockMessage); - mockMessageConsumer.close(); - messageConsumerControl.setVoidCallable(1); - - messageConsumerControl.replay(); - Message message = null; String textFromMessage = null; @@ -721,12 +598,12 @@ else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { else if (explicitDestination) { if (testConverter) { textFromMessage = (String) - (messageSelector ? template.receiveSelectedAndConvert(mockQueue, selectorString) : - template.receiveAndConvert(mockQueue)); + (messageSelector ? template.receiveSelectedAndConvert(queue, selectorString) : + template.receiveAndConvert(queue)); } else { - message = (messageSelector ? template.receiveSelected(mockQueue, selectorString) : - template.receive(mockQueue)); + message = (messageSelector ? template.receiveSelected(queue, selectorString) : + template.receive(queue)); } } else { @@ -741,105 +618,107 @@ else if (explicitDestination) { } } - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); - messageConsumerControl.verify(); - messageControl.verify(); - if (testConverter) { assertEquals("Message text should be equal", "Hello World!", textFromMessage); } else { - assertEquals("Messages should refer to the same object", message, mockMessage); + assertEquals("Messages should refer to the same object", message, textMessage); + } + + verify(connection).start(); + verify(connection).close(); + if (useTransactedTemplate()) { + verify(session).commit(); } + verify(session).close(); + if (!useTransactedSession() && clientAcknowledge) { + verify(textMessage).acknowledge(); + } + verify(messageConsumer).close(); } + @Test public void testIllegalStateException() throws Exception { doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class); } + @Test public void testInvalidClientIDException() throws Exception { doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class); } + @Test public void testInvalidDestinationException() throws Exception { doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class); } + @Test public void testInvalidSelectorException() throws Exception { doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class); } + @Test public void testJmsSecurityException() throws Exception { doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class); } + @Test public void testMessageEOFException() throws Exception { doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class); } + @Test public void testMessageFormatException() throws Exception { doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class); } + @Test public void testMessageNotReadableException() throws Exception { doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class); } + @Test public void testMessageNotWriteableException() throws Exception { doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class); } + @Test public void testResourceAllocationException() throws Exception { doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class); } + @Test public void testTransactionInProgressException() throws Exception { doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class); } + @Test public void testTransactionRolledBackException() throws Exception { doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class); } + @Test public void testUncategorizedJmsException() throws Exception { doTestJmsException(new javax.jms.JMSException(""), UncategorizedJmsException.class); } protected void doTestJmsException(JMSException original, Class thrownExceptionClass) throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); - - sessionControl.reset(); - mockSession.createProducer(mockQueue); - sessionControl.setReturnValue(mockMessageProducer); - mockSession.createTextMessage("Hello world"); - sessionControl.setReturnValue(mockMessage); - - mockMessageProducer.send(mockMessage); - messageProducerControl.setThrowable(original, 1); - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); + reset(session); + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("Hello world")).willReturn(textMessage); - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); + willThrow(original).given(messageProducer).send(textMessage); try { - template.convertAndSend(mockQueue, s); + template.convertAndSend(queue, s); fail("Should have thrown JmsException"); } catch (JmsException wrappedEx) { @@ -848,10 +727,9 @@ protected void doTestJmsException(JMSException original, Class thrownExceptionCl assertEquals(original, wrappedEx.getCause()); } - messageProducerControl.verify(); - sessionControl.verify(); - connectionControl.verify(); - connectionFactoryControl.verify(); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,26 +15,26 @@ */ package org.springframework.jms.core.support; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + import java.util.ArrayList; import java.util.List; import javax.jms.ConnectionFactory; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.jms.core.JmsTemplate; /** * @author Mark Pollack * @since 24.9.2004 */ -public class JmsGatewaySupportTests extends TestCase { +public class JmsGatewaySupportTests { + @Test public void testJmsGatewaySupportWithConnectionFactory() throws Exception { - MockControl connectionFactoryControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock(); - connectionFactoryControl.replay(); + ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); final List test = new ArrayList(); JmsGatewaySupport gateway = new JmsGatewaySupport() { @Override @@ -47,9 +47,9 @@ protected void initGateway() { assertEquals("Correct ConnectionFactory", mockConnectionFactory, gateway.getConnectionFactory()); assertEquals("Correct JmsTemplate", mockConnectionFactory, gateway.getJmsTemplate().getConnectionFactory()); assertEquals("initGatway called", test.size(), 1); - connectionFactoryControl.verify(); - } + + @Test public void testJmsGatewaySupportWithJmsTemplate() throws Exception { JmsTemplate template = new JmsTemplate(); final List test = new ArrayList();
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,14 @@ package org.springframework.jms.listener; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.HashSet; @@ -29,12 +36,8 @@ import javax.jms.MessageListener; import javax.jms.Session; -import org.easymock.EasyMock; -import org.easymock.MockControl; -import org.easymock.internal.AlwaysMatcher; import org.junit.Before; import org.junit.Test; - import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.task.TaskExecutor; import org.springframework.jms.StubQueue; @@ -91,38 +94,20 @@ public void testSettingConcurrentConsumersToANegativeValueIsNotAllowed() throws @Test public void testContextRefreshedEventDoesNotStartTheConnectionIfAutoStartIsSetToFalse() throws Exception { - MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class); - MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock(); - messageConsumer.setMessageListener(null); - // anon. inner class passed in, so just expect a call... - mockMessageConsumer.setMatcher(new AlwaysMatcher()); - mockMessageConsumer.setVoidCallable(); - mockMessageConsumer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); - mockConnection.replay(); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -134,49 +119,26 @@ public void testContextRefreshedEventDoesNotStartTheConnectionIfAutoStartIsSetTo context.getBeanFactory().registerSingleton("messageListenerContainer", this.container); context.refresh(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); } @Test public void testContextRefreshedEventStartsTheConnectionByDefault() throws Exception { - MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class); - MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock(); - messageConsumer.setMessageListener(null); - // anon. inner class passed in, so just expect a call... - mockMessageConsumer.setMatcher(new AlwaysMatcher()); - mockMessageConsumer.setVoidCallable(); - mockMessageConsumer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -187,48 +149,31 @@ public void testContextRefreshedEventStartsTheConnectionByDefault() throws Excep context.getBeanFactory().registerSingleton("messageListenerContainer", this.container); context.refresh(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testCorrectSessionExposedForSessionAwareMessageListenerInvocation() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); + final Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(false); - session.getAcknowledgeMode(); - mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + given(session.getTransacted()).willReturn(false); + given(session.getAcknowledgeMode()).willReturn(Session.AUTO_ACKNOWLEDGE); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final HashSet failure = new HashSet(); @@ -250,52 +195,33 @@ public void onMessage(Message message, Session sess) { this.container.afterPropertiesSet(); this.container.start(); - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); messageConsumer.sendMessage(message); if (!failure.isEmpty()) { fail(failure.iterator().next().toString()); } - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testTaskExecutorCorrectlyInvokedWhenSpecified() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - session.getTransacted(); - mockSession.setReturnValue(false); - session.getAcknowledgeMode(); - mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + final Session session = mock(Session.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + given(session.getTransacted()).willReturn(false); + given(session.getAcknowledgeMode()).willReturn(Session.AUTO_ACKNOWLEDGE); + + Connection connection = mock(Connection.class); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); + + final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final TestMessageListener listener = new TestMessageListener(); @@ -314,53 +240,36 @@ public void execute(Runnable task) { this.container.afterPropertiesSet(); this.container.start(); - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); messageConsumer.sendMessage(message); assertTrue(listener.executorInvoked); assertTrue(listener.listenerInvoked); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testRegisteredExceptionListenerIsInvokedOnException() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(false); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + given(session.getTransacted()).willReturn(false); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final JMSException theException = new JMSException(EXCEPTION_MESSAGE); @@ -373,61 +282,44 @@ public void onMessage(Message message, Session session) throws JMSException { } }); - MockControl mockExceptionListener = MockControl.createControl(ExceptionListener.class); - ExceptionListener exceptionListener = (ExceptionListener) mockExceptionListener.getMock(); - exceptionListener.onException(theException); - mockExceptionListener.setVoidCallable(); - mockExceptionListener.replay(); + ExceptionListener exceptionListener = mock(ExceptionListener.class); this.container.setExceptionListener(exceptionListener); this.container.afterPropertiesSet(); this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockExceptionListener.verify(); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(exceptionListener).onException(theException); } @Test public void testRegisteredErrorHandlerIsInvokedOnException() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - Session session = EasyMock.createMock(Session.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - EasyMock.expectLastCall().andReturn(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - EasyMock.expectLastCall().andReturn(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - EasyMock.expectLastCall().andReturn(false); - EasyMock.replay(session); + given(session.getTransacted()).willReturn(false); - Connection connection = EasyMock.createMock(Connection.class); - connection.setExceptionListener(this.container); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - EasyMock.expectLastCall().andReturn(session); - // and the connection is start()ed after the listener is registered... - connection.start(); - EasyMock.replay(connection); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); - ConnectionFactory connectionFactory = EasyMock.createMock(ConnectionFactory.class); - connectionFactory.createConnection(); - EasyMock.expectLastCall().andReturn(connection); - EasyMock.replay(connectionFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final IllegalStateException theException = new IllegalStateException("intentional test failure"); @@ -440,58 +332,42 @@ public void onMessage(Message message, Session session) throws JMSException { } }); - ErrorHandler errorHandler = EasyMock.createMock(ErrorHandler.class); - errorHandler.handleError(theException); - EasyMock.expectLastCall(); - EasyMock.replay(errorHandler); + ErrorHandler errorHandler = mock(ErrorHandler.class); this.container.setErrorHandler(errorHandler); this.container.afterPropertiesSet(); this.container.start(); // manually trigger an Exception with the above bad MessageListener... - Message message = EasyMock.createMock(Message.class); - EasyMock.replay(message); + Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - EasyMock.verify(errorHandler, message, session, connection, connectionFactory); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(errorHandler).handleError(theException); } @Test public void testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_Propagate() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(false); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + given(session.getTransacted()).willReturn(false); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -505,17 +381,13 @@ public void onMessage(Message message) { this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test @@ -524,39 +396,22 @@ public void testTransactedSessionsGetRollbackLogicAppliedAndThatExceptionsStillD final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(true); - // Session is rolled back 'cos it is transacted... - session.rollback(); - mockSession.setVoidCallable(); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + given(session.getTransacted()).willReturn(true); + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -570,65 +425,34 @@ public void onMessage(Message message) { this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + // Session is rolled back 'cos it is transacted... + verify(session).rollback(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testDestroyClosesConsumersSessionsAndConnectionInThatOrder() throws Exception { - MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class); - MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock(); - messageConsumer.setMessageListener(null); - // anon. inner class passed in, so just expect a call... - mockMessageConsumer.setMatcher(new AlwaysMatcher()); - mockMessageConsumer.setVoidCallable(); - // closing down... - messageConsumer.close(); - mockMessageConsumer.setVoidCallable(); - mockMessageConsumer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - // closing down... - session.close(); - mockSession.setVoidCallable(); - mockSession.replay(); - - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - // closing down... - connection.close(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -638,10 +462,11 @@ public void testDestroyClosesConsumersSessionsAndConnectionInThatOrder() throws this.container.start(); this.container.destroy(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(messageConsumer).close(); + verify(session).close(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(connection).close(); }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,13 @@ package org.springframework.jms.listener.adapter; import static org.junit.Assert.*; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import javax.jms.BytesMessage; import javax.jms.InvalidDestinationException; @@ -30,8 +37,9 @@ import javax.jms.TopicPublisher; import javax.jms.TopicSession; -import org.easymock.MockControl; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.SimpleMessageConverter102; /** @@ -40,6 +48,7 @@ * @author Rick Evans * @author Chris Beams */ +@Deprecated public final class MessageListenerAdapter102Tests { private static final String TEXT = "The Runaways"; @@ -50,48 +59,36 @@ public final class MessageListenerAdapter102Tests { @Test public void testWithMessageContentsDelegateForBytesMessage() throws Exception { - MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class); - BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock(); + BytesMessage bytesMessage = mock(BytesMessage.class); // BytesMessage contents must be unwrapped... - bytesMessage.readBytes(null); - mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER); - mockBytesMessage.setReturnValue(TEXT.getBytes().length); - mockBytesMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(TEXT.getBytes()); - mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + byte[] bytes = (byte[]) invocation.getArguments()[0]; + ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); + return inputStream.read(bytes); + } + }); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); adapter.onMessage(bytesMessage); - mockDelegate.verify(); - mockBytesMessage.verify(); + verify(delegate).handleMessage(TEXT.getBytes()); } @Test public void testWithMessageDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageDelegate.class); - MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + TextMessage textMessage = mock(TextMessage.class); + MessageDelegate delegate = mock(MessageDelegate.class); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test @@ -104,69 +101,38 @@ public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter1 @Test public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); + TextMessage textMessage = mock(TextMessage.class); - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setReturnValue(TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(textMessage)).willReturn(TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForQueue() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); + Queue destination = mock(Queue.class); - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); // we want to fall back to the default... - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createSender(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); + + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -177,58 +143,30 @@ protected Object extractMessage(Message message) { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForTopic() throws Exception { - MockControl mockDestination = MockControl.createControl(Topic.class); - Topic destination = (Topic) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Topic destination = mock(Topic.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); // we want to fall back to the default... - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockTopicPublisher = MockControl.createControl(TopicPublisher.class); - TopicPublisher topicPublisher = (TopicPublisher) mockTopicPublisher.getMock(); - topicPublisher.publish(responseTextMessage); - mockTopicPublisher.setVoidCallable(); - topicPublisher.close(); - mockTopicPublisher.setVoidCallable(); - mockTopicPublisher.replay(); - - MockControl mockSession = MockControl.createControl(TopicSession.class); - TopicSession session = (TopicSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createPublisher(destination); - mockSession.setReturnValue(topicPublisher); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); // we want to fall back to the default... + + TextMessage responseTextMessage = mock(TextMessage.class); + TopicPublisher topicPublisher = mock(TopicPublisher.class); + TopicSession session = mock(TopicSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createPublisher(destination)).willReturn(topicPublisher); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -239,58 +177,30 @@ protected Object extractMessage(Message message) { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockTopicPublisher.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(topicPublisher).publish(responseTextMessage); + verify(topicPublisher).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createSender(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -300,44 +210,29 @@ protected Object extractMessage(Message message) { }; adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); + + TextMessage responseTextMessage = mock(TextMessage.class); + + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -350,57 +245,31 @@ protected Object extractMessage(Message message) { fail("expected InvalidDestinationException"); } catch (InvalidDestinationException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setThrowable(new JMSException("Dow!")); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + willThrow(new JMSException("Doe!")).given(queueSender).send(responseTextMessage); // ensure that regardless of a JMSException the producer is closed... - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createSender(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -413,30 +282,20 @@ protected Object extractMessage(Message message) { fail("expected JMSException"); } catch (JMSException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); - mockSentTextMessage.replay(); + final TextMessage sentTextMessage = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setThrowable(new IllegalArgumentException("Dow!")); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + willThrow(new IllegalArgumentException("Doe!")).given(delegate).handleMessage(sentTextMessage); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -448,10 +307,6 @@ protected Object extractMessage(Message message) { adapter.onMessage(sentTextMessage, session); fail("expected ListenerExecutionFailedException"); } catch (ListenerExecutionFailedException ex) { /* expected */ } - - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); } }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,19 @@ package org.springframework.jms.listener.adapter; -import static org.junit.Assert.*; - +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.io.Serializable; import javax.jms.BytesMessage; @@ -33,9 +44,9 @@ import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.MockControl; import org.junit.Test; - +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; @@ -59,161 +70,110 @@ public class MessageListenerAdapterTests { @Test public void testWithMessageContentsDelegateForTextMessage() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(TEXT); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(TEXT); } @Test public void testWithMessageContentsDelegateForBytesMessage() throws Exception { - MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class); - BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock(); + BytesMessage bytesMessage = mock(BytesMessage.class); // BytesMessage contents must be unwrapped... - bytesMessage.getBodyLength(); - mockBytesMessage.setReturnValue(TEXT.getBytes().length); - bytesMessage.readBytes(null); - mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER); - mockBytesMessage.setReturnValue(TEXT.getBytes().length); - mockBytesMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(TEXT.getBytes()); - mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + given(bytesMessage.getBodyLength()).willReturn(new Long(TEXT.getBytes().length)); + given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + byte[] bytes = (byte[]) invocation.getArguments()[0]; + ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); + return inputStream.read(bytes); + } + }); + + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(bytesMessage); - mockDelegate.verify(); - mockBytesMessage.verify(); + verify(delegate).handleMessage(TEXT.getBytes()); } @Test public void testWithMessageContentsDelegateForObjectMessage() throws Exception { - MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class); - ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock(); - objectMessage.getObject(); - mockObjectMessage.setReturnValue(NUMBER); - mockObjectMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(NUMBER); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + ObjectMessage objectMessage = mock(ObjectMessage.class); + given(objectMessage.getObject()).willReturn(NUMBER); + + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(objectMessage); - mockDelegate.verify(); - mockObjectMessage.verify(); + verify(delegate).handleMessage(NUMBER); } @Test public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception { - MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class); - ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock(); - objectMessage.getObject(); - mockObjectMessage.setReturnValue(OBJECT); - mockObjectMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(OBJECT); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + ObjectMessage objectMessage = mock(ObjectMessage.class); + given(objectMessage.getObject()).willReturn(OBJECT); + + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(objectMessage); - mockDelegate.verify(); - mockObjectMessage.verify(); + verify(delegate).handleMessage(OBJECT); } @Test public void testWithMessageDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); + TextMessage textMessage = mock(TextMessage.class); - MockControl mockDelegate = MockControl.createControl(MessageDelegate.class); - MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageDelegate delegate = mock(MessageDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test public void testWhenTheAdapterItselfIsTheDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.onMessage(textMessage); assertTrue(adapter.wasCalled()); - - mockTextMessage.verify(); } @Test public void testRainyDayWithNoApplicableHandlingMethods() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.setDefaultListenerMethod("walnutsRock"); adapter.onMessage(textMessage); assertFalse(adapter.wasCalled()); - - mockTextMessage.verify(); } @Test public void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception { final IllegalArgumentException exception = new IllegalArgumentException(); - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageDelegate.class); - MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setThrowable(exception); - mockDelegate.replay(); + TextMessage textMessage = mock(TextMessage.class); + MessageDelegate delegate = mock(MessageDelegate.class); + willThrow(exception).given(delegate).handleMessage(textMessage); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -230,9 +190,6 @@ protected void handleListenerException(Throwable ex) { // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - - mockDelegate.verify(); - mockTextMessage.verify(); } @Test @@ -257,68 +214,35 @@ public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() th @Test public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setReturnValue(TEXT); - mockDelegate.replay(); + TextMessage textMessage = mock(TextMessage.class); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(textMessage)).willReturn(TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - - mockDelegate.verify(); - mockTextMessage.verify(); } @Test public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn( + CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); // we want to fall back to the default... - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createProducer(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); // we want to fall back to the default... + + TextMessage responseTextMessage = mock(TextMessage.class); + + QueueSender queueSender = mock(QueueSender.class); + Session session = mock(Session.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(queueSender); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -329,59 +253,30 @@ protected Object extractMessage(Message message) { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(null); - sentTextMessage.getJMSMessageID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(null); + given(sentTextMessage.getJMSMessageID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class); - MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock(); - messageProducer.send(responseTextMessage); - mockMessageProducer.setVoidCallable(); - messageProducer.close(); - mockMessageProducer.setVoidCallable(); - mockMessageProducer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createProducer(destination); - mockSession.setReturnValue(messageProducer); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + MessageProducer messageProducer = mock(MessageProducer.class); + Session session = mock(Session.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(messageProducer); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -391,43 +286,26 @@ protected Object extractMessage(Message message) { }; adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockMessageProducer.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(messageProducer).send(responseTextMessage); + verify(messageProducer).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); + + TextMessage responseTextMessage = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -440,56 +318,30 @@ protected Object extractMessage(Message message) { fail("expected InvalidDestinationException"); } catch(InvalidDestinationException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); + Queue destination = mock(Queue.class); - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); - - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class); - MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock(); - messageProducer.send(responseTextMessage); - mockMessageProducer.setThrowable(new JMSException("Dow!")); - // ensure that regardless of a JMSException the producer is closed... - messageProducer.close(); - mockMessageProducer.setVoidCallable(); - mockMessageProducer.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createProducer(destination); - mockSession.setReturnValue(messageProducer); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseTextMessage = mock(TextMessage.class); + MessageProducer messageProducer = mock(MessageProducer.class); + willThrow(new JMSException("Doe!")).given(messageProducer).send(responseTextMessage); + + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(messageProducer); + + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -502,29 +354,18 @@ protected Object extractMessage(Message message) { fail("expected JMSException"); } catch(JMSException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockMessageProducer.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(messageProducer).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception { - MockControl mockMessage = MockControl.createControl(TextMessage.class); - final TextMessage message = (TextMessage) mockMessage.getMock(); - mockMessage.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - mockSession.replay(); + final TextMessage message = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(message); - mockDelegate.setThrowable(new IllegalArgumentException("Dow!")); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + willThrow(new IllegalArgumentException("Doe!")).given(delegate).handleMessage(message); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -536,20 +377,12 @@ protected Object extractMessage(Message message) { adapter.onMessage(message, session); fail("expected ListenerExecutionFailedException"); } catch(ListenerExecutionFailedException ex) { /* expected */ } - - mockDelegate.verify(); - mockMessage.verify(); - mockSession.verify(); } @Test public void testFailsIfNoDefaultListenerMethodNameIsSupplied() throws Exception { - MockControl mockMessage = MockControl.createControl(TextMessage.class); - final TextMessage message = (TextMessage) mockMessage.getMock(); - message.getText(); - mockMessage.setReturnValue(TEXT); - - mockMessage.replay(); + final TextMessage message = mock(TextMessage.class); + given(message.getText()).willReturn(TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter() { @Override @@ -559,18 +392,12 @@ protected void handleListenerException(Throwable ex) { }; adapter.setDefaultListenerMethod(null); adapter.onMessage(message); - - mockMessage.verify(); } @Test public void testFailsWhenOverriddenGetListenerMethodNameReturnsNull() throws Exception { - MockControl mockMessage = MockControl.createControl(TextMessage.class); - final TextMessage message = (TextMessage) mockMessage.getMock(); - message.getText(); - mockMessage.setReturnValue(TEXT); - - mockMessage.replay(); + final TextMessage message = mock(TextMessage.class); + given(message.getText()).willReturn(TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter() { @Override @@ -584,25 +411,14 @@ protected String getListenerMethodName(Message originalMessage, Object extracted }; adapter.setDefaultListenerMethod(null); adapter.onMessage(message); - - mockMessage.verify(); } @Test public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); - mockSentTextMessage.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + final TextMessage sentTextMessage = mock(TextMessage.class); + final Session session = mock(Session.class); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -615,53 +431,25 @@ protected Object extractMessage(Message message) { adapter.onMessage(sentTextMessage, session); fail("expected MessageConversionException"); } catch(MessageConversionException ex) { /* expected */ } - - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); } @Test public void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); - - MockControl mockResponseMessage = MockControl.createControl(TextMessage.class); - TextMessage responseMessage = (TextMessage) mockResponseMessage.getMock(); - responseMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseMessage.setVoidCallable(); - mockResponseMessage.replay(); - - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createProducer(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveJmsTextMessageReturningMessageDelegate.class); - ResponsiveJmsTextMessageReturningMessageDelegate delegate = (ResponsiveJmsTextMessageReturningMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(responseMessage); - mockDelegate.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); + + TextMessage responseMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + + Session session = mock(Session.class); + given(session.createProducer(destination)).willReturn(queueSender); + + ResponsiveJmsTextMessageReturningMessageDelegate delegate = mock(ResponsiveJmsTextMessageReturningMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(responseMessage); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -672,12 +460,9 @@ protected Object extractMessage(Message message) { adapter.setMessageConverter(null); adapter.onMessage(sentTextMessage, session); - mockDestination.verify(); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); - mockQueueSender.verify(); - mockResponseMessage.verify(); + verify(responseMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseMessage); + verify(queueSender).close(); }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java
@@ -16,12 +16,14 @@ package org.springframework.jms.listener.endpoint; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import javax.jms.Destination; import javax.jms.Session; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.jca.StubResourceAdapter; import org.springframework.jms.StubQueue; import org.springframework.jms.support.destination.DestinationResolver; @@ -60,21 +62,17 @@ public void testActiveMQResourceAdapterSetup() { public void testWebSphereResourceAdapterSetup() throws Exception { Destination destination = new StubQueue(); - MockControl control = MockControl.createControl(DestinationResolver.class); - DestinationResolver destinationResolver = (DestinationResolver) control.getMock(); + DestinationResolver destinationResolver = mock(DestinationResolver.class); - destinationResolver.resolveDestinationName(null, "destinationname", false); - control.setReturnValue(destination); - control.replay(); + given(destinationResolver.resolveDestinationName(null, "destinationname", + false)).willReturn(destination); DefaultJmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory(); activationSpecFactory.setDestinationResolver(destinationResolver); StubWebSphereActivationSpecImpl spec = (StubWebSphereActivationSpecImpl) activationSpecFactory .createActivationSpec(new StubWebSphereResourceAdapterImpl(), activationSpecConfig); - control.verify(); - assertEquals(destination, spec.getDestination()); assertEquals(5, spec.getMaxConcurrency()); assertEquals(3, spec.getMaxBatchSize());
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java
@@ -16,9 +16,16 @@ package org.springframework.jms.remoting; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import java.io.Serializable; import java.util.Arrays; import java.util.Enumeration; + import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; @@ -30,71 +37,47 @@ import javax.jms.QueueSession; import javax.jms.Session; -import junit.framework.TestCase; -import org.easymock.MockControl; - -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller */ -public class JmsInvokerTests extends TestCase { +public class JmsInvokerTests { - private MockControl connectionFactoryControl; private QueueConnectionFactory mockConnectionFactory; - private MockControl connectionControl; private QueueConnection mockConnection; - private MockControl sessionControl; private QueueSession mockSession; - private MockControl queueControl; private Queue mockQueue; - @Override - protected void setUp() throws Exception { - connectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class); - mockConnectionFactory = (QueueConnectionFactory) connectionFactoryControl.getMock(); - - connectionControl = MockControl.createControl(QueueConnection.class); - mockConnection = (QueueConnection) connectionControl.getMock(); + @Before + public void setUpMocks() throws Exception { + mockConnectionFactory = mock(QueueConnectionFactory.class); + mockConnection = mock(QueueConnection.class); + mockSession = mock(QueueSession.class); + mockQueue = mock(Queue.class); - sessionControl = MockControl.createControl(QueueSession.class); - mockSession = (QueueSession) sessionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - mockConnectionFactory.createConnection(); - connectionFactoryControl.setReturnValue(mockConnection, 8); - - mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connectionControl.setReturnValue(mockSession, 8); - - mockConnection.start(); - connectionControl.setVoidCallable(8); - - connectionFactoryControl.replay(); - connectionControl.replay(); + given(mockConnectionFactory.createConnection()).willReturn(mockConnection); + given(mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(mockSession); } + @Test public void testJmsInvokerProxyFactoryBeanAndServiceExporter() throws Throwable { - sessionControl.replay(); - doTestJmsInvokerProxyFactoryBeanAndServiceExporter(false); } + @Test public void testJmsInvokerProxyFactoryBeanAndServiceExporterWithDynamicQueue() throws Throwable { - mockSession.createQueue("myQueue"); - sessionControl.setReturnValue(mockQueue, 8); - sessionControl.replay(); - + given(mockSession.createQueue("myQueue")).willReturn(mockQueue); doTestJmsInvokerProxyFactoryBeanAndServiceExporter(true); } @@ -110,14 +93,10 @@ private void doTestJmsInvokerProxyFactoryBeanAndServiceExporter(boolean dynamicQ JmsInvokerProxyFactoryBean pfb = new JmsInvokerProxyFactoryBean() { @Override protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException { - MockControl exporterSessionControl = MockControl.createControl(Session.class); - Session mockExporterSession = (Session) exporterSessionControl.getMock(); + Session mockExporterSession = mock(Session.class); ResponseStoringProducer mockProducer = new ResponseStoringProducer(); - mockExporterSession.createProducer(requestMessage.getJMSReplyTo()); - exporterSessionControl.setReturnValue(mockProducer); - exporterSessionControl.replay(); + given(mockExporterSession.createProducer(requestMessage.getJMSReplyTo())).willReturn(mockProducer); exporter.onMessage(requestMessage, mockExporterSession); - exporterSessionControl.verify(); assertTrue(mockProducer.closed); return mockProducer.response; } @@ -156,10 +135,6 @@ protected Message doExecuteRequest(Session session, Queue queue, Message request catch (IllegalAccessException ex) { // expected } - - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,63 +16,53 @@ package org.springframework.jms.support; -import junit.framework.TestCase; -import org.easymock.ArgumentsMatcher; -import org.easymock.MockControl; -import org.springframework.jms.support.converter.SimpleMessageConverter102; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; + +import java.io.ByteArrayInputStream; +import java.util.Random; import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; -import java.util.Arrays; + +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.springframework.jms.support.converter.SimpleMessageConverter102; /** * Unit tests for the {@link SimpleMessageConverter102} class. * * @author Juergen Hoeller * @author Rick Evans */ -public final class SimpleMessageConverter102Tests extends TestCase { +public final class SimpleMessageConverter102Tests { + @Test public void testByteArrayConversion102() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(BytesMessage.class); - BytesMessage message = (BytesMessage) messageControl.getMock(); + Session session = mock(Session.class); + BytesMessage message = mock(BytesMessage.class); byte[] content = new byte[5000]; + new Random().nextBytes(content); - session.createBytesMessage(); - sessionControl.setReturnValue(message, 1); - message.writeBytes(content); - messageControl.setVoidCallable(1); - message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]); - messageControl.setMatcher(new ArgumentsMatcher() { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); + given(session.createBytesMessage()).willReturn(message); + given(message.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() { @Override - public boolean matches(Object[] arg0, Object[] arg1) { - byte[] one = (byte[]) arg0[0]; - byte[] two = (byte[]) arg1[0]; - return Arrays.equals(one, two); - } - - @Override - public String toString(Object[] arg0) { - return "bla"; + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteArrayInputStream.read((byte[])invocation.getArguments()[0]); } }); - messageControl.setReturnValue(SimpleMessageConverter102.BUFFER_SIZE, 1); - message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]); - messageControl.setReturnValue(5000 - SimpleMessageConverter102.BUFFER_SIZE, 1); - sessionControl.replay(); - messageControl.replay(); SimpleMessageConverter102 converter = new SimpleMessageConverter102(); Message msg = converter.toMessage(content, session); - assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length); - - sessionControl.verify(); - messageControl.verify(); + assertThat((byte[])converter.fromMessage(msg), equalTo(content)); } }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,15 @@ package org.springframework.jms.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -import java.util.Arrays; +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -31,9 +37,9 @@ import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.ArgumentsMatcher; -import org.easymock.MockControl; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; @@ -48,127 +54,79 @@ public final class SimpleMessageConverterTests { @Test public void testStringConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage message = (TextMessage) messageControl.getMock(); + Session session = mock(Session.class); + TextMessage message = mock(TextMessage.class); String content = "test"; - session.createTextMessage(content); - sessionControl.setReturnValue(message, 1); - message.getText(); - messageControl.setReturnValue(content, 1); - sessionControl.replay(); - messageControl.replay(); + given(session.createTextMessage(content)).willReturn(message); + given(message.getText()).willReturn(content); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - - sessionControl.verify(); - messageControl.verify(); } @Test public void testByteArrayConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(BytesMessage.class); - BytesMessage message = (BytesMessage) messageControl.getMock(); + Session session = mock(Session.class); + BytesMessage message = mock(BytesMessage.class); byte[] content = "test".getBytes(); + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); - session.createBytesMessage(); - sessionControl.setReturnValue(message, 1); - message.writeBytes(content); - messageControl.setVoidCallable(1); - message.getBodyLength(); - messageControl.setReturnValue(content.length, 1); - message.readBytes(new byte[content.length]); - messageControl.setMatcher(new ArgumentsMatcher() { - @Override - public boolean matches(Object[] arg0, Object[] arg1) { - byte[] one = (byte[]) arg0[0]; - byte[] two = (byte[]) arg1[0]; - return Arrays.equals(one, two); - } - + given(session.createBytesMessage()).willReturn(message); + given(message.getBodyLength()).willReturn((long) content.length); + given(message.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() { @Override - public String toString(Object[] arg0) { - return "bla"; + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteArrayInputStream.read((byte[]) invocation.getArguments()[0]); } }); - messageControl.setReturnValue(content.length, 1); - sessionControl.replay(); - messageControl.replay(); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length); - sessionControl.verify(); - messageControl.verify(); + verify(message).writeBytes(content); } @Test public void testMapConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(MapMessage.class); - MapMessage message = (MapMessage) messageControl.getMock(); + Session session = mock(Session.class); + MapMessage message = mock(MapMessage.class); Map content = new HashMap(); content.put("key1", "value1"); content.put("key2", "value2"); - session.createMapMessage(); - sessionControl.setReturnValue(message, 1); - message.setObject("key1", "value1"); - messageControl.setVoidCallable(1); - message.setObject("key2", "value2"); - messageControl.setVoidCallable(1); - message.getMapNames(); - messageControl.setReturnValue(Collections.enumeration(content.keySet())); - message.getObject("key1"); - messageControl.setReturnValue("value1", 1); - message.getObject("key2"); - messageControl.setReturnValue("value2", 1); - - sessionControl.replay(); - messageControl.replay(); + given(session.createMapMessage()).willReturn(message); + given(message.getMapNames()).willReturn(Collections.enumeration(content.keySet())); + given(message.getObject("key1")).willReturn("value1"); + given(message.getObject("key2")).willReturn("value2"); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - sessionControl.verify(); - messageControl.verify(); + verify(message).setObject("key1", "value1"); + verify(message).setObject("key2", "value2"); } @Test public void testSerializableConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(ObjectMessage.class); - ObjectMessage message = (ObjectMessage) messageControl.getMock(); + Session session = mock(Session.class); + ObjectMessage message = mock(ObjectMessage.class); Integer content = new Integer(5); - session.createObjectMessage(content); - sessionControl.setReturnValue(message, 1); - message.getObject(); - messageControl.setReturnValue(content, 1); - sessionControl.replay(); - messageControl.replay(); + given(session.createObjectMessage(content)).willReturn(message); + given(message.getObject()).willReturn(content); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - - sessionControl.verify(); - messageControl.verify(); } @Test(expected=MessageConversionException.class) @@ -184,50 +142,30 @@ public void testToMessageThrowsExceptionIfGivenIncompatibleObjectToConvert() thr @Test public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - - MockControl messageControl = MockControl.createControl(ObjectMessage.class); - ObjectMessage message = (ObjectMessage) messageControl.getMock(); - - sessionControl.replay(); - messageControl.replay(); + Session session = mock(Session.class); + ObjectMessage message = mock(ObjectMessage.class); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(message, session); assertSame(message, msg); - - sessionControl.verify(); - messageControl.verify(); } @Test public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException { - MockControl messageControl = MockControl.createControl(Message.class); - Message message = (Message) messageControl.getMock(); - - messageControl.replay(); + Message message = mock(Message.class); SimpleMessageConverter converter = new SimpleMessageConverter(); Object msg = converter.fromMessage(message); assertSame(message, msg); - - messageControl.verify(); } @Test public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException { - MockControl messageControl = MockControl.createControl(MapMessage.class); - MapMessage message = (MapMessage) messageControl.getMock(); - messageControl.replay(); - - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - session.createMapMessage(); - sessionControl.setReturnValue(message); - sessionControl.replay(); + MapMessage message = mock(MapMessage.class); + final Session session = mock(Session.class); + given(session.createMapMessage()).willReturn(message); final Map content = new HashMap(); content.put(new Integer(1), "value1"); @@ -237,22 +175,14 @@ public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSExcept converter.toMessage(content, session); fail("expected MessageConversionException"); } catch (MessageConversionException ex) { /* expected */ } - - sessionControl.verify(); } @Test public void testMapConversionWhereMapHasNNullForKey() throws JMSException { - MockControl messageControl = MockControl.createControl(MapMessage.class); - MapMessage message = (MapMessage) messageControl.getMock(); - messageControl.replay(); - - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - session.createMapMessage(); - sessionControl.setReturnValue(message); - sessionControl.replay(); + MapMessage message = mock(MapMessage.class); + final Session session = mock(Session.class); + given(session.createMapMessage()).willReturn(message); final Map content = new HashMap(); content.put(null, "value1"); @@ -262,8 +192,6 @@ public void testMapConversionWhereMapHasNNullForKey() throws JMSException { converter.toMessage(content, session); fail("expected MessageConversionException"); } catch (MessageConversionException ex) { /* expected */ } - - sessionControl.verify(); } }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,27 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.Capture; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; /** * @author Arjen Poutsma @@ -44,136 +50,102 @@ public class MappingJackson2MessageConverterTests { @Before public void setUp() throws Exception { - sessionMock = createMock(Session.class); + sessionMock = mock(Session.class); converter = new MappingJackson2MessageConverter(); converter.setEncodingPropertyName("__encoding__"); converter.setTypeIdPropertyName("__typeid__"); } @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Date toBeMarshalled = new Date(); - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - bytesMessageMock.setStringProperty("__encoding__", "UTF-8"); - bytesMessageMock.setStringProperty("__typeid__", Date.class.getName()); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, bytesMessageMock); + verify(bytesMessageMock).setStringProperty("__encoding__", "UTF-8"); + verify(bytesMessageMock).setStringProperty("__typeid__", Date.class.getName()); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); - Map<String, String> unmarshalled = Collections.singletonMap("foo", - "bar"); - - final byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); - @SuppressWarnings("serial") - Capture<byte[]> captured = new Capture<byte[]>() { - @Override - public void setValue(byte[] value) { - super.setValue(value); - System.arraycopy(bytes, 0, value, 0, bytes.length); - } - }; - - expect( - bytesMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect( - bytesMessageMock.propertyExists("__encoding__")) - .andReturn(false); - expect(bytesMessageMock.getBodyLength()).andReturn( - new Long(bytes.length)); - expect(bytesMessageMock.readBytes(EasyMock.capture(captured))) - .andReturn(bytes.length); - - replay(sessionMock, bytesMessageMock); + BytesMessage bytesMessageMock = mock(BytesMessage.class); + Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); + + byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); + final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); + + given(bytesMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); + given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length)); + given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( + new Answer<Integer>() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteStream.read((byte[]) invocation.getArguments()[0]); + } + }); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, bytesMessageMock); } @Test public void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Date toBeMarshalled = new Date(); - textMessageMock.setStringProperty("__typeid__", Date.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( textMessageMock); - - replay(sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn( + textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", Date.class.getName()); } @Test public void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Map<String, String> toBeMarshalled = new HashMap<String, String>(); toBeMarshalled.put("foo", "bar"); - textMessageMock.setStringProperty("__typeid__", HashMap.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( + given(sessionMock.createTextMessage(isA(String.class))).willReturn( textMessageMock); - replay(sessionMock, textMessageMock); - converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", HashMap.class.getName()); } @Test public void fromTextMessageAsObject() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map<String, String> unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } @Test public void fromTextMessageAsMap() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map<String, String> unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(HashMap.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + HashMap.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } - }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,26 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.Capture; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; /** * @author Arjen Poutsma @@ -43,136 +49,104 @@ public class MappingJacksonMessageConverterTests { @Before public void setUp() throws Exception { - sessionMock = createMock(Session.class); + sessionMock = mock(Session.class); converter = new MappingJacksonMessageConverter(); converter.setEncodingPropertyName("__encoding__"); converter.setTypeIdPropertyName("__typeid__"); } @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object toBeMarshalled = new Object(); - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - bytesMessageMock.setStringProperty("__encoding__", "UTF-8"); - bytesMessageMock.setStringProperty("__typeid__", Object.class.getName()); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, bytesMessageMock); + verify(bytesMessageMock).setStringProperty("__encoding__", "UTF-8"); + verify(bytesMessageMock).setStringProperty("__typeid__", Object.class.getName()); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test @SuppressWarnings("serial") public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); - Map<String, String> unmarshalled = Collections.singletonMap("foo", - "bar"); - - final byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); - Capture<byte[]> captured = new Capture<byte[]>() { - @Override - public void setValue(byte[] value) { - super.setValue(value); - System.arraycopy(bytes, 0, value, 0, bytes.length); - } - }; - - expect( - bytesMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect( - bytesMessageMock.propertyExists("__encoding__")) - .andReturn(false); - expect(bytesMessageMock.getBodyLength()).andReturn( - new Long(bytes.length)); - expect(bytesMessageMock.readBytes(EasyMock.capture(captured))) - .andReturn(bytes.length); - - replay(sessionMock, bytesMessageMock); + BytesMessage bytesMessageMock = mock(BytesMessage.class); + Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); + + byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); + final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); + + given(bytesMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); + given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length)); + given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( + new Answer<Integer>() { + + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteStream.read((byte[]) invocation.getArguments()[0]); + } + }); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, bytesMessageMock); } @Test public void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object toBeMarshalled = new Object(); - textMessageMock.setStringProperty("__typeid__", Object.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( textMessageMock); - - replay(sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn( + textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", Object.class.getName()); } @Test public void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Map<String, String> toBeMarshalled = new HashMap<String, String>(); toBeMarshalled.put("foo", "bar"); - - textMessageMock.setStringProperty("__typeid__", HashMap.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( + given(sessionMock.createTextMessage(isA(String.class))).willReturn( textMessageMock); - replay(sessionMock, textMessageMock); - converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", HashMap.class.getName()); } @Test public void fromTextMessageAsObject() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map<String, String> unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } @Test public void fromTextMessageAsMap() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map<String, String> unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map<String, String> unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(HashMap.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + HashMap.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } - }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,21 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; import javax.xml.transform.Result; import javax.xml.transform.Source; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; - import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; @@ -45,76 +49,60 @@ public class MarshallingMessageConverterTests { @Before public void setUp() throws Exception { - marshallerMock = createMock(Marshaller.class); - unmarshallerMock = createMock(Unmarshaller.class); - sessionMock = createMock(Session.class); + marshallerMock = mock(Marshaller.class); + unmarshallerMock = mock(Unmarshaller.class); + sessionMock = mock(Session.class); converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock); } @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object toBeMarshalled = new Object(); - - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class)); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object unmarshalled = new Object(); - expect(bytesMessageMock.getBodyLength()).andReturn(10L); - expect(bytesMessageMock.readBytes(isA(byte[].class))).andReturn(0); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); - - replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + given(bytesMessageMock.getBodyLength()).willReturn(10L); + given(bytesMessageMock.readBytes(isA(byte[].class))).willReturn(0); + given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); } @Test public void toTextMessage() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object toBeMarshalled = new Object(); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn(textMessageMock); - marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class)); - - replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); } @Test public void fromTextMessage() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object unmarshalled = new Object(); String text = "foo"; - expect(textMessageMock.getText()).andReturn(text); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); - - replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + given(textMessageMock.getText()).willReturn(text); + given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); } - }
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ package org.springframework.jms.support.destination; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Queue; @@ -25,7 +28,6 @@ import javax.jms.TopicSession; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.jms.StubQueue; import org.springframework.jms.StubTopic; @@ -39,63 +41,31 @@ public class DynamicDestinationResolverTests extends TestCase { public void testResolveWithPubSubTopicSession() throws Exception { - Topic expectedDestination = new StubTopic(); - - MockControl mockSession = MockControl.createControl(TopicSession.class); - TopicSession session = (TopicSession) mockSession.getMock(); - session.createTopic(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + TopicSession session = mock(TopicSession.class); + given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, true); - - mockSession.verify(); } public void testResolveWithPubSubVanillaSession() throws Exception { - Topic expectedDestination = new StubTopic(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createTopic(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + Session session = mock(Session.class); + given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, true); - - mockSession.verify(); } public void testResolveWithPointToPointQueueSession() throws Exception { - Queue expectedDestination = new StubQueue(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - Session session = (Session) mockSession.getMock(); - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + Session session = mock(QueueSession.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, false); - - mockSession.verify(); } public void testResolveWithPointToPointVanillaSession() throws Exception { - Queue expectedDestination = new StubQueue(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + Session session = mock(Session.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, false); - - mockSession.verify(); } private static void testResolveDestination(Session session, Destination expectedDestination, boolean isPubSub) throws JMSException {
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,9 @@ package org.springframework.jms.support.destination; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; import javax.jms.ConnectionFactory; @@ -31,18 +32,19 @@ public class JmsDestinationAccessorTests { @Test public void testChokesIfDestinationResolverIsetToNullExplcitly() throws Exception { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - replay(connectionFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); try { JmsDestinationAccessor accessor = new StubJmsDestinationAccessor(); accessor.setConnectionFactory(connectionFactory); accessor.setDestinationResolver(null); accessor.afterPropertiesSet(); fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException ex) { /* expected */ } + } + catch (IllegalArgumentException ex) { + // expected + } - verify(connectionFactory); } @Test
true
Other
spring-projects
spring-framework
2642cf2e05e7851acf4727c09b7c0d5dc71dcde4.json
Replace EasyMock with Mockito in spring-jms Issue: SPR-10126
spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,17 @@ package org.springframework.jms.support.destination; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; import javax.jms.Destination; import javax.jms.Session; import javax.naming.NamingException; -import org.easymock.MockControl; import org.junit.Test; import org.springframework.jms.StubTopic; @@ -40,24 +44,18 @@ public class JndiDestinationResolverTests { @Test public void testHitsCacheSecondTimeThrough() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); JndiDestinationResolver resolver = new OneTimeLookupJndiDestinationResolver(); Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true); assertNotNull(destination); assertSame(DESTINATION, destination); - - mockSession.verify(); } @Test public void testDoesNotUseCacheIfCachingIsTurnedOff() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); CountingCannedJndiDestinationResolver resolver = new CountingCannedJndiDestinationResolver(); @@ -71,21 +69,15 @@ public void testDoesNotUseCacheIfCachingIsTurnedOff() throws Exception { assertNotNull(destination); assertSame(DESTINATION, destination); assertEquals(2, resolver.getCallCount()); - - mockSession.verify(); } @Test public void testDelegatesToFallbackIfNotResolvedInJndi() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); - MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class); - DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock(); - dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, true); - mockDestinationResolver.setReturnValue(DESTINATION); - mockDestinationResolver.replay(); + DestinationResolver dynamicResolver = mock(DestinationResolver.class); + given(dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, + true)).willReturn(DESTINATION); JndiDestinationResolver resolver = new JndiDestinationResolver() { @Override @@ -99,20 +91,12 @@ protected Object lookup(String jndiName, Class requiredClass) throws NamingExcep assertNotNull(destination); assertSame(DESTINATION, destination); - - mockSession.verify(); - mockDestinationResolver.verify(); } @Test public void testDoesNotDelegateToFallbackIfNotResolvedInJndi() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); - mockSession.replay(); - - MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class); - DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock(); - mockDestinationResolver.replay(); + final Session session = mock(Session.class); + DestinationResolver dynamicResolver = mock(DestinationResolver.class); final JndiDestinationResolver resolver = new JndiDestinationResolver() { @Override @@ -125,10 +109,10 @@ protected Object lookup(String jndiName, Class requiredClass) throws NamingExcep try { resolver.resolveDestinationName(session, DESTINATION_NAME, true); fail("expected DestinationResolutionException"); - } catch (DestinationResolutionException ex) { /* expected */ } - - mockSession.verify(); - mockDestinationResolver.verify(); + } + catch (DestinationResolutionException ex) { + // expected + } }
true
Other
spring-projects
spring-framework
5710cf5ed29139e94853f3d14124eb100a924b82.json
Reduce log level to DEBUG when @TELs isn't present The default set of TestExecutionListeners is sufficient in most integration testing scenarios; however, the TestContextManager nonetheless logs an INFO message if the @TestExecutionListeners annotation is not present on an integration test class. In order to avoid flooding the logs with messages about the absence of @TestExecutionListeners, this commit reduces the log level for such messages from INFO to DEBUG. Issue: SPR-8645
spring-test/src/main/java/org/springframework/test/context/TestContextManager.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * 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. @@ -181,8 +181,8 @@ private TestExecutionListener[] retrieveTestExecutionListeners(Class<?> clazz) { // Use defaults? if (declaringClass == null) { - if (logger.isInfoEnabled()) { - logger.info("@TestExecutionListeners is not present for class [" + clazz + "]: using defaults."); + if (logger.isDebugEnabled()) { + logger.debug("@TestExecutionListeners is not present for class [" + clazz + "]: using defaults."); } classesList.addAll(getDefaultTestExecutionListenerClasses()); defaultListeners = true;
false
Other
spring-projects
spring-framework
69a392981e135a1c78ed18b9495626e7b34349e4.json
Upgrade JarJar to version 1.3 JarJar 1.3 now uses ASM 4 in order to be compatible with Java 7 'invokedynamic' instructions. This is not an immediate concern for the classes that we use JarJar to repackage and transform, but is a timely upgrade in anticipation of the subsequent commits in which we upgrade Spring's own dependency on ASM from 2.2.3 to 4.0 and Spring's dependency on CGLIB from 2.2 to 3.0 (which in turn depends on ASM 4.0). See https://code.google.com/p/jarjar/wiki/ChangeLog Issue: SPR-9669
build.gradle
@@ -98,7 +98,7 @@ project("spring-asm") { } dependencies { asm "asm:asm:${asmVersion}@jar", "asm:asm-commons:${asmVersion}@jar" - jarjar 'com.googlecode.jarjar:jarjar:1.1' + jarjar 'com.googlecode.jarjar:jarjar:1.3' } task repackageAsm(type: Jar) { jar ->
false
Other
spring-projects
spring-framework
f5d3cd07e733f9b21749a96603de14f65a0add3d.json
Avoid NPE when registering a SpEL MethodFilter Attempting to register a custom MethodFilter with a StandardEvaluationContext after invoking setMethodResolvers() with a custom list of MethodResolver instances results in a NullPointerException. Based on the current documentation in StandardEvaluationContext it is unclear what the expected behavior should be, but either the implementation is broken, or the use case is unsupported. In either case, allowing a NullPointerException to be thrown is inappropriate. This commit documents the fact that the SpEL MethodFilter is intended to be used with the ReflectiveMethodResolver. Furthermore, StandardEvaluationContext.registerMethodFilter() now throws an IllegalStateException if the user attempts to set a filter after having registered a custom set of resolvers. Issue: SPR-9621
spring-expression/src/main/java/org/springframework/expression/spel/support/StandardEvaluationContext.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -43,6 +43,7 @@ * * @author Andy Clement * @author Juergen Hoeller + * @author Sam Brannen * @since 3.0 */ public class StandardEvaluationContext implements EvaluationContext { @@ -218,16 +219,23 @@ public Object lookupVariable(String name) { } /** - * Register a MethodFilter which will be called during method resolution for the - * specified type. The MethodFilter may remove methods and/or sort the methods - * which will then be used by SpEL as the candidates to look through for a match. - * + * Register a {@code MethodFilter} which will be called during method resolution + * for the specified type. + * + * <p>The {@code MethodFilter} may remove methods and/or sort the methods which + * will then be used by SpEL as the candidates to look through for a match. + * * @param type the type for which the filter should be called - * @param filter a MethodFilter, or NULL to deregister a filter for the type + * @param filter a {@code MethodFilter}, or {@code null} to unregister a filter for the type + * @throws IllegalStateException if the {@link ReflectiveMethodResolver} is not in use */ - public void registerMethodFilter(Class<?> type, MethodFilter filter) { + public void registerMethodFilter(Class<?> type, MethodFilter filter) throws IllegalStateException { ensureMethodResolversInitialized(); - reflectiveMethodResolver.registerMethodFilter(type,filter); + if (reflectiveMethodResolver != null) { + reflectiveMethodResolver.registerMethodFilter(type, filter); + } else { + throw new IllegalStateException("Method filter cannot be set as the reflective method resolver is not in use"); + } } private void ensurePropertyAccessorsInitialized() {
true
Other
spring-projects
spring-framework
f5d3cd07e733f9b21749a96603de14f65a0add3d.json
Avoid NPE when registering a SpEL MethodFilter Attempting to register a custom MethodFilter with a StandardEvaluationContext after invoking setMethodResolvers() with a custom list of MethodResolver instances results in a NullPointerException. Based on the current documentation in StandardEvaluationContext it is unclear what the expected behavior should be, but either the implementation is broken, or the use case is unsupported. In either case, allowing a NullPointerException to be thrown is inappropriate. This commit documents the fact that the SpEL MethodFilter is intended to be used with the ReflectiveMethodResolver. Furthermore, StandardEvaluationContext.registerMethodFilter() now throws an IllegalStateException if the user attempts to set a filter after having registered a custom set of resolvers. Issue: SPR-9621
spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
@@ -18,15 +18,22 @@ import static org.junit.Assert.*; +import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.expression.AccessException; import org.springframework.expression.EvaluationContext; import org.springframework.expression.EvaluationException; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; +import org.springframework.expression.MethodExecutor; +import org.springframework.expression.MethodFilter; +import org.springframework.expression.MethodResolver; import org.springframework.expression.ParseException; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; @@ -98,8 +105,8 @@ public void testCreateObjectsOnAttemptToReferenceNull() throws Exception { } + @SuppressWarnings("rawtypes") static class TestClass { - public Foo wibble; private Foo wibble2; public Map map; @@ -571,4 +578,48 @@ public void caseInsensitiveNullLiterals() { assertNull(exp.getValue()); } + /** + * Verifies behavior requested in SPR-9621. + */ + @Test + public void customMethodFilter() throws Exception { + StandardEvaluationContext context = new StandardEvaluationContext(); + + // Register a custom MethodResolver... + List<MethodResolver> customResolvers = new ArrayList<MethodResolver>(); + customResolvers.add(new CustomMethodResolver()); + context.setMethodResolvers(customResolvers); + + // or simply... + // context.setMethodResolvers(new ArrayList<MethodResolver>()); + + // Register a custom MethodFilter... + MethodFilter filter = new CustomMethodFilter(); + try { + context.registerMethodFilter(String.class, filter); + fail("should have failed"); + } catch (IllegalStateException ise) { + assertEquals( + "Method filter cannot be set as the reflective method resolver is not in use", + ise.getMessage()); + } + } + + static class CustomMethodResolver implements MethodResolver { + + public MethodExecutor resolve(EvaluationContext context, + Object targetObject, String name, + List<TypeDescriptor> argumentTypes) throws AccessException { + return null; + } + } + + static class CustomMethodFilter implements MethodFilter { + + public List<Method> filter(List<Method> methods) { + return null; + } + + } + }
true
Other
spring-projects
spring-framework
f5d3cd07e733f9b21749a96603de14f65a0add3d.json
Avoid NPE when registering a SpEL MethodFilter Attempting to register a custom MethodFilter with a StandardEvaluationContext after invoking setMethodResolvers() with a custom list of MethodResolver instances results in a NullPointerException. Based on the current documentation in StandardEvaluationContext it is unclear what the expected behavior should be, but either the implementation is broken, or the use case is unsupported. In either case, allowing a NullPointerException to be thrown is inappropriate. This commit documents the fact that the SpEL MethodFilter is intended to be used with the ReflectiveMethodResolver. Furthermore, StandardEvaluationContext.registerMethodFilter() now throws an IllegalStateException if the user attempts to set a filter after having registered a custom set of resolvers. Issue: SPR-9621
src/dist/changelog.txt
@@ -9,9 +9,10 @@ Changes in version 3.2 M2 (2012-08-xx) * spring-test module now depends on junit:junit-dep (SPR-6966) * now inferring return type of generic factory methods (SPR-9493) * SpEL now supports method invocations on integers (SPR-9612) +* SpEL now supports case-insensitive null literals in expressions (SPR-9613) * SpEL now supports symbolic boolean operators for OR and AND (SPR-9614) * SpEL now supports nested double quotes in expressions (SPR-9620) -* introduced support for case-insensitive null literals in SpEL expressions (SPR-9613) +* SpEL now throws an ISE if a MethodFilter is registered against custom resolvers (SPR-9621) * now using BufferedInputStream in SimpleMetaDataReader to double performance (SPR-9528) * introduced "repeatCount" property in Quartz SimpleTriggerFactoryBean (SPR-9521) * introduced "jtaTransactionManager" property in Hibernate 4 LocalSessionFactoryBean/Builder (SPR-9480)
true
Other
spring-projects
spring-framework
015086cb9c50fa4eabd47fab064bc1bbdde8caa6.json
Introduce new methods in tx base test classes Recently new utility methods were added to JdbcTestUtils, and a JdbcTemplate was introduced in abstract transactional base classes in the TestContext framework. This presents an easy opportunity to make these new utility methods available as convenience methods in the base test classes. This commit introduces new countRowsInTableWhere() and dropTables() convenience methods in the abstract transactional base classes in the TestContext framework. These new methods internally delegate to methods of the same names in JdbcTestUtils. Issue: SPR-9665
spring-test/src/main/java/org/springframework/test/context/junit4/AbstractTransactionalJUnit4SpringContextTests.java
@@ -33,17 +33,18 @@ import org.springframework.transaction.annotation.Transactional; /** - * Abstract {@link Transactional transactional} extension of + * Abstract {@linkplain Transactional transactional} extension of * {@link AbstractJUnit4SpringContextTests} which adds convenience functionality * for JDBC access. Expects a {@link DataSource} bean and a * {@link PlatformTransactionManager} bean to be defined in the Spring - * {@link ApplicationContext application context}. + * {@linkplain ApplicationContext application context}. * - * <p>This class exposes a {@link JdbcTemplate} and provides an easy way - * to {@link #countRowsInTable(String) count the number of rows in a table}, - * {@link #deleteFromTables(String...) delete from tables}, and - * {@link #executeSqlScript(String, boolean) execute SQL scripts} within a - * transaction. + * <p>This class exposes a {@link JdbcTemplate} and provides an easy way to + * {@linkplain #countRowsInTable count the number of rows in a table} + * (potentially {@linkplain #countRowsInTableWhere with a WHERE clause}), + * {@linkplain #deleteFromTables delete from tables}, + * {@linkplain #dropTables drop tables}, and + * {@linkplain #executeSqlScript execute SQL scripts} within a transaction. * * <p>Concrete subclasses must fulfill the same requirements outlined in * {@link AbstractJUnit4SpringContextTests}. @@ -86,6 +87,7 @@ public abstract class AbstractTransactionalJUnit4SpringContextTests extends Abst /** * The {@code JdbcTemplate} that this base class manages, available to subclasses. + * @since 3.2 */ protected JdbcTemplate jdbcTemplate; @@ -120,6 +122,19 @@ protected int countRowsInTable(String tableName) { return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName); } + /** + * Count the rows in the given table, using the provided {@code WHERE} clause. + * <p>See the Javadoc for {@link JdbcTestUtils#countRowsInTableWhere()} for details. + * @param tableName the name of the table to count rows in + * @param whereClause the {@code WHERE} clause to append to the query + * @return the number of rows in the table that match the provided + * {@code WHERE} clause + * @since 3.2 + */ + protected int countRowsInTableWhere(String tableName, String whereClause) { + return JdbcTestUtils.countRowsInTableWhere(this.jdbcTemplate, tableName, whereClause); + } + /** * Convenience method for deleting all rows from the specified tables. Use * with caution outside of a transaction! @@ -130,6 +145,16 @@ protected int deleteFromTables(String... names) { return JdbcTestUtils.deleteFromTables(this.jdbcTemplate, names); } + /** + * Convenience method for dropping all of the specified tables. Use + * with caution outside of a transaction! + * @param names the names of the tables to drop + * @since 3.2 + */ + protected void dropTables(String... names) { + JdbcTestUtils.dropTables(this.jdbcTemplate, names); + } + /** * Execute the given SQL script. Use with caution outside of a transaction! * <p>The script will normally be loaded by classpath. There should be one
true
Other
spring-projects
spring-framework
015086cb9c50fa4eabd47fab064bc1bbdde8caa6.json
Introduce new methods in tx base test classes Recently new utility methods were added to JdbcTestUtils, and a JdbcTemplate was introduced in abstract transactional base classes in the TestContext framework. This presents an easy opportunity to make these new utility methods available as convenience methods in the base test classes. This commit introduces new countRowsInTableWhere() and dropTables() convenience methods in the abstract transactional base classes in the TestContext framework. These new methods internally delegate to methods of the same names in JdbcTestUtils. Issue: SPR-9665
spring-test/src/main/java/org/springframework/test/context/testng/AbstractTransactionalTestNGSpringContextTests.java
@@ -32,17 +32,18 @@ import org.springframework.transaction.annotation.Transactional; /** - * Abstract {@link Transactional transactional} extension of + * Abstract {@linkplain Transactional transactional} extension of * {@link AbstractTestNGSpringContextTests} which adds convenience functionality * for JDBC access. Expects a {@link DataSource} bean and a * {@link PlatformTransactionManager} bean to be defined in the Spring - * {@link ApplicationContext application context}. + * {@linkplain ApplicationContext application context}. * - * <p>This class exposes a {@link JdbcTemplate} and provides an easy way - * to {@link #countRowsInTable(String) count the number of rows in a table}, - * {@link #deleteFromTables(String...) delete from tables}, and - * {@link #executeSqlScript(String, boolean) execute SQL scripts} within a - * transaction. + * <p>This class exposes a {@link JdbcTemplate} and provides an easy way to + * {@linkplain #countRowsInTable count the number of rows in a table} + * (potentially {@linkplain #countRowsInTableWhere with a WHERE clause}), + * {@linkplain #deleteFromTables delete from tables}, + * {@linkplain #dropTables drop tables}, and + * {@linkplain #executeSqlScript execute SQL scripts} within a transaction. * * <p>Concrete subclasses must fulfill the same requirements outlined in * {@link AbstractTestNGSpringContextTests}. @@ -77,6 +78,7 @@ public abstract class AbstractTransactionalTestNGSpringContextTests extends Abst /** * The {@code JdbcTemplate} that this base class manages, available to subclasses. + * @since 3.2 */ protected JdbcTemplate jdbcTemplate; @@ -111,6 +113,19 @@ protected int countRowsInTable(String tableName) { return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName); } + /** + * Count the rows in the given table, using the provided {@code WHERE} clause. + * <p>See the Javadoc for {@link JdbcTestUtils#countRowsInTableWhere()} for details. + * @param tableName the name of the table to count rows in + * @param whereClause the {@code WHERE} clause to append to the query + * @return the number of rows in the table that match the provided + * {@code WHERE} clause + * @since 3.2 + */ + protected int countRowsInTableWhere(String tableName, String whereClause) { + return JdbcTestUtils.countRowsInTableWhere(this.jdbcTemplate, tableName, whereClause); + } + /** * Convenience method for deleting all rows from the specified tables. Use * with caution outside of a transaction! @@ -121,6 +136,16 @@ protected int deleteFromTables(String... names) { return JdbcTestUtils.deleteFromTables(this.jdbcTemplate, names); } + /** + * Convenience method for dropping all of the specified tables. Use + * with caution outside of a transaction! + * @param names the names of the tables to drop + * @since 3.2 + */ + protected void dropTables(String... names) { + JdbcTestUtils.dropTables(this.jdbcTemplate, names); + } + /** * Execute the given SQL script. Use with caution outside of a transaction! * <p>The script will normally be loaded by classpath. There should be one
true
Other
spring-projects
spring-framework
015086cb9c50fa4eabd47fab064bc1bbdde8caa6.json
Introduce new methods in tx base test classes Recently new utility methods were added to JdbcTestUtils, and a JdbcTemplate was introduced in abstract transactional base classes in the TestContext framework. This presents an easy opportunity to make these new utility methods available as convenience methods in the base test classes. This commit introduces new countRowsInTableWhere() and dropTables() convenience methods in the abstract transactional base classes in the TestContext framework. These new methods internally delegate to methods of the same names in JdbcTestUtils. Issue: SPR-9665
spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java
@@ -74,7 +74,7 @@ public static int countRowsInTable(JdbcTemplate jdbcTemplate, String tableName) * @param tableName the name of the table to count rows in * @param whereClause the {@code WHERE} clause to append to the query * @return the number of rows in the table that match the provided - * {@code WHERE} clause + * {@code WHERE} clause * @since 3.2 */ public static int countRowsInTableWhere(JdbcTemplate jdbcTemplate, String tableName, String whereClause) { @@ -111,7 +111,7 @@ public static int deleteFromTables(JdbcTemplate jdbcTemplate, String... tableNam * Drop the specified tables. * * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations - * @param tableNames the names of the tables to drop + * @param tableNames the names of the tables to drop * @since 3.2 */ public static void dropTables(JdbcTemplate jdbcTemplate, String... tableNames) {
true
Other
spring-projects
spring-framework
015086cb9c50fa4eabd47fab064bc1bbdde8caa6.json
Introduce new methods in tx base test classes Recently new utility methods were added to JdbcTestUtils, and a JdbcTemplate was introduced in abstract transactional base classes in the TestContext framework. This presents an easy opportunity to make these new utility methods available as convenience methods in the base test classes. This commit introduces new countRowsInTableWhere() and dropTables() convenience methods in the abstract transactional base classes in the TestContext framework. These new methods internally delegate to methods of the same names in JdbcTestUtils. Issue: SPR-9665
src/dist/changelog.txt
@@ -33,6 +33,7 @@ Changes in version 3.2 M2 (2012-08-xx) * deprecated SimpleJdbcTestUtils in favor of JdbcTestUtils (SPR-9235) * introduced countRowsInTableWhere() and dropTables() in JdbcTestUtils (SPR-9235) * introduced JdbcTemplate in tx base classes in the TestContext framework (SPR-8990) +* introduced countRowsInTableWhere() and dropTables() in tx base test classes (SPR-9665) Changes in version 3.2 M1 (2012-05-28)
true
Other
spring-projects
spring-framework
8d9637ada65b3b7211a37f853221493c963b1799.json
Provide JdbcTemplate in tx base classes in the TCF Since Spring 2.5, the abstract transactional base classes in the TestContext framework have defined and delegated to a protected SimpleJdbcTemplate instance variable; however, SimpleJdbcTemplate has deprecated since Spring 3.1. Consequently, subclasses of AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests that use this instance variable suffer from seemingly unnecessary deprecation warnings. This commit addresses this issue by introducing a protected JdbcTemplate instance variable in abstract transactional base classes to replace the use of the existing SimpleJdbcTemplate. Furthermore, the existing simpleJdbcTemplate instance variable has been deprecated, and utility methods in the affected base classes now delegate to JdbcTestUtils instead of the now deprecated SimpleJdbcTestUtils. Issue: SPR-8990
spring-test/src/main/java/org/springframework/test/context/junit4/AbstractTransactionalJUnit4SpringContextTests.java
@@ -23,11 +23,12 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; -import org.springframework.test.jdbc.SimpleJdbcTestUtils; +import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; @@ -38,7 +39,7 @@ * {@link PlatformTransactionManager} bean to be defined in the Spring * {@link ApplicationContext application context}. * - * <p>This class exposes a {@link SimpleJdbcTemplate} and provides an easy way + * <p>This class exposes a {@link JdbcTemplate} and provides an easy way * to {@link #countRowsInTable(String) count the number of rows in a table}, * {@link #deleteFromTables(String...) delete from tables}, and * {@link #executeSqlScript(String, boolean) execute SQL scripts} within a @@ -68,7 +69,7 @@ * @see org.springframework.test.annotation.Rollback * @see org.springframework.test.context.transaction.BeforeTransaction * @see org.springframework.test.context.transaction.AfterTransaction - * @see org.springframework.test.jdbc.SimpleJdbcTestUtils + * @see org.springframework.test.jdbc.JdbcTestUtils * @see org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests */ @TestExecutionListeners(TransactionalTestExecutionListener.class) @@ -77,19 +78,29 @@ public abstract class AbstractTransactionalJUnit4SpringContextTests extends AbstractJUnit4SpringContextTests { /** - * The SimpleJdbcTemplate that this base class manages, available to subclasses. + * The {@code SimpleJdbcTemplate} that this base class manages, available to subclasses. + * @deprecated As of Spring 3.2, use {@link #jdbcTemplate} instead. */ + @Deprecated protected SimpleJdbcTemplate simpleJdbcTemplate; + /** + * The {@code JdbcTemplate} that this base class manages, available to subclasses. + */ + protected JdbcTemplate jdbcTemplate; + private String sqlScriptEncoding; /** - * Set the DataSource, typically provided via Dependency Injection. + * Set the {@code DataSource}, typically provided via Dependency Injection. + * <p>This method also instantiates the {@link #simpleJdbcTemplate} and + * {@link #jdbcTemplate} instance variables. */ @Autowired public void setDataSource(DataSource dataSource) { this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); } /** @@ -106,7 +117,7 @@ public void setSqlScriptEncoding(String sqlScriptEncoding) { * @return the number of rows in the table */ protected int countRowsInTable(String tableName) { - return SimpleJdbcTestUtils.countRowsInTable(this.simpleJdbcTemplate, tableName); + return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName); } /** @@ -116,7 +127,7 @@ protected int countRowsInTable(String tableName) { * @return the total number of rows deleted from all specified tables */ protected int deleteFromTables(String... names) { - return SimpleJdbcTestUtils.deleteFromTables(this.simpleJdbcTemplate, names); + return JdbcTestUtils.deleteFromTables(this.jdbcTemplate, names); } /** @@ -132,7 +143,7 @@ protected int deleteFromTables(String... names) { */ protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException { Resource resource = this.applicationContext.getResource(sqlResourcePath); - SimpleJdbcTestUtils.executeSqlScript(this.simpleJdbcTemplate, new EncodedResource(resource, + JdbcTestUtils.executeSqlScript(this.jdbcTemplate, new EncodedResource(resource, this.sqlScriptEncoding), continueOnError); }
true
Other
spring-projects
spring-framework
8d9637ada65b3b7211a37f853221493c963b1799.json
Provide JdbcTemplate in tx base classes in the TCF Since Spring 2.5, the abstract transactional base classes in the TestContext framework have defined and delegated to a protected SimpleJdbcTemplate instance variable; however, SimpleJdbcTemplate has deprecated since Spring 3.1. Consequently, subclasses of AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests that use this instance variable suffer from seemingly unnecessary deprecation warnings. This commit addresses this issue by introducing a protected JdbcTemplate instance variable in abstract transactional base classes to replace the use of the existing SimpleJdbcTemplate. Furthermore, the existing simpleJdbcTemplate instance variable has been deprecated, and utility methods in the affected base classes now delegate to JdbcTestUtils instead of the now deprecated SimpleJdbcTestUtils. Issue: SPR-8990
spring-test/src/main/java/org/springframework/test/context/testng/AbstractTransactionalTestNGSpringContextTests.java
@@ -23,10 +23,11 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; -import org.springframework.test.jdbc.SimpleJdbcTestUtils; +import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; @@ -37,7 +38,7 @@ * {@link PlatformTransactionManager} bean to be defined in the Spring * {@link ApplicationContext application context}. * - * <p>This class exposes a {@link SimpleJdbcTemplate} and provides an easy way + * <p>This class exposes a {@link JdbcTemplate} and provides an easy way * to {@link #countRowsInTable(String) count the number of rows in a table}, * {@link #deleteFromTables(String...) delete from tables}, and * {@link #executeSqlScript(String, boolean) execute SQL scripts} within a @@ -57,7 +58,9 @@ * @see org.springframework.transaction.annotation.Transactional * @see org.springframework.test.annotation.NotTransactional * @see org.springframework.test.annotation.Rollback - * @see org.springframework.test.jdbc.SimpleJdbcTestUtils + * @see org.springframework.test.context.transaction.BeforeTransaction + * @see org.springframework.test.context.transaction.AfterTransaction + * @see org.springframework.test.jdbc.JdbcTestUtils * @see org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests */ @TestExecutionListeners(TransactionalTestExecutionListener.class) @@ -66,20 +69,29 @@ public abstract class AbstractTransactionalTestNGSpringContextTests extends AbstractTestNGSpringContextTests { /** - * The SimpleJdbcTemplate that this base class manages, available to subclasses. + * The {@code SimpleJdbcTemplate} that this base class manages, available to subclasses. + * @deprecated As of Spring 3.2, use {@link #jdbcTemplate} instead. */ + @Deprecated protected SimpleJdbcTemplate simpleJdbcTemplate; + /** + * The {@code JdbcTemplate} that this base class manages, available to subclasses. + */ + protected JdbcTemplate jdbcTemplate; + private String sqlScriptEncoding; /** - * Set the DataSource, typically provided via Dependency Injection. - * @param dataSource the DataSource to inject + * Set the {@code DataSource}, typically provided via Dependency Injection. + * <p>This method also instantiates the {@link #simpleJdbcTemplate} and + * {@link #jdbcTemplate} instance variables. */ @Autowired - public void setDataSource(final DataSource dataSource) { + public void setDataSource(DataSource dataSource) { this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); } /** @@ -96,24 +108,24 @@ public void setSqlScriptEncoding(String sqlScriptEncoding) { * @return the number of rows in the table */ protected int countRowsInTable(String tableName) { - return SimpleJdbcTestUtils.countRowsInTable(this.simpleJdbcTemplate, tableName); + return JdbcTestUtils.countRowsInTable(this.jdbcTemplate, tableName); } /** - * Convenience method for deleting all rows from the specified tables. - * Use with caution outside of a transaction! + * Convenience method for deleting all rows from the specified tables. Use + * with caution outside of a transaction! * @param names the names of the tables from which to delete * @return the total number of rows deleted from all specified tables */ protected int deleteFromTables(String... names) { - return SimpleJdbcTestUtils.deleteFromTables(this.simpleJdbcTemplate, names); + return JdbcTestUtils.deleteFromTables(this.jdbcTemplate, names); } /** * Execute the given SQL script. Use with caution outside of a transaction! - * <p>The script will normally be loaded by classpath. There should be one statement - * per line. Any semicolons will be removed. <b>Do not use this method to execute - * DDL if you expect rollback.</b> + * <p>The script will normally be loaded by classpath. There should be one + * statement per line. Any semicolons will be removed. <b>Do not use this + * method to execute DDL if you expect rollback.</b> * @param sqlResourcePath the Spring resource path for the SQL script * @param continueOnError whether or not to continue without throwing an * exception in the event of an error @@ -122,7 +134,7 @@ protected int deleteFromTables(String... names) { */ protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException { Resource resource = this.applicationContext.getResource(sqlResourcePath); - SimpleJdbcTestUtils.executeSqlScript(this.simpleJdbcTemplate, new EncodedResource(resource, + JdbcTestUtils.executeSqlScript(this.jdbcTemplate, new EncodedResource(resource, this.sqlScriptEncoding), continueOnError); }
true
Other
spring-projects
spring-framework
8d9637ada65b3b7211a37f853221493c963b1799.json
Provide JdbcTemplate in tx base classes in the TCF Since Spring 2.5, the abstract transactional base classes in the TestContext framework have defined and delegated to a protected SimpleJdbcTemplate instance variable; however, SimpleJdbcTemplate has deprecated since Spring 3.1. Consequently, subclasses of AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests that use this instance variable suffer from seemingly unnecessary deprecation warnings. This commit addresses this issue by introducing a protected JdbcTemplate instance variable in abstract transactional base classes to replace the use of the existing SimpleJdbcTemplate. Furthermore, the existing simpleJdbcTemplate instance variable has been deprecated, and utility methods in the affected base classes now delegate to JdbcTestUtils instead of the now deprecated SimpleJdbcTestUtils. Issue: SPR-8990
src/dist/changelog.txt
@@ -32,6 +32,7 @@ Changes in version 3.2 M2 (2012-08-xx) * introduced MockEnvironment in the spring-test module (SPR-9492) * deprecated SimpleJdbcTestUtils in favor of JdbcTestUtils (SPR-9235) * introduced countRowsInTableWhere() and dropTables() in JdbcTestUtils (SPR-9235) +* introduced JdbcTemplate in tx base classes in the TestContext framework (SPR-8990) Changes in version 3.2 M1 (2012-05-28)
true
Other
spring-projects
spring-framework
8d9637ada65b3b7211a37f853221493c963b1799.json
Provide JdbcTemplate in tx base classes in the TCF Since Spring 2.5, the abstract transactional base classes in the TestContext framework have defined and delegated to a protected SimpleJdbcTemplate instance variable; however, SimpleJdbcTemplate has deprecated since Spring 3.1. Consequently, subclasses of AbstractTransactionalJUnit4SpringContextTests and AbstractTransactionalTestNGSpringContextTests that use this instance variable suffer from seemingly unnecessary deprecation warnings. This commit addresses this issue by introducing a protected JdbcTemplate instance variable in abstract transactional base classes to replace the use of the existing SimpleJdbcTemplate. Furthermore, the existing simpleJdbcTemplate instance variable has been deprecated, and utility methods in the affected base classes now delegate to JdbcTestUtils instead of the now deprecated SimpleJdbcTestUtils. Issue: SPR-8990
src/reference/docbook/testing.xml
@@ -396,7 +396,7 @@ </listitem> <listitem> - <para>A <classname>SimpleJdbcTemplate</classname>, for executing + <para>A <classname>JdbcTemplate</classname>, for executing SQL statements to query the database. Such queries can be used to confirm database state both <emphasis>prior to</emphasis> and <emphasis>after</emphasis> execution of database-related @@ -422,15 +422,15 @@ <title>JDBC Testing Support</title> <para>The <literal>org.springframework.test.jdbc</literal> package - contains <classname>SimpleJdbcTestUtils</classname>, which is a + contains <classname>JdbcTestUtils</classname>, which is a collection of JDBC related utility functions intended to simplify standard database testing scenarios. <emphasis>Note that <link linkend="testcontext-support-classes-junit4"> <classname>AbstractTransactionalJUnit4SpringContextTests</classname> </link> and <link linkend="testcontext-support-classes-testng"> <classname>AbstractTransactionalTestNGSpringContextTests</classname> </link> provide convenience methods which delegate to - <classname>SimpleJdbcTestUtils</classname> internally.</emphasis></para> + <classname>JdbcTestUtils</classname> internally.</emphasis></para> <para>The <literal>spring-jdbc</literal> module provides support for configuring and launching an embedded database which can be used in @@ -2157,7 +2157,7 @@ public void updateWithSessionFlush() { </listitem> <listitem> - <para><literal>simpleJdbcTemplate</literal>: Use this + <para><literal>jdbcTemplate</literal>: Use this variable to execute SQL statements to query the database. Such queries can be used to confirm database state both <emphasis>prior to</emphasis> and <emphasis>after</emphasis> @@ -2266,7 +2266,7 @@ public class SimpleTest { </listitem> <listitem> - <para><literal>simpleJdbcTemplate</literal>: Use this + <para><literal>jdbcTemplate</literal>: Use this variable to execute SQL statements to query the database. Such queries can be used to confirm database state both <emphasis>prior to</emphasis> and <emphasis>after</emphasis>
true
Other
spring-projects
spring-framework
04bfc802dbb6809cccb6d0d1cbd7aa85938a0a0a.json
Use consistent HSQLDB version in Gradle build
build.gradle
@@ -18,6 +18,7 @@ configure(allprojects) { targetCompatibility=1.5 ext.aspectjVersion = '1.6.12' + ext.hsqldbVersion='1.8.0.10' ext.junitVersion = '4.10' [compileJava, compileTestJava]*.options*.compilerArgs = ['-Xlint:none'] @@ -301,7 +302,7 @@ project('spring-jdbc') { compile(project(":spring-context"), optional) // for JndiDataSourceLookup compile project(":spring-tx") compile("c3p0:c3p0:0.9.1.2", optional) - compile("hsqldb:hsqldb:1.8.0.7", optional) + compile("hsqldb:hsqldb:${hsqldbVersion}", optional) compile("com.h2database:h2:1.0.71", optional) compile("org.apache.derby:derby:10.5.3.0_1", optional) compile("org.apache.derby:derbyclient:10.5.3.0_1", optional) @@ -330,7 +331,7 @@ project('spring-context-support') { compile("commons-digester:commons-digester:1.8.1", optional) compile("commons-beanutils:commons-beanutils:1.8.0", optional) compile("com.lowagie:itext:2.0.8", optional) - testCompile "hsqldb:hsqldb:1.8.0.10" + testCompile "hsqldb:hsqldb:${hsqldbVersion}" testCompile("org.apache.poi:poi:3.0.2-FINAL") { exclude group: 'log4j', module: 'log4j' }
false
Other
spring-projects
spring-framework
914557b9753d2822f79b7be9d33a1258895a69e9.json
Use a default for INTROSPECT_TYPE_LEVEL_MAPPING Usually this request attribute is set for all sub-classes of AbstractUrlHandlerMapping and therefore whenever AnnotationMethodHandlerAdapter is used. However, having a default value to fall back on in AnnotationMethodHandlerAdapter is still appropriate in general and also considering the Javadoc of HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING. Issue: SPR-9629
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java
@@ -35,6 +35,7 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; + import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; @@ -45,7 +46,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -673,7 +673,8 @@ private boolean useTypeLevelMapping(HttpServletRequest request) { if (!hasTypeLevelMapping() || ObjectUtils.isEmpty(getTypeLevelMapping().value())) { return false; } - return (Boolean) request.getAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING); + Object value = request.getAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING); + return (value != null) ? (Boolean) value : Boolean.TRUE; } private boolean useSuffixPattern(HttpServletRequest request) {
false
Other
spring-projects
spring-framework
7c6a1a1bf0db6b428344ec6797a9152c5f4f6d30.json
Improve tests for detection of @MVC annotations Issue: SPR-9601
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HandlerMethodAnnotationDetectionTests.java
@@ -19,20 +19,25 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collection; import java.util.Date; +import org.aopalliance.aop.Advice; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; +import org.springframework.aop.Pointcut; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.aop.interceptor.SimpleTraceInterceptor; import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.aop.support.StaticMethodMatcherPointcut; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.propertyeditors.CustomDateEditor; +import org.springframework.core.annotation.AnnotationUtils; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.stereotype.Controller; @@ -91,21 +96,29 @@ public static Collection<Object[]> handlerTypes() { private ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver(); - public HandlerMethodAnnotationDetectionTests(Class<?> controllerType, boolean useAutoProxy) { + public HandlerMethodAnnotationDetectionTests(final Class<?> controllerType, boolean useAutoProxy) { GenericWebApplicationContext context = new GenericWebApplicationContext(); context.registerBeanDefinition("controller", new RootBeanDefinition(controllerType)); + context.registerBeanDefinition("handlerMapping", new RootBeanDefinition(RequestMappingHandlerMapping.class)); + context.registerBeanDefinition("handlerAdapter", new RootBeanDefinition(RequestMappingHandlerAdapter.class)); + context.registerBeanDefinition("exceptionResolver", new RootBeanDefinition(ExceptionHandlerExceptionResolver.class)); if (useAutoProxy) { DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator(); autoProxyCreator.setBeanFactory(context.getBeanFactory()); context.getBeanFactory().addBeanPostProcessor(autoProxyCreator); - context.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); + context.registerBeanDefinition("controllerAdvice", new RootBeanDefinition(ControllerAdvice.class)); } context.refresh(); - handlerMapping.setApplicationContext(context); - handlerMapping.afterPropertiesSet(); - handlerAdapter.afterPropertiesSet(); - exceptionResolver.afterPropertiesSet(); + this.handlerMapping = context.getBean(RequestMappingHandlerMapping.class); + this.handlerAdapter = context.getBean(RequestMappingHandlerAdapter.class); + this.exceptionResolver = context.getBean(ExceptionHandlerExceptionResolver.class); + } + + class TestPointcut extends StaticMethodMatcherPointcut { + public boolean matches(Method method, Class<?> clazz) { + return method.getName().equals("hashCode"); + } } @Test @@ -232,11 +245,11 @@ static interface MappingInterface { /** * CONTROLLER WITH INTERFACE * - * No AOP: - * All annotations can be on interface methods except parameter annotations. - * * JDK Dynamic proxy: * All annotations must be on the interface. + * + * Without AOP: + * Annotations can be on interface methods except parameter annotations. */ static class InterfaceController implements MappingInterface { @@ -391,4 +404,21 @@ public String handleException(Exception exception) { static class SupportClassController extends MappingSupportClass { } + + static class ControllerAdvice extends DefaultPointcutAdvisor { + + public ControllerAdvice() { + super(getControllerPointcut(), new SimpleTraceInterceptor()); + } + + private static StaticMethodMatcherPointcut getControllerPointcut() { + return new StaticMethodMatcherPointcut() { + public boolean matches(Method method, Class<?> targetClass) { + return ((AnnotationUtils.findAnnotation(targetClass, Controller.class) != null) || + (AnnotationUtils.findAnnotation(targetClass, RequestMapping.class) != null)); + } + }; + } + } + }
false
Other
spring-projects
spring-framework
060b37ca8db5a3b822029800348a3fe0f0b1b15f.json
Fix typo in MockFilterChain
spring-orm/src/test/java/org/springframework/mock/web/MockFilterChain.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * 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. @@ -23,15 +23,15 @@ import org.springframework.util.Assert; /** - * Mock implementation of the {@link javax.servlet.FilterConfig} interface. + * Mock implementation of the {@link javax.servlet.FilterChain} interface. * * <p>Used for testing the web framework; also useful for testing * custom {@link javax.servlet.Filter} implementations. * * @author Juergen Hoeller * @since 2.0.3 - * @see org.springframework.mock.web.MockFilterConfig - * @see org.springframework.mock.web.PassThroughFilterChain + * @see MockFilterConfig + * @see PassThroughFilterChain */ public class MockFilterChain implements FilterChain {
true
Other
spring-projects
spring-framework
060b37ca8db5a3b822029800348a3fe0f0b1b15f.json
Fix typo in MockFilterChain
spring-test/src/main/java/org/springframework/mock/web/MockFilterChain.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * 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. @@ -23,7 +23,7 @@ import org.springframework.util.Assert; /** - * Mock implementation of the {@link javax.servlet.FilterConfig} interface. + * Mock implementation of the {@link javax.servlet.FilterChain} interface. * * <p>Used for testing the web framework; also useful for testing * custom {@link javax.servlet.Filter} implementations.
true
Other
spring-projects
spring-framework
060b37ca8db5a3b822029800348a3fe0f0b1b15f.json
Fix typo in MockFilterChain
spring-web/src/test/java/org/springframework/mock/web/MockFilterChain.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -23,7 +23,7 @@ import org.springframework.util.Assert; /** - * Mock implementation of the {@link javax.servlet.FilterConfig} interface. + * Mock implementation of the {@link javax.servlet.FilterChain} interface. * * <p>Used for testing the web framework; also useful for testing * custom {@link javax.servlet.Filter} implementations.
true
Other
spring-projects
spring-framework
060b37ca8db5a3b822029800348a3fe0f0b1b15f.json
Fix typo in MockFilterChain
spring-webmvc/src/test/java/org/springframework/mock/web/MockFilterChain.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * 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. @@ -23,9 +23,9 @@ import org.springframework.util.Assert; /** - * Mock implementation of the {@link javax.servlet.FilterConfig} interface. + * Mock implementation of the {@link javax.servlet.FilterChain} interface. * - * <p>Used for testing the web framework; also usefol for testing + * <p>Used for testing the web framework; also useful for testing * custom {@link javax.servlet.Filter} implementations. * * @author Juergen Hoeller
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java
@@ -30,10 +30,19 @@ /** * This class is used to determine the requested {@linkplain MediaType media types} - * in a request by delegating to a list of {@link ContentNegotiationStrategy} instances. + * of a request by delegating to a list of ContentNegotiationStrategy instances. + * The strategies must be provided at instantiation or alternatively if using + * the default constructor, an instance of {@link HeaderContentNegotiationStrategy} + * will be configured by default. * - * <p>It may also be used to determine the extensions associated with a MediaType by - * delegating to a list of {@link MediaTypeFileExtensionResolver} instances. + * <p>This class may also be used to look up file extensions associated with a + * MediaType. This is done by consulting the list of configured + * {@link MediaTypeFileExtensionResolver} instances. Note that some + * ContentNegotiationStrategy implementations also implement + * MediaTypeFileExtensionResolver and the class constructor accepting the former + * will also detect if they implement the latter. If you need to register additional + * resolvers, you can use the method + * {@link #addFileExtensionResolvers(MediaTypeFileExtensionResolver...)}. * * @author Rossen Stoyanchev * @since 3.2 @@ -50,6 +59,7 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me * Create an instance with the given ContentNegotiationStrategy instances. * <p>Each instance is checked to see if it is also an implementation of * MediaTypeFileExtensionResolver, and if so it is registered as such. + * @param strategies one more more ContentNegotiationStrategy instances */ public ContentNegotiationManager(ContentNegotiationStrategy... strategies) { Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected"); @@ -70,6 +80,11 @@ public ContentNegotiationManager() { /** * Add MediaTypeFileExtensionResolver instances. + * <p>Note that some {@link ContentNegotiationStrategy} implementations also + * implement {@link MediaTypeFileExtensionResolver} and the class constructor + * accepting the former will also detect implementations of the latter. Therefore + * you only need to use this method to register additional instances. + * @param one more resolvers */ public void addFileExtensionResolvers(MediaTypeFileExtensionResolver... resolvers) { this.fileExtensionResolvers.addAll(Arrays.asList(resolvers));
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java
@@ -16,7 +16,10 @@ package org.springframework.web.servlet.config; +import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; @@ -29,6 +32,7 @@ import org.springframework.beans.factory.xml.ParserContext; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionServiceFactoryBean; +import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; @@ -44,6 +48,9 @@ import org.springframework.util.xml.DomUtils; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.HttpRequestHandler; +import org.springframework.web.accept.ContentNegotiationManager; +import org.springframework.web.accept.HeaderContentNegotiationStrategy; +import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; @@ -102,9 +109,10 @@ * </ul> * * <p>Both the {@link RequestMappingHandlerAdapter} and the - * {@link ExceptionHandlerExceptionResolver} are configured with default - * instances of the following kind, unless custom instances are provided: + * {@link ExceptionHandlerExceptionResolver} are configured with instances of + * the following by default: * <ul> + * <li>A {@link ContentNegotiationManager} * <li>A {@link DefaultFormattingConversionService} * <li>A {@link LocalValidatorFactoryBean} if a JSR-303 implementation is * available on the classpath @@ -143,11 +151,14 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source); parserContext.pushContainingComponent(compDefinition); - RootBeanDefinition methodMappingDef = new RootBeanDefinition(RequestMappingHandlerMapping.class); - methodMappingDef.setSource(source); - methodMappingDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - methodMappingDef.getPropertyValues().add("order", 0); - String methodMappingName = parserContext.getReaderContext().registerWithGeneratedName(methodMappingDef); + RuntimeBeanReference contentNegotiationManager = getContentNegotiationManager(element, source, parserContext); + + RootBeanDefinition handlerMappingDef = new RootBeanDefinition(RequestMappingHandlerMapping.class); + handlerMappingDef.setSource(source); + handlerMappingDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + handlerMappingDef.getPropertyValues().add("order", 0); + handlerMappingDef.getPropertyValues().add("contentNegotiationManager", contentNegotiationManager); + String methodMappingName = parserContext.getReaderContext().registerWithGeneratedName(handlerMappingDef); RuntimeBeanReference conversionService = getConversionService(element, source, parserContext); RuntimeBeanReference validator = getValidator(element, source, parserContext); @@ -164,22 +175,23 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { ManagedList<?> argumentResolvers = getArgumentResolvers(element, source, parserContext); ManagedList<?> returnValueHandlers = getReturnValueHandlers(element, source, parserContext); - RootBeanDefinition methodAdapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); - methodAdapterDef.setSource(source); - methodAdapterDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - methodAdapterDef.getPropertyValues().add("webBindingInitializer", bindingDef); - methodAdapterDef.getPropertyValues().add("messageConverters", messageConverters); + RootBeanDefinition handlerAdapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); + handlerAdapterDef.setSource(source); + handlerAdapterDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + handlerAdapterDef.getPropertyValues().add("contentNegotiationManager", contentNegotiationManager); + handlerAdapterDef.getPropertyValues().add("webBindingInitializer", bindingDef); + handlerAdapterDef.getPropertyValues().add("messageConverters", messageConverters); if (element.hasAttribute("ignoreDefaultModelOnRedirect")) { Boolean ignoreDefaultModel = Boolean.valueOf(element.getAttribute("ignoreDefaultModelOnRedirect")); - methodAdapterDef.getPropertyValues().add("ignoreDefaultModelOnRedirect", ignoreDefaultModel); + handlerAdapterDef.getPropertyValues().add("ignoreDefaultModelOnRedirect", ignoreDefaultModel); } if (argumentResolvers != null) { - methodAdapterDef.getPropertyValues().add("customArgumentResolvers", argumentResolvers); + handlerAdapterDef.getPropertyValues().add("customArgumentResolvers", argumentResolvers); } if (returnValueHandlers != null) { - methodAdapterDef.getPropertyValues().add("customReturnValueHandlers", returnValueHandlers); + handlerAdapterDef.getPropertyValues().add("customReturnValueHandlers", returnValueHandlers); } - String methodAdapterName = parserContext.getReaderContext().registerWithGeneratedName(methodAdapterDef); + String handlerAdapterName = parserContext.getReaderContext().registerWithGeneratedName(handlerAdapterDef); RootBeanDefinition csInterceptorDef = new RootBeanDefinition(ConversionServiceExposingInterceptor.class); csInterceptorDef.setSource(source); @@ -191,13 +203,14 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { mappedCsInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(1, csInterceptorDef); String mappedInterceptorName = parserContext.getReaderContext().registerWithGeneratedName(mappedCsInterceptorDef); - RootBeanDefinition methodExceptionResolver = new RootBeanDefinition(ExceptionHandlerExceptionResolver.class); - methodExceptionResolver.setSource(source); - methodExceptionResolver.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); - methodExceptionResolver.getPropertyValues().add("messageConverters", messageConverters); - methodExceptionResolver.getPropertyValues().add("order", 0); + RootBeanDefinition exceptionHandlerExceptionResolver = new RootBeanDefinition(ExceptionHandlerExceptionResolver.class); + exceptionHandlerExceptionResolver.setSource(source); + exceptionHandlerExceptionResolver.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + exceptionHandlerExceptionResolver.getPropertyValues().add("contentNegotiationManager", contentNegotiationManager); + exceptionHandlerExceptionResolver.getPropertyValues().add("messageConverters", messageConverters); + exceptionHandlerExceptionResolver.getPropertyValues().add("order", 0); String methodExceptionResolverName = - parserContext.getReaderContext().registerWithGeneratedName(methodExceptionResolver); + parserContext.getReaderContext().registerWithGeneratedName(exceptionHandlerExceptionResolver); RootBeanDefinition responseStatusExceptionResolver = new RootBeanDefinition(ResponseStatusExceptionResolver.class); responseStatusExceptionResolver.setSource(source); @@ -213,9 +226,9 @@ public BeanDefinition parse(Element element, ParserContext parserContext) { String defaultExceptionResolverName = parserContext.getReaderContext().registerWithGeneratedName(defaultExceptionResolver); - parserContext.registerComponent(new BeanComponentDefinition(methodMappingDef, methodMappingName)); - parserContext.registerComponent(new BeanComponentDefinition(methodAdapterDef, methodAdapterName)); - parserContext.registerComponent(new BeanComponentDefinition(methodExceptionResolver, methodExceptionResolverName)); + parserContext.registerComponent(new BeanComponentDefinition(handlerMappingDef, methodMappingName)); + parserContext.registerComponent(new BeanComponentDefinition(handlerAdapterDef, handlerAdapterName)); + parserContext.registerComponent(new BeanComponentDefinition(exceptionHandlerExceptionResolver, methodExceptionResolverName)); parserContext.registerComponent(new BeanComponentDefinition(responseStatusExceptionResolver, responseStatusExceptionResolverName)); parserContext.registerComponent(new BeanComponentDefinition(defaultExceptionResolver, defaultExceptionResolverName)); parserContext.registerComponent(new BeanComponentDefinition(mappedCsInterceptorDef, mappedInterceptorName)); @@ -261,6 +274,42 @@ else if (jsr303Present) { } } + private RuntimeBeanReference getContentNegotiationManager(Element element, Object source, ParserContext parserContext) { + RuntimeBeanReference contentNegotiationManagerRef; + if (element.hasAttribute("content-negotiation-manager")) { + contentNegotiationManagerRef = new RuntimeBeanReference(element.getAttribute("content-negotiation-manager")); + } + else { + RootBeanDefinition managerDef = new RootBeanDefinition(ContentNegotiationManager.class); + managerDef.setSource(source); + managerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); + PathExtensionContentNegotiationStrategy strategy1 = new PathExtensionContentNegotiationStrategy(getDefaultMediaTypes()); + HeaderContentNegotiationStrategy strategy2 = new HeaderContentNegotiationStrategy(); + managerDef.getConstructorArgumentValues().addIndexedArgumentValue(0, Arrays.asList(strategy1,strategy2)); + + String beanName = "mvcContentNegotiationManager"; + parserContext.getReaderContext().getRegistry().registerBeanDefinition(beanName , managerDef); + parserContext.registerComponent(new BeanComponentDefinition(managerDef, beanName)); + contentNegotiationManagerRef = new RuntimeBeanReference(beanName); + } + return contentNegotiationManagerRef; + } + + private Map<String, MediaType> getDefaultMediaTypes() { + Map<String, MediaType> map = new HashMap<String, MediaType>(); + if (romePresent) { + map.put("atom", MediaType.APPLICATION_ATOM_XML); + map.put("rss", MediaType.valueOf("application/rss+xml")); + } + if (jackson2Present || jacksonPresent) { + map.put("json", MediaType.APPLICATION_JSON); + } + if (jaxb2Present) { + map.put("xml", MediaType.APPLICATION_XML); + } + return map; + } + private RuntimeBeanReference getMessageCodesResolver(Element element, Object source, ParserContext parserContext) { if (element.hasAttribute("message-codes-resolver")) { return new RuntimeBeanReference(element.getAttribute("message-codes-resolver"));
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ContentNegotiationConfigurer.java
@@ -0,0 +1,195 @@ +/* + * 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.web.servlet.config.annotation; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.springframework.http.MediaType; +import org.springframework.util.CollectionUtils; +import org.springframework.web.accept.ContentNegotiationManager; +import org.springframework.web.accept.ContentNegotiationStrategy; +import org.springframework.web.accept.FixedContentNegotiationStrategy; +import org.springframework.web.accept.HeaderContentNegotiationStrategy; +import org.springframework.web.accept.ParameterContentNegotiationStrategy; +import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; + +/** + * Helps with configuring a {@link ContentNegotiationManager}. + * + * <p>By default the extension of the request path extension is checked first and + * the {@code Accept} is checked second. The path extension check will perform a + * look up in the media types configured via {@link #setMediaTypes(Map)} and + * will also fall back to {@link ServletContext} and the Java Activation Framework + * (if present). + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +public class ContentNegotiationConfigurer { + + private boolean favorPathExtension = true; + + private boolean favorParameter = false; + + private boolean ignoreAcceptHeader = false; + + private Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>(); + + private Boolean useJaf; + + private String parameterName; + + private MediaType defaultContentType; + + /** + * Indicate whether the extension of the request path should be used to determine + * the requested media type with the <em>highest priority</em>. + * <p>By default this value is set to {@code true} in which case a request + * for {@code /hotels.pdf} will be interpreted as a request for + * {@code "application/pdf"} regardless of the {@code Accept} header. + */ + public ContentNegotiationConfigurer setFavorPathExtension(boolean favorPathExtension) { + this.favorPathExtension = favorPathExtension; + return this; + } + + /** + * Add mappings from file extensions to media types. + * <p>If this property is not set, the Java Action Framework, if available, may + * still be used in conjunction with {@link #setFavorPathExtension(boolean)}. + */ + public ContentNegotiationConfigurer addMediaTypes(Map<String, MediaType> mediaTypes) { + if (!CollectionUtils.isEmpty(mediaTypes)) { + for (Map.Entry<String, MediaType> entry : mediaTypes.entrySet()) { + String extension = entry.getKey().toLowerCase(Locale.ENGLISH); + this.mediaTypes.put(extension, entry.getValue()); + } + } + return this; + } + + /** + * Add mappings from file extensions to media types replacing any previous mappings. + * <p>If this property is not set, the Java Action Framework, if available, may + * still be used in conjunction with {@link #setFavorPathExtension(boolean)}. + */ + public ContentNegotiationConfigurer replaceMediaTypes(Map<String, MediaType> mediaTypes) { + this.mediaTypes.clear(); + if (!CollectionUtils.isEmpty(mediaTypes)) { + for (Map.Entry<String, MediaType> entry : mediaTypes.entrySet()) { + String extension = entry.getKey().toLowerCase(Locale.ENGLISH); + this.mediaTypes.put(extension, entry.getValue()); + } + } + return this; + } + + /** + * Indicate whether to use the Java Activation Framework as a fallback option + * to map from file extensions to media types. This is used only when + * {@link #setFavorPathExtension(boolean)} is set to {@code true}. + * <p>The default value is {@code true}. + * @see #parameterName + * @see #setMediaTypes(Map) + */ + public ContentNegotiationConfigurer setUseJaf(boolean useJaf) { + this.useJaf = useJaf; + return this; + } + + /** + * Indicate whether a request parameter should be used to determine the + * requested media type with the <em>2nd highest priority</em>, i.e. + * after path extensions but before the {@code Accept} header. + * <p>The default value is {@code false}. If set to to {@code true}, a request + * for {@code /hotels?format=pdf} will be interpreted as a request for + * {@code "application/pdf"} regardless of the {@code Accept} header. + * <p>To use this option effectively you must also configure the MediaType + * type mappings via {@link #setMediaTypes(Map)}. + * @see #setParameterName(String) + */ + public ContentNegotiationConfigurer setFavorParameter(boolean favorParameter) { + this.favorParameter = favorParameter; + return this; + } + + /** + * Set the parameter name that can be used to determine the requested media type + * if the {@link #setFavorParameter} property is {@code true}. + * <p>The default parameter name is {@code "format"}. + */ + public ContentNegotiationConfigurer setParameterName(String parameterName) { + this.parameterName = parameterName; + return this; + } + + /** + * Indicate whether the HTTP {@code Accept} header should be ignored altogether. + * If set the {@code Accept} header is checked at the + * <em>3rd highest priority</em>, i.e. after the request path extension and + * possibly a request parameter if configured. + * <p>By default this value is set to {@code false}. + */ + public ContentNegotiationConfigurer setIgnoreAcceptHeader(boolean ignoreAcceptHeader) { + this.ignoreAcceptHeader = ignoreAcceptHeader; + return this; + } + + /** + * Set the default content type. + * <p>This content type will be used when neither the request path extension, + * nor a request parameter, nor the {@code Accept} header could help determine + * the requested content type. + */ + public ContentNegotiationConfigurer setDefaultContentType(MediaType defaultContentType) { + this.defaultContentType = defaultContentType; + return this; + } + + /** + * @return the configured {@link ContentNegotiationManager} instance + */ + protected ContentNegotiationManager getContentNegotiationManager() { + List<ContentNegotiationStrategy> strategies = new ArrayList<ContentNegotiationStrategy>(); + if (this.favorPathExtension) { + PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes); + if (this.useJaf != null) { + strategy.setUseJaf(this.useJaf); + } + strategies.add(strategy); + } + if (this.favorParameter) { + ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(this.mediaTypes); + strategy.setParameterName(this.parameterName); + strategies.add(strategy); + } + if (!this.ignoreAcceptHeader) { + strategies.add(new HeaderContentNegotiationStrategy()); + } + if (this.defaultContentType != null) { + strategies.add(new FixedContentNegotiationStrategy(this.defaultContentType)); + } + ContentNegotiationStrategy[] array = strategies.toArray(new ContentNegotiationStrategy[strategies.size()]); + return new ContentNegotiationManager(array); + } + +}
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java
@@ -55,6 +55,11 @@ protected void addInterceptors(InterceptorRegistry registry) { this.configurers.addInterceptors(registry); } + @Override + protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) { + this.configurers.configureContentNegotiation(configurer); + } + @Override protected void addViewControllers(ViewControllerRegistry registry) { this.configurers.addViewControllers(registry);
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/InterceptorRegistry.java
@@ -24,23 +24,22 @@ import org.springframework.web.servlet.handler.WebRequestHandlerInterceptorAdapter; /** - * Stores and provides access to a list of interceptors. For each interceptor you can optionally - * specify one or more URL patterns it applies to. + * Helps with configuring a list of mapped interceptors. * * @author Rossen Stoyanchev * @author Keith Donald - * + * * @since 3.1 */ public class InterceptorRegistry { private final List<InterceptorRegistration> registrations = new ArrayList<InterceptorRegistration>(); - + /** - * Adds the provided {@link HandlerInterceptor}. + * Adds the provided {@link HandlerInterceptor}. * @param interceptor the interceptor to add - * @return An {@link InterceptorRegistration} that allows you optionally configure the - * registered interceptor further for example adding URL patterns it should apply to. + * @return An {@link InterceptorRegistration} that allows you optionally configure the + * registered interceptor further for example adding URL patterns it should apply to. */ public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) { InterceptorRegistration registration = new InterceptorRegistration(interceptor); @@ -49,10 +48,10 @@ public InterceptorRegistration addInterceptor(HandlerInterceptor interceptor) { } /** - * Adds the provided {@link WebRequestInterceptor}. + * Adds the provided {@link WebRequestInterceptor}. * @param interceptor the interceptor to add - * @return An {@link InterceptorRegistration} that allows you optionally configure the - * registered interceptor further for example adding URL patterns it should apply to. + * @return An {@link InterceptorRegistration} that allows you optionally configure the + * registered interceptor further for example adding URL patterns it should apply to. */ public InterceptorRegistration addWebRequestInterceptor(WebRequestInterceptor interceptor) { WebRequestHandlerInterceptorAdapter adapted = new WebRequestHandlerInterceptorAdapter(interceptor);
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
@@ -17,7 +17,9 @@ package org.springframework.web.servlet.config.annotation; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -35,6 +37,7 @@ import org.springframework.format.FormatterRegistry; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; +import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; @@ -52,6 +55,7 @@ import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.HttpRequestHandler; +import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; @@ -120,8 +124,9 @@ * * <p>Both the {@link RequestMappingHandlerAdapter} and the * {@link ExceptionHandlerExceptionResolver} are configured with default - * instances of the following kind, unless custom instances are provided: + * instances of the following by default: * <ul> + * <li>A {@link ContentNegotiationManager} * <li>A {@link DefaultFormattingConversionService} * <li>A {@link LocalValidatorFactoryBean} if a JSR-303 implementation is * available on the classpath @@ -158,6 +163,8 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv private List<Object> interceptors; + private ContentNegotiationManager contentNegotiationManager; + private List<HttpMessageConverter<?>> messageConverters; public void setServletContext(ServletContext servletContext) { @@ -177,6 +184,7 @@ public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping(); handlerMapping.setOrder(0); handlerMapping.setInterceptors(getInterceptors()); + handlerMapping.setContentNegotiationManager(mvcContentNegotiationManager()); return handlerMapping; } @@ -203,6 +211,43 @@ protected final Object[] getInterceptors() { protected void addInterceptors(InterceptorRegistry registry) { } + /** + * Return a {@link ContentNegotiationManager} instance to use to determine + * requested {@linkplain MediaType media types} in a given request. + */ + @Bean + public ContentNegotiationManager mvcContentNegotiationManager() { + if (this.contentNegotiationManager == null) { + ContentNegotiationConfigurer configurer = new ContentNegotiationConfigurer(); + configurer.addMediaTypes(getDefaultMediaTypes()); + configureContentNegotiation(configurer); + this.contentNegotiationManager = configurer.getContentNegotiationManager(); + } + return this.contentNegotiationManager; + } + + protected Map<String, MediaType> getDefaultMediaTypes() { + Map<String, MediaType> map = new HashMap<String, MediaType>(); + if (romePresent) { + map.put("atom", MediaType.APPLICATION_ATOM_XML); + map.put("rss", MediaType.valueOf("application/rss+xml")); + } + if (jackson2Present || jacksonPresent) { + map.put("json", MediaType.APPLICATION_JSON); + } + if (jaxb2Present) { + map.put("xml", MediaType.APPLICATION_XML); + } + return map; + } + + /** + * Override this method to configure content negotiation. + * @see DefaultServletHandlerConfigurer + */ + protected void configureContentNegotiation(ContentNegotiationConfigurer configurer) { + } + /** * Return a handler mapping ordered at 1 to map URL paths directly to * view names. To configure view controllers, override @@ -304,6 +349,7 @@ public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { addReturnValueHandlers(returnValueHandlers); RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); + adapter.setContentNegotiationManager(mvcContentNegotiationManager()); adapter.setMessageConverters(getMessageConverters()); adapter.setWebBindingInitializer(webBindingInitializer); adapter.setCustomArgumentResolvers(argumentResolvers); @@ -526,8 +572,7 @@ protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> } /** - * A method available to subclasses for adding default - * {@link HandlerExceptionResolver}s. + * A method available to subclasses for adding default {@link HandlerExceptionResolver}s. * <p>Adds the following exception resolvers: * <ul> * <li>{@link ExceptionHandlerExceptionResolver} @@ -540,6 +585,7 @@ protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> */ protected final void addDefaultHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver = new ExceptionHandlerExceptionResolver(); + exceptionHandlerExceptionResolver.setContentNegotiationManager(mvcContentNegotiationManager()); exceptionHandlerExceptionResolver.setMessageConverters(getMessageConverters()); exceptionHandlerExceptionResolver.afterPropertiesSet();
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.java
@@ -69,6 +69,11 @@ public interface WebMvcConfigurer { */ Validator getValidator(); + /** + * Configure content negotiation options. + */ + void configureContentNegotiation(ContentNegotiationConfigurer configurer); + /** * Add resolvers to support custom controller method argument types. * <p>This does not override the built-in support for resolving handler
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java
@@ -57,6 +57,13 @@ public Validator getValidator() { return null; } + /** + * {@inheritDoc} + * <p>This implementation is empty. + */ + public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { + } + /** * {@inheritDoc} * <p>This implementation is empty.
true
Other
spring-projects
spring-framework
028e15faa33888673bfc7b55eaa65eb93f7bca0c.json
Add options to configure content negotiation The MVC Java config and the MVC namespace now support options to configure content negotiation. By default both support checking path extensions first and the "Accept" header second. For path extensions .json, .xml, .atom, and .rss are recognized out of the box if the Jackson, JAXB2, or Rome libraries are available. The ServletContext and the Java Activation Framework may be used as fallback options for path extension lookups. Issue: SPR-8420
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerComposite.java
@@ -49,6 +49,12 @@ public void addFormatters(FormatterRegistry registry) { } } + public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { + for (WebMvcConfigurer delegate : this.delegates) { + delegate.configureContentNegotiation(configurer); + } + } + public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { for (WebMvcConfigurer delegate : this.delegates) { delegate.configureMessageConverters(converters);
true