Rossen Stoyanchev
2017-10-20 16:41:40 -04:00
parent 8ad212dae2
commit 1cc5afe24b
197 changed files with 1688 additions and 994 deletions

View File

@@ -68,7 +68,8 @@ public class ContextLoaderTests {
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr);
assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext);
LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
@@ -80,7 +81,7 @@ public class ContextLoaderTests {
assertFalse(context.containsBean("beans1.bean2"));
listener.contextDestroyed(event);
assertTrue("Destroyed", lb.isDestroyed());
assertNull(sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
assertNull(sc.getAttribute(contextAttr));
assertNull(WebApplicationContextUtils.getWebApplicationContext(sc));
}
@@ -207,7 +208,8 @@ public class ContextLoaderTests {
"/org/springframework/web/context/WEB-INF/empty-context.xml");
sc.addInitParameter("someProperty", "someValue");
sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, EnvApplicationContextInitializer.class.getName());
sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM,
EnvApplicationContextInitializer.class.getName());
ContextLoaderListener listener = new ContextLoaderListener();
listener.contextInitialized(new ServletContextEvent(sc));
}
@@ -238,8 +240,10 @@ public class ContextLoaderTests {
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
assertTrue("Correct WebApplicationContext exposed in ServletContext", wc instanceof SimpleWebApplicationContext);
String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(contextAttr);
assertTrue("Correct WebApplicationContext exposed in ServletContext",
wc instanceof SimpleWebApplicationContext);
}
@Test
@@ -376,7 +380,8 @@ public class ContextLoaderTests {
}
private static class TestWebContextInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
private static class TestWebContextInitializer implements
ApplicationContextInitializer<ConfigurableWebApplicationContext> {
@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {
@@ -386,7 +391,8 @@ public class ContextLoaderTests {
}
private static class EnvApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
private static class EnvApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {

View File

@@ -880,7 +880,8 @@ public class DispatcherServletTests {
}
private static class TestWebContextInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
private static class TestWebContextInitializer
implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {
@@ -889,7 +890,8 @@ public class DispatcherServletTests {
}
private static class OtherWebContextInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
private static class OtherWebContextInitializer
implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {

View File

@@ -188,8 +188,8 @@ public class MvcNamespaceTests {
appContext.getServletContext().setAttribute(attributeName, appContext);
handler = new TestController();
Method method = TestController.class.getMethod("testBind", Date.class, Double.class, TestBean.class, BindingResult.class);
handlerMethod = new InvocableHandlerMethod(handler, method);
handlerMethod = new InvocableHandlerMethod(handler, TestController.class.getMethod("testBind",
Date.class, Double.class, TestBean.class, BindingResult.class));
}

View File

@@ -48,6 +48,7 @@ import org.springframework.web.util.UrlPathHelper;
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;
@@ -98,11 +99,10 @@ public class DelegatingWebMvcConfigurationTests {
@Test
public void requestMappingHandlerAdapter() throws Exception {
delegatingConfig.setConfigurers(Collections.singletonList(webMvcConfigurer));
RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter();
RequestMappingHandlerAdapter adapter = this.delegatingConfig.requestMappingHandlerAdapter();
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
ConversionService initializerConversionService = initializer.getConversionService();
assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
ConfigurableWebBindingInitializer initializer =
(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
verify(webMvcConfigurer).configureMessageConverters(converters.capture());
verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture());
@@ -111,7 +111,9 @@ public class DelegatingWebMvcConfigurationTests {
verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture());
verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture());
assertSame(conversionService.getValue(), initializerConversionService);
assertNotNull(initializer);
assertSame(conversionService.getValue(), initializer.getConversionService());
assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
assertEquals(0, resolvers.getValue().size());
assertEquals(0, handlers.getValue().size());
assertEquals(converters.getValue(), adapter.getMessageConverters());

View File

@@ -175,7 +175,9 @@ public class InterceptorRegistryTests {
return result;
}
private void verifyWebInterceptor(HandlerInterceptor interceptor, TestWebRequestInterceptor webInterceptor) throws Exception {
private void verifyWebInterceptor(HandlerInterceptor interceptor,
TestWebRequestInterceptor webInterceptor) throws Exception {
assertTrue(interceptor instanceof WebRequestHandlerInterceptorAdapter);
interceptor.preHandle(this.request, this.response, null);
assertTrue(webInterceptor.preHandleInvoked);

View File

@@ -224,7 +224,9 @@ public class WebMvcConfigurationSupportExtensionTests {
public void webBindingInitializer() throws Exception {
RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter();
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
ConfigurableWebBindingInitializer initializer =
(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
assertNotNull(initializer);
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, "");

View File

@@ -189,7 +189,9 @@ public class CorsAbstractHandlerMappingTests {
}
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setStatus(HttpStatus.OK.value());
}

View File

@@ -56,18 +56,18 @@ public class HandlerMappingTests {
@Test
public void orderedInterceptors() throws Exception {
MappedInterceptor firstMappedInterceptor = new MappedInterceptor(new String[]{"/**"}, Mockito.mock(HandlerInterceptor.class));
HandlerInterceptor secondHandlerInterceptor = Mockito.mock(HandlerInterceptor.class);
MappedInterceptor thirdMappedInterceptor = new MappedInterceptor(new String[]{"/**"}, Mockito.mock(HandlerInterceptor.class));
HandlerInterceptor fourthHandlerInterceptor = Mockito.mock(HandlerInterceptor.class);
HandlerInterceptor i1 = Mockito.mock(HandlerInterceptor.class);
MappedInterceptor mappedInterceptor1 = new MappedInterceptor(new String[]{"/**"}, i1);
HandlerInterceptor i2 = Mockito.mock(HandlerInterceptor.class);
HandlerInterceptor i3 = Mockito.mock(HandlerInterceptor.class);
MappedInterceptor mappedInterceptor3 = new MappedInterceptor(new String[]{"/**"}, i3);
HandlerInterceptor i4 = Mockito.mock(HandlerInterceptor.class);
this.handlerMapping.setInterceptors(new Object[]{firstMappedInterceptor, secondHandlerInterceptor,
thirdMappedInterceptor, fourthHandlerInterceptor});
this.handlerMapping.setInterceptors(mappedInterceptor1, i2, mappedInterceptor3, i4);
this.handlerMapping.setApplicationContext(this.context);
HandlerExecutionChain chain = this.handlerMapping.getHandlerExecutionChain(new SimpleHandler(), this.request);
Assert.assertThat(chain.getInterceptors(),
Matchers.arrayContaining(firstMappedInterceptor.getInterceptor(), secondHandlerInterceptor,
thirdMappedInterceptor.getInterceptor(), fourthHandlerInterceptor));
Assert.assertThat(chain.getInterceptors(), Matchers.arrayContaining(
mappedInterceptor1.getInterceptor(), i2, mappedInterceptor3.getInterceptor(), i4));
}
class TestHandlerMapping extends AbstractHandlerMapping {

View File

@@ -237,7 +237,8 @@ public class PathMatchingUrlHandlerMappingTests {
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/show.html");
HandlerExecutionChain hec = getHandler(req);
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
assertEquals("Mapping not exposed", "show.html", req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
assertEquals("Mapping not exposed", "show.html",
req.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
}
private HandlerExecutionChain getHandler(MockHttpServletRequest req) throws Exception {

View File

@@ -152,16 +152,16 @@ public class UrlFilenameViewControllerTests {
public void settingPrefixToNullCausesEmptyStringToBeUsed() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
ctrl.setPrefix(null);
assertNotNull("When setPrefix(..) is called with a null argument, the empty string value must be used instead.", ctrl.getPrefix());
assertEquals("When setPrefix(..) is called with a null argument, the empty string value must be used instead.", "", ctrl.getPrefix());
assertNotNull("For setPrefix(..) with null, the empty string must be used instead.", ctrl.getPrefix());
assertEquals("For setPrefix(..) with null, the empty string must be used instead.", "", ctrl.getPrefix());
}
@Test
public void settingSuffixToNullCausesEmptyStringToBeUsed() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
ctrl.setSuffix(null);
assertNotNull("When setSuffix(..) is called with a null argument, the empty string value must be used instead.", ctrl.getSuffix());
assertEquals("When setSuffix(..) is called with a null argument, the empty string value must be used instead.", "", ctrl.getSuffix());
assertNotNull("For setPrefix(..) with null, the empty string must be used instead.", ctrl.getSuffix());
assertEquals("For setPrefix(..) with null, the empty string must be used instead.", "", ctrl.getSuffix());
}
/**

View File

@@ -87,14 +87,14 @@ public abstract class AbstractServletHandlerMethodTests {
RootBeanDefinition mappingDef = new RootBeanDefinition(RequestMappingHandlerMapping.class);
mappingDef.getPropertyValues().add("removeSemicolonContent", "false");
wac.registerBeanDefinition("handlerMapping", mappingDef);
wac.registerBeanDefinition("handlerAdapter", new RootBeanDefinition(RequestMappingHandlerAdapter.class));
wac.registerBeanDefinition("requestMappingResolver", new RootBeanDefinition(ExceptionHandlerExceptionResolver.class));
wac.registerBeanDefinition("responseStatusResolver", new RootBeanDefinition(ResponseStatusExceptionResolver.class));
wac.registerBeanDefinition("defaultResolver", new RootBeanDefinition(DefaultHandlerExceptionResolver.class));
wac.registerBeanDefinition("handlerAdapter",
new RootBeanDefinition(RequestMappingHandlerAdapter.class));
wac.registerBeanDefinition("requestMappingResolver",
new RootBeanDefinition(ExceptionHandlerExceptionResolver.class));
wac.registerBeanDefinition("responseStatusResolver",
new RootBeanDefinition(ResponseStatusExceptionResolver.class));
wac.registerBeanDefinition("defaultResolver",
new RootBeanDefinition(DefaultHandlerExceptionResolver.class));
if (initializer != null) {
initializer.initialize(wac);

View File

@@ -39,6 +39,8 @@ import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.StaticWebApplicationContext;
@@ -315,48 +317,52 @@ public class CrossOriginTests {
@Controller
private static class MethodLevelController {
@RequestMapping(path = "/no", method = RequestMethod.GET)
@GetMapping("/no")
public void noAnnotation() {
}
@RequestMapping(path = "/no", method = RequestMethod.POST)
@PostMapping("/no")
public void noAnnotationPost() {
}
@CrossOrigin
@RequestMapping(path = "/default", method = RequestMethod.GET)
@GetMapping(path = "/default")
public void defaultAnnotation() {
}
@CrossOrigin
@RequestMapping(path = "/default", method = RequestMethod.GET, params = "q")
@GetMapping(path = "/default", params = "q")
public void defaultAnnotationWithParams() {
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-header", method = RequestMethod.GET, headers = "header1=a")
@GetMapping(path = "/ambiguous-header", headers = "header1=a")
public void ambigousHeader1a() {
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-header", method = RequestMethod.GET, headers = "header1=b")
@GetMapping(path = "/ambiguous-header", headers = "header1=b")
public void ambigousHeader1b() {
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-produces", method = RequestMethod.GET, produces = "application/xml")
@GetMapping(path = "/ambiguous-produces", produces = "application/xml")
public String ambigousProducesXml() {
return "<a></a>";
}
@CrossOrigin
@RequestMapping(path = "/ambiguous-produces", method = RequestMethod.GET, produces = "application/json")
@GetMapping(path = "/ambiguous-produces", produces = "application/json")
public String ambigousProducesJson() {
return "{}";
}
@CrossOrigin(origins = { "http://site1.com", "http://site2.com" }, allowedHeaders = { "header1", "header2" },
exposedHeaders = { "header3", "header4" }, methods = RequestMethod.DELETE, maxAge = 123, allowCredentials = "false")
@CrossOrigin(origins = { "http://site1.com", "http://site2.com" },
allowedHeaders = { "header1", "header2" },
exposedHeaders = { "header3", "header4" },
methods = RequestMethod.DELETE,
maxAge = 123,
allowCredentials = "false")
@RequestMapping(path = "/customized", method = { RequestMethod.GET, RequestMethod.POST })
public void customized() {
}

View File

@@ -395,7 +395,8 @@ public class HandlerMethodAnnotationDetectionTests {
public abstract String handleException(Exception exception);
}
static class ParameterizedSubclassOverridesDefaultMappings extends GenericAbstractClassDeclaresDefaultMappings<String, Date, Date> {
static class ParameterizedSubclassOverridesDefaultMappings
extends GenericAbstractClassDeclaresDefaultMappings<String, Date, Date> {
@Override
public void initBinder(WebDataBinder dataBinder, @RequestParam("datePattern") String thePattern) {

View File

@@ -20,6 +20,7 @@ import java.lang.reflect.Method;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
@@ -55,6 +56,8 @@ import static java.time.Instant.*;
import static java.time.format.DateTimeFormatter.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.http.MediaType.APPLICATION_OCTET_STREAM;
import static org.springframework.http.MediaType.TEXT_PLAIN;
import static org.springframework.web.servlet.HandlerMapping.*;
/**
@@ -115,15 +118,21 @@ public class HttpEntityMethodProcessorMockTests {
@Before
@SuppressWarnings("unchecked")
public void setup() throws Exception {
stringHttpMessageConverter = mock(HttpMessageConverter.class);
given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
resourceMessageConverter = mock(HttpMessageConverter.class);
given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
resourceRegionMessageConverter = mock(HttpMessageConverter.class);
given(resourceRegionMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
processor = new HttpEntityMethodProcessor(
Arrays.asList(stringHttpMessageConverter, resourceMessageConverter, resourceRegionMessageConverter));
stringHttpMessageConverter = mock(HttpMessageConverter.class);
given(stringHttpMessageConverter.getSupportedMediaTypes())
.willReturn(Collections.singletonList(TEXT_PLAIN));
resourceMessageConverter = mock(HttpMessageConverter.class);
given(resourceMessageConverter.getSupportedMediaTypes())
.willReturn(Collections.singletonList(MediaType.ALL));
resourceRegionMessageConverter = mock(HttpMessageConverter.class);
given(resourceRegionMessageConverter.getSupportedMediaTypes())
.willReturn(Collections.singletonList(MediaType.ALL));
processor = new HttpEntityMethodProcessor(Arrays.asList(
stringHttpMessageConverter, resourceMessageConverter, resourceRegionMessageConverter));
Method handle1 = getClass().getMethod("handle1", HttpEntity.class, ResponseEntity.class,
Integer.TYPE, RequestEntity.class);
@@ -168,7 +177,7 @@ public class HttpEntityMethodProcessorMockTests {
public void shouldResolveHttpEntityArgument() throws Exception {
String body = "Foo";
MediaType contentType = MediaType.TEXT_PLAIN;
MediaType contentType = TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString());
servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));
@@ -186,7 +195,7 @@ public class HttpEntityMethodProcessorMockTests {
public void shouldResolveRequestEntityArgument() throws Exception {
String body = "Foo";
MediaType contentType = MediaType.TEXT_PLAIN;
MediaType contentType = TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString());
servletRequest.setMethod("GET");
servletRequest.setServerName("www.example.com");
@@ -204,13 +213,14 @@ public class HttpEntityMethodProcessorMockTests {
RequestEntity<?> requestEntity = (RequestEntity<?>) result;
assertEquals("Invalid method", HttpMethod.GET, requestEntity.getMethod());
// using default port (which is 80), so do not need to append the port (-1 means ignore)
assertEquals("Invalid url", new URI("http", null, "www.example.com", -1, "/path", null, null), requestEntity.getUrl());
URI uri = new URI("http", null, "www.example.com", -1, "/path", null, null);
assertEquals("Invalid url", uri, requestEntity.getUrl());
assertEquals("Invalid argument", body, requestEntity.getBody());
}
@Test
public void shouldFailResolvingWhenConverterCannotRead() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
MediaType contentType = TEXT_PLAIN;
servletRequest.setMethod("POST");
servletRequest.addHeader("Content-Type", contentType.toString());
@@ -233,7 +243,7 @@ public class HttpEntityMethodProcessorMockTests {
public void shouldHandleReturnValue() throws Exception {
String body = "Foo";
ResponseEntity<String> returnValue = new ResponseEntity<>(body, HttpStatus.OK);
MediaType accepted = MediaType.TEXT_PLAIN;
MediaType accepted = TEXT_PLAIN;
servletRequest.addHeader("Accept", accepted.toString());
initStringMessageConversion(accepted);
@@ -287,7 +297,8 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader("Accept", accepted.toString());
given(stringHttpMessageConverter.canWrite(String.class, null)).willReturn(true);
given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(stringHttpMessageConverter.getSupportedMediaTypes())
.willReturn(Collections.singletonList(TEXT_PLAIN));
this.thrown.expect(HttpMediaTypeNotAcceptableException.class);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
@@ -297,11 +308,12 @@ public class HttpEntityMethodProcessorMockTests {
public void shouldFailHandlingWhenConverterCannotWrite() throws Exception {
String body = "Foo";
ResponseEntity<String> returnValue = new ResponseEntity<>(body, HttpStatus.OK);
MediaType accepted = MediaType.TEXT_PLAIN;
MediaType accepted = TEXT_PLAIN;
servletRequest.addHeader("Accept", accepted.toString());
given(stringHttpMessageConverter.canWrite(String.class, null)).willReturn(true);
given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(stringHttpMessageConverter.getSupportedMediaTypes())
.willReturn(Collections.singletonList(TEXT_PLAIN));
given(stringHttpMessageConverter.canWrite(String.class, accepted)).willReturn(false);
this.thrown.expect(HttpMediaTypeNotAcceptableException.class);
@@ -335,11 +347,11 @@ public class HttpEntityMethodProcessorMockTests {
responseHeaders.set("header", "headerValue");
ResponseEntity<String> returnValue = new ResponseEntity<>("body", responseHeaders, HttpStatus.ACCEPTED);
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
ArgumentCaptor<HttpOutputMessage> outputMessage = ArgumentCaptor.forClass(HttpOutputMessage.class);
verify(stringHttpMessageConverter).write(eq("body"), eq(MediaType.TEXT_PLAIN), outputMessage.capture());
verify(stringHttpMessageConverter).write(eq("body"), eq(TEXT_PLAIN), outputMessage.capture());
assertTrue(mavContainer.isRequestHandled());
assertEquals("headerValue", outputMessage.getValue().getHeaders().get("header").get(0));
}
@@ -348,10 +360,11 @@ public class HttpEntityMethodProcessorMockTests {
public void shouldHandleLastModifiedWithHttp304() throws Exception {
long currentTime = new Date().getTime();
long oneMinuteAgo = currentTime - (1000 * 60);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, RFC_1123_DATE_TIME.format(ofEpochMilli(currentTime).atZone(GMT)));
ZonedDateTime dateTime = ofEpochMilli(currentTime).atZone(GMT);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, RFC_1123_DATE_TIME.format(dateTime));
ResponseEntity<String> returnValue = ResponseEntity.ok().lastModified(oneMinuteAgo).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, null, oneMinuteAgo);
@@ -363,7 +376,7 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(etagValue).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, etagValue, -1);
@@ -375,7 +388,7 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, "unquoted");
ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(etagValue).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.OK, "body", etagValue, -1);
@@ -386,11 +399,13 @@ public class HttpEntityMethodProcessorMockTests {
long currentTime = new Date().getTime();
long oneMinuteAgo = currentTime - (1000 * 60);
String etagValue = "\"deadb33f8badf00d\"";
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, RFC_1123_DATE_TIME.format(ofEpochMilli(currentTime).atZone(GMT)));
ZonedDateTime dateTime = ofEpochMilli(currentTime).atZone(GMT);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, RFC_1123_DATE_TIME.format(dateTime));
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(etagValue).lastModified(oneMinuteAgo).body("body");
ResponseEntity<String> returnValue = ResponseEntity.ok()
.eTag(etagValue).lastModified(oneMinuteAgo).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, etagValue, oneMinuteAgo);
@@ -404,7 +419,7 @@ public class HttpEntityMethodProcessorMockTests {
ResponseEntity<String> returnValue = ResponseEntity.status(HttpStatus.NOT_MODIFIED)
.eTag(etagValue).lastModified(oneMinuteAgo).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, etagValue, oneMinuteAgo);
@@ -416,12 +431,13 @@ public class HttpEntityMethodProcessorMockTests {
long oneMinuteAgo = currentTime - (1000 * 60);
String etagValue = "\"deadb33f8badf00d\"";
String changedEtagValue = "\"changed-etag-value\"";
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, RFC_1123_DATE_TIME.format(ofEpochMilli(currentTime).atZone(GMT)));
ZonedDateTime dateTime = ofEpochMilli(currentTime).atZone(GMT);
servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, RFC_1123_DATE_TIME.format(dateTime));
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
ResponseEntity<String> returnValue = ResponseEntity.ok()
.eTag(changedEtagValue).lastModified(oneMinuteAgo).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.OK, null, changedEtagValue, oneMinuteAgo);
@@ -435,7 +451,7 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, wildcardValue);
ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(etagValue).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.OK, "body", etagValue, -1);
@@ -448,7 +464,7 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, wildcardValue);
ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(etagValue).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.OK, "body", etagValue, -1);
@@ -461,7 +477,7 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader(HttpHeaders.IF_MATCH, "ifmatch");
ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(etagValue).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, etagValue, -1);
@@ -471,10 +487,11 @@ public class HttpEntityMethodProcessorMockTests {
public void shouldHandleIfNoneMatchIfUnmodifiedSince() throws Exception {
String etagValue = "\"some-etag\"";
servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
servletRequest.addHeader(HttpHeaders.IF_UNMODIFIED_SINCE, RFC_1123_DATE_TIME.format(ofEpochMilli(new Date().getTime()).atZone(GMT)));
ZonedDateTime dateTime = ofEpochMilli(new Date().getTime()).atZone(GMT);
servletRequest.addHeader(HttpHeaders.IF_UNMODIFIED_SINCE, RFC_1123_DATE_TIME.format(dateTime));
ResponseEntity<String> returnValue = ResponseEntity.ok().eTag(etagValue).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.NOT_MODIFIED, null, etagValue, -1);
@@ -487,12 +504,12 @@ public class HttpEntityMethodProcessorMockTests {
given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true);
given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
given(resourceMessageConverter.canWrite(ByteArrayResource.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(true);
given(resourceMessageConverter.canWrite(ByteArrayResource.class, APPLICATION_OCTET_STREAM)).willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest);
then(resourceMessageConverter).should(times(1)).write(any(ByteArrayResource.class),
eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
then(resourceMessageConverter).should(times(1)).write(
any(ByteArrayResource.class), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
assertEquals(200, servletResponse.getStatus());
}
@@ -503,12 +520,12 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader("Range", "bytes=0-5");
given(resourceRegionMessageConverter.canWrite(any(), eq(null))).willReturn(true);
given(resourceRegionMessageConverter.canWrite(any(), eq(MediaType.APPLICATION_OCTET_STREAM))).willReturn(true);
given(resourceRegionMessageConverter.canWrite(any(), eq(APPLICATION_OCTET_STREAM))).willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest);
then(resourceRegionMessageConverter).should(times(1)).write(
anyCollection(), eq(MediaType.APPLICATION_OCTET_STREAM),
anyCollection(), eq(APPLICATION_OCTET_STREAM),
argThat(outputMessage -> outputMessage.getHeaders().getFirst(HttpHeaders.ACCEPT_RANGES) == "bytes"));
assertEquals(206, servletResponse.getStatus());
}
@@ -520,12 +537,12 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.addHeader("Range", "illegal");
given(resourceRegionMessageConverter.canWrite(any(), eq(null))).willReturn(true);
given(resourceRegionMessageConverter.canWrite(any(), eq(MediaType.APPLICATION_OCTET_STREAM))).willReturn(true);
given(resourceRegionMessageConverter.canWrite(any(), eq(APPLICATION_OCTET_STREAM))).willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResponseEntityResource, mavContainer, webRequest);
then(resourceRegionMessageConverter).should(never()).write(
anyCollection(), eq(MediaType.APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
anyCollection(), eq(APPLICATION_OCTET_STREAM), any(HttpOutputMessage.class));
assertEquals(416, servletResponse.getStatus());
}
@@ -535,7 +552,7 @@ public class HttpEntityMethodProcessorMockTests {
String etagValue = "\"some-etag\"";
ResponseEntity<String> returnValue = ResponseEntity.ok().header(HttpHeaders.ETAG, etagValue).body("body");
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertConditionalResponse(HttpStatus.OK, "body", etagValue, -1);
@@ -587,26 +604,28 @@ public class HttpEntityMethodProcessorMockTests {
for (String value : existingValues) {
servletResponse.addHeader("Vary", value);
}
initStringMessageConversion(MediaType.TEXT_PLAIN);
initStringMessageConversion(TEXT_PLAIN);
processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);
assertTrue(mavContainer.isRequestHandled());
assertEquals(Arrays.asList(expected), servletResponse.getHeaders("Vary"));
verify(stringHttpMessageConverter).write(eq("Foo"), eq(MediaType.TEXT_PLAIN), isA(HttpOutputMessage.class));
verify(stringHttpMessageConverter).write(eq("Foo"), eq(TEXT_PLAIN), isA(HttpOutputMessage.class));
}
private void initStringMessageConversion(MediaType accepted) {
given(stringHttpMessageConverter.canWrite(String.class, null)).willReturn(true);
given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(TEXT_PLAIN));
given(stringHttpMessageConverter.canWrite(String.class, accepted)).willReturn(true);
}
private void assertResponseBody(String body) throws Exception {
ArgumentCaptor<HttpOutputMessage> outputMessage = ArgumentCaptor.forClass(HttpOutputMessage.class);
verify(stringHttpMessageConverter).write(eq(body), eq(MediaType.TEXT_PLAIN), outputMessage.capture());
verify(stringHttpMessageConverter).write(eq(body), eq(TEXT_PLAIN), outputMessage.capture());
}
private void assertConditionalResponse(HttpStatus status, String body, String etag, long lastModified) throws Exception {
private void assertConditionalResponse(HttpStatus status, String body, String etag,
long lastModified) throws Exception {
assertEquals(status.value(), servletResponse.getStatus());
assertTrue(mavContainer.isRequestHandled());
if (body != null) {
@@ -621,7 +640,8 @@ public class HttpEntityMethodProcessorMockTests {
}
if (lastModified != -1) {
assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size());
assertEquals(RFC_1123_DATE_TIME.format(ofEpochMilli(lastModified).atZone(GMT)), servletResponse.getHeader(HttpHeaders.LAST_MODIFIED));
assertEquals(RFC_1123_DATE_TIME.format(ofEpochMilli(lastModified).atZone(GMT)),
servletResponse.getHeader(HttpHeaders.LAST_MODIFIED));
}
}

View File

@@ -126,7 +126,8 @@ public class ReactiveTypeHandlerTests {
// RxJava 2 Single
AtomicReference<io.reactivex.SingleEmitter<String>> ref2 = new AtomicReference<>();
io.reactivex.Single<String> single2 = io.reactivex.Single.create(ref2::set);
testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class), () -> ref2.get().onSuccess("foo"), "foo");
testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class),
() -> ref2.get().onSuccess("foo"), "foo");
}
@Test
@@ -169,7 +170,8 @@ public class ReactiveTypeHandlerTests {
// RxJava 2 Single
AtomicReference<io.reactivex.SingleEmitter<String>> ref2 = new AtomicReference<>();
io.reactivex.Single<String> single2 = io.reactivex.Single.create(ref2::set);
testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class), () -> ref2.get().onError(ex), ex);
testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class),
() -> ref2.get().onError(ex), ex);
}
@Test

View File

@@ -103,7 +103,7 @@ public class RequestPartMethodArgumentResolverTests {
messageConverter = mock(HttpMessageConverter.class);
given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
resolver = new RequestPartMethodArgumentResolver(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
resolver = new RequestPartMethodArgumentResolver(Collections.singletonList(messageConverter));
reset(messageConverter);
byte[] content = "doesn't matter as long as not empty".getBytes(StandardCharsets.UTF_8);
@@ -492,7 +492,8 @@ public class RequestPartMethodArgumentResolverTests {
ModelAndViewContainer mavContainer = new ModelAndViewContainer();
Object actualValue = resolver.resolveArgument(optionalRequestPart, mavContainer, webRequest, new ValidatingBinderFactory());
Object actualValue = resolver.resolveArgument(
optionalRequestPart, mavContainer, webRequest, new ValidatingBinderFactory());
assertEquals("Invalid argument value", Optional.of(simpleBean), actualValue);
assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
@@ -558,7 +559,9 @@ public class RequestPartMethodArgumentResolverTests {
private final class ValidatingBinderFactory implements WebDataBinderFactory {
@Override
public WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target, String objectName) throws Exception {
public WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target,
String objectName) throws Exception {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
WebDataBinder dataBinder = new WebDataBinder(target, objectName);

View File

@@ -150,7 +150,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
given(stringMessageConverter.canRead(String.class, contentType)).willReturn(true);
given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);
Object result = processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory());
Object result = processor.resolveArgument(paramRequestBodyString, mavContainer,
webRequest, new ValidatingBinderFactory());
assertEquals("Invalid argument", body, result);
assertFalse("The requestHandled flag shouldn't change", mavContainer.isRequestHandled());
@@ -185,7 +186,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
given(beanConverter.canRead(SimpleBean.class, contentType)).willReturn(true);
given(beanConverter.read(eq(SimpleBean.class), isA(HttpInputMessage.class))).willReturn(simpleBean);
processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(beanConverter));
processor = new RequestResponseBodyMethodProcessor(Collections.singletonList(beanConverter));
processor.resolveArgument(paramValidBean, mavContainer, webRequest, new ValidatingBinderFactory());
}
@@ -220,7 +221,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.setContent(new byte[0]);
given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(null);
assertNull(processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, new ValidatingBinderFactory()));
assertNull(processor.resolveArgument(paramRequestBodyString, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test
@@ -228,7 +230,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.setMethod("GET");
servletRequest.setContent(new byte[0]);
given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false);
assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory()));
assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test
@@ -237,7 +240,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.setContent("body".getBytes());
given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn("body");
assertEquals("body", processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory()));
assertEquals("body", processor.resolveArgument(paramStringNotRequired, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test
@@ -245,7 +249,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.setContentType("text/plain");
servletRequest.setContent(new byte[0]);
given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory()));
assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test // SPR-13417
@@ -253,7 +258,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.setContent(new byte[0]);
given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false);
assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory()));
assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test
@@ -262,7 +268,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.setContent("body".getBytes());
given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn("body");
assertEquals(Optional.of("body"), processor.resolveArgument(paramOptionalString, mavContainer, webRequest, new ValidatingBinderFactory()));
assertEquals(Optional.of("body"), processor.resolveArgument(paramOptionalString, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test
@@ -278,7 +285,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.setContent(new byte[0]);
given(stringMessageConverter.canRead(String.class, MediaType.TEXT_PLAIN)).willReturn(true);
given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false);
assertEquals(Optional.empty(), processor.resolveArgument(paramOptionalString, mavContainer, webRequest, new ValidatingBinderFactory()));
assertEquals(Optional.empty(), processor.resolveArgument(paramOptionalString, mavContainer,
webRequest, new ValidatingBinderFactory()));
}
@Test
@@ -302,7 +310,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
String body = "Foo";
servletRequest.addHeader("Accept", "text/*");
servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(MediaType.TEXT_HTML));
servletRequest.setAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE,
Collections.singleton(MediaType.TEXT_HTML));
given(stringMessageConverter.canWrite(String.class, MediaType.TEXT_HTML)).willReturn(true);
@@ -343,7 +352,8 @@ public class RequestResponseBodyMethodProcessorMockTests {
given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true);
given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));
given(resourceMessageConverter.canWrite(ByteArrayResource.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(true);
given(resourceMessageConverter.canWrite(ByteArrayResource.class, MediaType.APPLICATION_OCTET_STREAM))
.willReturn(true);
processor.handleReturnValue(returnValue, returnTypeResource, mavContainer, webRequest);
@@ -441,7 +451,9 @@ public class RequestResponseBodyMethodProcessorMockTests {
private final class ValidatingBinderFactory implements WebDataBinderFactory {
@Override
public WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target, String objectName) throws Exception {
public WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target,
String objectName) throws Exception {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.afterPropertiesSet();
WebDataBinder dataBinder = new WebDataBinder(target, objectName);

View File

@@ -560,7 +560,10 @@ public class RequestResponseBodyMethodProcessorTests {
@Test // SPR-12501
public void resolveArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
String content = "<root><withView1>with</withView1><withView2>with</withView2><withoutView>without</withoutView></root>";
String content = "<root>" +
"<withView1>with</withView1>" +
"<withView2>with</withView2>" +
"<withoutView>without</withoutView></root>";
this.servletRequest.setContent(content.getBytes("UTF-8"));
this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);
@@ -586,7 +589,10 @@ public class RequestResponseBodyMethodProcessorTests {
@Test // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonViewAndXmlMessageConverter() throws Exception {
String content = "<root><withView1>with</withView1><withView2>with</withView2><withoutView>without</withoutView></root>";
String content = "<root>" +
"<withView1>with</withView1>" +
"<withView2>with</withView2>" +
"<withoutView>without</withoutView></root>";
this.servletRequest.setContent(content.getBytes("UTF-8"));
this.servletRequest.setContentType(MediaType.APPLICATION_XML_VALUE);

View File

@@ -626,7 +626,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
@Test
public void binderInitializingCommandProvidingFormController() throws Exception {
initServlet(wac -> wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)), MyBinderInitializingCommandProvidingFormController.class);
initServlet(wac -> wac.registerBeanDefinition("viewResolver",
new RootBeanDefinition(TestViewResolver.class)),
MyBinderInitializingCommandProvidingFormController.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
request.addParameter("defaultName", "myDefaultName");
@@ -639,7 +641,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
@Test
public void specificBinderInitializingCommandProvidingFormController() throws Exception {
initServlet(wac -> wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)), MySpecificBinderInitializingCommandProvidingFormController.class);
initServlet(wac -> wac.registerBeanDefinition("viewResolver",
new RootBeanDefinition(TestViewResolver.class)),
MySpecificBinderInitializingCommandProvidingFormController.class);
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do");
request.addParameter("defaultName", "myDefaultName");
@@ -2000,12 +2004,16 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
@InitBinder
public void initBinder(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) {
public void initBinder(@RequestParam("param1") String p1,
@RequestParam(value="paramX", required=false) String px, int param2) {
assertNull(px);
}
@ModelAttribute
public void modelAttribute(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) {
public void modelAttribute(@RequestParam("param1") String p1,
@RequestParam(value="paramX", required=false) String px, int param2) {
assertNull(px);
}
}
@@ -2036,13 +2044,17 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
@Override
@InitBinder
public void initBinder(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) {
public void initBinder(@RequestParam("param1") String p1,
@RequestParam(value="paramX", required=false) String px, int param2) {
assertNull(px);
}
@Override
@ModelAttribute
public void modelAttribute(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) {
public void modelAttribute(@RequestParam("param1") String p1,
@RequestParam(value="paramX", required=false) String px, int param2) {
assertNull(px);
}
}
@@ -2154,7 +2166,8 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
@Controller
public static class MyParameterizedControllerImplWithOverriddenMappings implements MyEditableParameterizedControllerIfc<TestBean> {
public static class MyParameterizedControllerImplWithOverriddenMappings
implements MyEditableParameterizedControllerIfc<TestBean> {
@Override
@ModelAttribute("testBeanList")
@@ -2251,7 +2264,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute(name="myCommand", binding=true) TestBean tb, BindingResult errors, ModelMap model) {
public String myHandle(@ModelAttribute(name="myCommand", binding=true) TestBean tb,
BindingResult errors, ModelMap model) {
FieldError error = errors.getFieldError("age");
assertNotNull("Must have field error for age property", error);
assertEquals("value2", error.getRejectedValue());
@@ -2266,7 +2281,9 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
static class MyCommandProvidingFormController<T, TB, TB2> extends MyFormController {
@ModelAttribute("myCommand")
public ValidTestBean createTestBean(@RequestParam T defaultName, Map<String, Object> model, @RequestParam Date date) {
public ValidTestBean createTestBean(@RequestParam T defaultName, Map<String, Object> model,
@RequestParam Date date) {
model.put("myKey", "myOriginalValue");
ValidTestBean tb = new ValidTestBean();
tb.setName(defaultName.getClass().getSimpleName() + ":" + defaultName.toString());
@@ -3264,12 +3281,16 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl
}
@RequestMapping("/singleString")
public void processMultipart(@RequestParam("content") String content, HttpServletResponse response) throws IOException {
public void processMultipart(@RequestParam("content") String content,
HttpServletResponse response) throws IOException {
response.getWriter().write(content);
}
@RequestMapping("/stringArray")
public void processMultipart(@RequestParam("content") String[] content, HttpServletResponse response) throws IOException {
public void processMultipart(@RequestParam("content") String[] content,
HttpServletResponse response) throws IOException {
response.getWriter().write(StringUtils.arrayToDelimitedString(content, "-"));
}
}

View File

@@ -54,7 +54,8 @@ public class UriComponentsBuilderMethodArgumentResolverTests {
this.servletRequest = new MockHttpServletRequest();
this.webRequest = new ServletWebRequest(this.servletRequest);
Method method = this.getClass().getDeclaredMethod("handle", UriComponentsBuilder.class, ServletUriComponentsBuilder.class, int.class);
Method method = this.getClass().getDeclaredMethod(
"handle", UriComponentsBuilder.class, ServletUriComponentsBuilder.class, int.class);
this.builderParam = new MethodParameter(method, 0);
this.servletBuilderParam = new MethodParameter(method, 1);
this.intParam = new MethodParameter(method, 2);

View File

@@ -620,7 +620,8 @@ public class ResourceHttpRequestHandlerTests {
private long dateHeaderAsLong(String responseHeaderName) throws Exception {
return ZonedDateTime.parse(this.response.getHeader(responseHeaderName), RFC_1123_DATE_TIME).toInstant().toEpochMilli();
String header = this.response.getHeader(responseHeaderName);
return ZonedDateTime.parse(header, RFC_1123_DATE_TIME).toInstant().toEpochMilli();
}
private long resourceLastModified(String resourceName) throws IOException {

View File

@@ -21,6 +21,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
@@ -175,11 +176,12 @@ public class VersionResourceResolverTests {
this.resolver.addFixedVersionStrategy("fixedversion", "/js/**", "/css/**", "/fixedversion/css/**");
Matcher<VersionStrategy> matcher = Matchers.instanceOf(FixedVersionStrategy.class);
assertThat(this.resolver.getStrategyMap().size(), is(4));
assertThat(this.resolver.getStrategyForPath("js/something.js"), Matchers.instanceOf(FixedVersionStrategy.class));
assertThat(this.resolver.getStrategyForPath("fixedversion/js/something.js"), Matchers.instanceOf(FixedVersionStrategy.class));
assertThat(this.resolver.getStrategyForPath("css/something.css"), Matchers.instanceOf(FixedVersionStrategy.class));
assertThat(this.resolver.getStrategyForPath("fixedversion/css/something.css"), Matchers.instanceOf(FixedVersionStrategy.class));
assertThat(this.resolver.getStrategyForPath("js/something.js"), matcher);
assertThat(this.resolver.getStrategyForPath("fixedversion/js/something.js"), matcher);
assertThat(this.resolver.getStrategyForPath("css/something.css"), matcher);
assertThat(this.resolver.getStrategyForPath("fixedversion/css/something.css"), matcher);
}
@Test // SPR-15372

View File

@@ -113,8 +113,9 @@ public class AnnotationConfigDispatcherServletInitializerTests {
for (MockFilterRegistration filterRegistration : filterRegistrations.values()) {
assertTrue(filterRegistration.isAsyncSupported());
assertEquals(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE, DispatcherType.ASYNC),
filterRegistration.getMappings().get(SERVLET_NAME));
EnumSet<DispatcherType> enumSet = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
DispatcherType.INCLUDE, DispatcherType.ASYNC);
assertEquals(enumSet, filterRegistration.getMappings().get(SERVLET_NAME));
}
}

View File

@@ -282,7 +282,8 @@ public class FlashMapManagerTests {
this.flashMapManager.saveOutputFlashMap(flashMap, this.request, this.response);
MockHttpServletRequest requestAfterRedirect = new MockHttpServletRequest("GET", "/path");
requestAfterRedirect.setQueryString("param=%D0%90%D0%90&param=%D0%91%D0%91&param=%D0%92%D0%92&%3A%2F%3F%23%5B%5D%40=value");
requestAfterRedirect.setQueryString(
"param=%D0%90%D0%90&param=%D0%91%D0%91&param=%D0%92%D0%92&%3A%2F%3F%23%5B%5D%40=value");
requestAfterRedirect.addParameter("param", "\u0410\u0410");
requestAfterRedirect.addParameter("param", "\u0411\u0411");
requestAfterRedirect.addParameter("param", "\u0412\u0412");

View File

@@ -656,7 +656,8 @@ public class BindTagTests extends AbstractTagTests {
tag.setPageContext(pc);
tag.setName("tb");
assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
assertTrue("Has errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE) == errors);
assertTrue("Has errors variable",
pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE) == errors);
}
@Test

View File

@@ -29,6 +29,7 @@ import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockPageContext;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.support.JspAwareRequestContext;
import org.springframework.web.servlet.support.RequestContext;
@@ -68,8 +69,8 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
protected MockPageContext createAndPopulatePageContext() throws JspException {
MockPageContext pageContext = createPageContext();
MockHttpServletRequest request = (MockHttpServletRequest) pageContext.getRequest();
StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.findWebApplicationContext(request);
wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
((StaticWebApplicationContext) RequestContextUtils.findWebApplicationContext(request))
.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
extendRequest(request);
extendPageContext(pageContext);
RequestContext requestContext = new JspAwareRequestContext(pageContext);
@@ -106,7 +107,7 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
protected RequestDataValueProcessor getMockRequestDataValueProcessor() {
RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
HttpServletRequest request = (HttpServletRequest) getPageContext().getRequest();
StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.findWebApplicationContext(request);
WebApplicationContext wac = RequestContextUtils.findWebApplicationContext(request);
wac.getBean(RequestDataValueProcessorWrapper.class).setRequestDataValueProcessor(mockProcessor);
return mockProcessor;
}

View File

@@ -233,8 +233,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
String xssQueryString = QUERY_STRING + "&stuff=\"><script>alert('XSS!')</script>";
request.setQueryString(xssQueryString);
tag.doStartTag();
assertEquals("<form id=\"command\" action=\"/my/form?foo=bar&amp;stuff=&quot;&gt;&lt;script&gt;alert(&#39;XSS!&#39;)&lt;/script&gt;\" method=\"post\">",
getOutput());
assertEquals("<form id=\"command\" action=\"/my/form?foo=bar&amp;stuff=&quot;&gt;&lt;" +
"script&gt;alert(&#39;XSS!&#39;)&lt;/script&gt;\" method=\"post\">", getOutput());
}
@Test

View File

@@ -63,7 +63,8 @@ public class OptionTagEnumTests extends AbstractHtmlElementTagTests {
testBean.setCustomEnum(CustomEnum.VALUE_1);
getPageContext().getRequest().setAttribute("testBean", testBean);
String selectName = "testBean.customEnum";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE,
new BindStatus(getRequestContext(), selectName, false));
this.tag.setValue("VALUE_1");

View File

@@ -79,7 +79,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
@Test
public void canBeDisabledEvenWhenSelected() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue("bar");
this.tag.setLabel("Bar");
this.tag.setDisabled(true);
@@ -100,7 +101,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
@Test
public void renderNotSelected() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue("bar");
this.tag.setLabel("Bar");
int result = this.tag.doStartTag();
@@ -122,7 +124,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
String dynamicAttribute2 = "attr2";
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue("bar");
this.tag.setLabel("Bar");
this.tag.setDynamicAttribute(null, dynamicAttribute1, dynamicAttribute1);
@@ -146,7 +149,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
@Test
public void renderSelected() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setId("myOption");
this.tag.setValue("foo");
this.tag.setLabel("Foo");
@@ -168,7 +172,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
@Test
public void withNoLabel() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue("bar");
this.tag.setCssClass("myClass");
this.tag.setOnclick("CLICK");
@@ -261,7 +266,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
@Test
public void withCustomObjectSelected() throws Exception {
String selectName = "testBean.someNumber";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue(new Float(12.34));
this.tag.setLabel("GBP 12.34");
int result = this.tag.doStartTag();
@@ -281,7 +287,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
@Test
public void withCustomObjectNotSelected() throws Exception {
String selectName = "testBean.someNumber";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
this.tag.setValue(new Float(12.35));
this.tag.setLabel("GBP 12.35");
int result = this.tag.doStartTag();

View File

@@ -495,8 +495,10 @@ public class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals(2, rootElement.elements().size());
Node value1 = rootElement.selectSingleNode("//input[@value = 'VALUE_1']");
Node value2 = rootElement.selectSingleNode("//input[@value = 'VALUE_2']");
assertEquals("TestEnum: VALUE_1", rootElement.selectSingleNode("//label[@for = '" + value1.valueOf("@id") + "']").getText());
assertEquals("TestEnum: VALUE_2", rootElement.selectSingleNode("//label[@for = '" + value2.valueOf("@id") + "']").getText());
assertEquals("TestEnum: VALUE_1",
rootElement.selectSingleNode("//label[@for = '" + value1.valueOf("@id") + "']").getText());
assertEquals("TestEnum: VALUE_2",
rootElement.selectSingleNode("//label[@for = '" + value2.valueOf("@id") + "']").getText());
assertEquals(value2, rootElement.selectSingleNode("//input[@checked]"));
}
@@ -520,8 +522,10 @@ public class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals(2, rootElement.elements().size());
Node value1 = rootElement.selectSingleNode("//input[@value = 'Value: VALUE_1']");
Node value2 = rootElement.selectSingleNode("//input[@value = 'Value: VALUE_2']");
assertEquals("Label: VALUE_1", rootElement.selectSingleNode("//label[@for = '" + value1.valueOf("@id") + "']").getText());
assertEquals("Label: VALUE_2", rootElement.selectSingleNode("//label[@for = '" + value2.valueOf("@id") + "']").getText());
assertEquals("Label: VALUE_1",
rootElement.selectSingleNode("//label[@for = '" + value1.valueOf("@id") + "']").getText());
assertEquals("Label: VALUE_2",
rootElement.selectSingleNode("//label[@for = '" + value2.valueOf("@id") + "']").getText());
assertEquals(value2, rootElement.selectSingleNode("//input[@checked]"));
}

View File

@@ -99,7 +99,8 @@ public class TagWriterTests {
}
this.writer.endTag();
assertEquals("<span class=\"highlight\"><strong>Rob</strong> <emphasis>Harrop</emphasis></span>", this.data.toString());
assertEquals("<span class=\"highlight\"><strong>Rob</strong> <emphasis>Harrop</emphasis></span>",
this.data.toString());
}
@Test

View File

@@ -293,7 +293,9 @@ public class BaseViewTests {
private static class ConcreteView extends AbstractView {
// Do-nothing concrete subclass
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
throw new UnsupportedOperationException();
}

View File

@@ -56,9 +56,12 @@ public class RssFeedViewTests {
view.render(model, request, response);
assertEquals("Invalid content-type", "application/rss+xml", response.getContentType());
String expected = "<rss version=\"2.0\">" +
"<channel><title>Test Feed</title><link>http://example.com</link><description>Test feed description</description>" +
"<channel><title>Test Feed</title>" +
"<link>http://example.com</link>" +
"<description>Test feed description</description>" +
"<item><title>2</title><description>This is entry 2</description></item>" +
"<item><title>1</title><description>This is entry 1</description></item>" + "</channel></rss>";
"<item><title>1</title><description>This is entry 1</description></item>" +
"</channel></rss>";
assertThat(response.getContentAsString(), isSimilarTo(expected).ignoreWhitespace());
}
@@ -73,7 +76,9 @@ public class RssFeedViewTests {
}
@Override
protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
protected List<Item> buildFeedItems(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Item> items = new ArrayList<>();
for (String name : model.keySet()) {
Item item = new Item();

View File

@@ -260,20 +260,26 @@ public class FreeMarkerMacroTests {
@Test
public void testForm16() throws Exception {
String output = getMacroOutput("FORM16");
assertTrue("Wrong output: " + output, output.startsWith("<input type=\"hidden\" name=\"_jedi\" value=\"on\"/>"));
assertTrue("Wrong output: " + output, output.contains("<input type=\"checkbox\" id=\"jedi\" name=\"jedi\" checked=\"checked\" />"));
assertTrue("Wrong output: " + output, output.startsWith(
"<input type=\"hidden\" name=\"_jedi\" value=\"on\"/>"));
assertTrue("Wrong output: " + output, output.contains(
"<input type=\"checkbox\" id=\"jedi\" name=\"jedi\" checked=\"checked\" />"));
}
@Test
public void testForm17() throws Exception {
assertEquals("<input type=\"text\" id=\"spouses0.name\" name=\"spouses[0].name\" value=\"Fred\" >", getMacroOutput("FORM17"));
assertEquals(
"<input type=\"text\" id=\"spouses0.name\" name=\"spouses[0].name\" value=\"Fred\" >",
getMacroOutput("FORM17"));
}
@Test
public void testForm18() throws Exception {
String output = getMacroOutput("FORM18");
assertTrue("Wrong output: " + output, output.startsWith("<input type=\"hidden\" name=\"_spouses[0].jedi\" value=\"on\"/>"));
assertTrue("Wrong output: " + output, output.contains("<input type=\"checkbox\" id=\"spouses0.jedi\" name=\"spouses[0].jedi\" checked=\"checked\" />"));
assertTrue("Wrong output: " + output, output.startsWith(
"<input type=\"hidden\" name=\"_spouses[0].jedi\" value=\"on\"/>"));
assertTrue("Wrong output: " + output, output.contains(
"<input type=\"checkbox\" id=\"spouses0.jedi\" name=\"spouses[0].jedi\" checked=\"checked\" />"));
}

View File

@@ -158,7 +158,9 @@ public class GroovyMarkupViewTests {
}
private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String, Object> model, Locale locale) throws Exception {
private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String,
Object> model, Locale locale) throws Exception {
GroovyMarkupView view = createViewWithUrl(viewUrl);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();

View File

@@ -60,12 +60,13 @@ public class JRubyScriptTemplateTests {
Map<String, Object> model = new HashMap<>();
model.put("title", "Layout example");
model.put("body", "This is the body");
MockHttpServletResponse response = renderViewWithModel("org/springframework/web/servlet/view/script/jruby/template.erb", model);
String url = "org/springframework/web/servlet/view/script/jruby/template.erb";
MockHttpServletResponse response = render(url, model);
assertEquals("<html><head><title>Layout example</title></head><body><p>This is the body</p></body></html>",
response.getContentAsString());
}
private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String, Object> model) throws Exception {
private MockHttpServletResponse render(String viewUrl, Map<String, Object> model) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();

View File

@@ -57,12 +57,13 @@ public class JythonScriptTemplateTests {
Map<String, Object> model = new HashMap<>();
model.put("title", "Layout example");
model.put("body", "This is the body");
MockHttpServletResponse response = renderViewWithModel("org/springframework/web/servlet/view/script/jython/template.html", model);
String url = "org/springframework/web/servlet/view/script/jython/template.html";
MockHttpServletResponse response = render(url, model);
assertEquals("<html><head><title>Layout example</title></head><body><p>This is the body</p></body></html>",
response.getContentAsString());
}
private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String, Object> model) throws Exception {
private MockHttpServletResponse render(String viewUrl, Map<String, Object> model) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();

View File

@@ -62,20 +62,18 @@ public class KotlinScriptTemplateTests {
public void renderTemplateWithFrenchLocale() throws Exception {
Map<String, Object> model = new HashMap<>();
model.put("foo", "Foo");
MockHttpServletResponse response = renderViewWithModel("org/springframework/web/servlet/view/script/kotlin/template.kts",
model, Locale.FRENCH, ScriptTemplatingConfiguration.class);
assertEquals("<html><body>\n<p>Bonjour Foo</p>\n</body></html>",
response.getContentAsString());
String url = "org/springframework/web/servlet/view/script/kotlin/template.kts";
MockHttpServletResponse response = render(url, model, Locale.FRENCH, ScriptTemplatingConfiguration.class);
assertEquals("<html><body>\n<p>Bonjour Foo</p>\n</body></html>", response.getContentAsString());
}
@Test
public void renderTemplateWithEnglishLocale() throws Exception {
Map<String, Object> model = new HashMap<>();
model.put("foo", "Foo");
MockHttpServletResponse response = renderViewWithModel("org/springframework/web/servlet/view/script/kotlin/template.kts",
model, Locale.ENGLISH, ScriptTemplatingConfiguration.class);
assertEquals("<html><body>\n<p>Hello Foo</p>\n</body></html>",
response.getContentAsString());
String url = "org/springframework/web/servlet/view/script/kotlin/template.kts";
MockHttpServletResponse response = render(url, model, Locale.ENGLISH, ScriptTemplatingConfiguration.class);
assertEquals("<html><body>\n<p>Hello Foo</p>\n</body></html>", response.getContentAsString());
}
@Test
@@ -85,14 +83,16 @@ public class KotlinScriptTemplateTests {
model.put("hello", "Hello");
model.put("foo", "Foo");
model.put("footer", "</body></html>");
MockHttpServletResponse response = renderViewWithModel("org/springframework/web/servlet/view/script/kotlin/eval.kts",
MockHttpServletResponse response = render("org/springframework/web/servlet/view/script/kotlin/eval.kts",
model, Locale.ENGLISH, ScriptTemplatingConfigurationWithoutRenderFunction.class);
assertEquals("<html><body>\n<p>Hello Foo</p>\n</body></html>",
response.getContentAsString());
}
private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String, Object> model, Locale locale, Class<?> configuration) throws Exception {
private MockHttpServletResponse render(String viewUrl, Map<String, Object> model,
Locale locale, Class<?> configuration) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl, configuration);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();

View File

@@ -57,21 +57,23 @@ public class NashornScriptTemplateTests {
Map<String, Object> model = new HashMap<>();
model.put("title", "Layout example");
model.put("body", "This is the body");
MockHttpServletResponse response = renderViewWithModel("org/springframework/web/servlet/view/script/nashorn/template.html",
model, ScriptTemplatingConfiguration.class);
String url = "org/springframework/web/servlet/view/script/nashorn/template.html";
MockHttpServletResponse response = render(url, model, ScriptTemplatingConfiguration.class);
assertEquals("<html><head><title>Layout example</title></head><body><p>This is the body</p></body></html>",
response.getContentAsString());
}
@Test // SPR-13453
public void renderTemplateWithUrl() throws Exception {
MockHttpServletResponse response = renderViewWithModel("org/springframework/web/servlet/view/script/nashorn/template.html",
null, ScriptTemplatingWithUrlConfiguration.class);
assertEquals("<html><head><title>Check url parameter</title></head><body><p>org/springframework/web/servlet/view/script/nashorn/template.html</p></body></html>",
String url = "org/springframework/web/servlet/view/script/nashorn/template.html";
MockHttpServletResponse response = render(url, null, ScriptTemplatingWithUrlConfiguration.class);
assertEquals("<html><head><title>Check url parameter</title></head><body><p>" + url + "</p></body></html>",
response.getContentAsString());
}
private MockHttpServletResponse renderViewWithModel(String viewUrl, Map<String, Object> model, Class<?> configuration) throws Exception {
private MockHttpServletResponse render(String viewUrl, Map<String, Object> model,
Class<?> configuration) throws Exception {
ScriptTemplateView view = createViewWithUrl(viewUrl, configuration);
MockHttpServletResponse response = new MockHttpServletResponse();
MockHttpServletRequest request = new MockHttpServletRequest();