Search in sources :

Example 11 with MockHttpServletResponse

use of org.springframework.web.testfixture.servlet.MockHttpServletResponse in project spring-framework by spring-projects.

the class MvcUriComponentsBuilderTests method adaptRequestFromForwardedHeaders.

// SPR-16668
private void adaptRequestFromForwardedHeaders() throws Exception {
    MockFilterChain chain = new MockFilterChain();
    new ForwardedHeaderFilter().doFilter(this.request, new MockHttpServletResponse(), chain);
    HttpServletRequest adaptedRequest = (HttpServletRequest) chain.getRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(adaptedRequest));
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) ForwardedHeaderFilter(org.springframework.web.filter.ForwardedHeaderFilter) MockFilterChain(org.springframework.web.testfixture.servlet.MockFilterChain) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse)

Example 12 with MockHttpServletResponse

use of org.springframework.web.testfixture.servlet.MockHttpServletResponse in project spring-framework by spring-projects.

the class MvcNamespaceTests method testResources.

@Test
@SuppressWarnings("deprecation")
public void testResources() throws Exception {
    loadBeanDefinitions("mvc-config-resources.xml");
    HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class);
    assertThat(adapter).isNotNull();
    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    ContentNegotiationManager manager = mapping.getContentNegotiationManager();
    ResourceHttpRequestHandler handler = appContext.getBean(ResourceHttpRequestHandler.class);
    assertThat(handler).isNotNull();
    assertThat(handler.getContentNegotiationManager()).isSameAs(manager);
    SimpleUrlHandlerMapping resourceMapping = appContext.getBean(SimpleUrlHandlerMapping.class);
    assertThat(resourceMapping).isNotNull();
    assertThat(resourceMapping.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE - 1);
    BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
    assertThat(beanNameMapping).isNotNull();
    assertThat(beanNameMapping.getOrder()).isEqualTo(2);
    ResourceUrlProvider urlProvider = appContext.getBean(ResourceUrlProvider.class);
    assertThat(urlProvider).isNotNull();
    Map<String, MappedInterceptor> beans = appContext.getBeansOfType(MappedInterceptor.class);
    List<Class<?>> interceptors = beans.values().stream().map(mappedInterceptor -> mappedInterceptor.getInterceptor().getClass()).collect(Collectors.toList());
    assertThat(interceptors).contains(ConversionServiceExposingInterceptor.class, ResourceUrlProviderExposingInterceptor.class);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/resources/foo.css");
    request.setMethod("GET");
    HandlerExecutionChain chain = resourceMapping.getHandler(request);
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler() instanceof ResourceHttpRequestHandler).isTrue();
    MockHttpServletResponse response = new MockHttpServletResponse();
    for (HandlerInterceptor interceptor : chain.getInterceptorList()) {
        interceptor.preHandle(request, response, chain.getHandler());
    }
    ModelAndView mv = adapter.handle(request, response, chain.getHandler());
    assertThat((Object) mv).isNull();
}
Also used : MappedInterceptor(org.springframework.web.servlet.handler.MappedInterceptor) BeforeEach(org.junit.jupiter.api.BeforeEach) LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) RequestParam(org.springframework.web.bind.annotation.RequestParam) Validator(org.springframework.validation.Validator) ResourceUrlProvider(org.springframework.web.servlet.resource.ResourceUrlProvider) InvocableHandlerMethod(org.springframework.web.method.support.InvocableHandlerMethod) LocaleResolver(org.springframework.web.servlet.LocaleResolver) CacheControl(org.springframework.http.CacheControl) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) MvcUriComponentsBuilder(org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder) Map(java.util.Map) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) ContentNegotiatingViewResolver(org.springframework.web.servlet.view.ContentNegotiatingViewResolver) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) Resource(org.springframework.core.io.Resource) PathResourceResolver(org.springframework.web.servlet.resource.PathResourceResolver) ResourceTransformer(org.springframework.web.servlet.resource.ResourceTransformer) UrlBasedCorsConfigurationSource(org.springframework.web.cors.UrlBasedCorsConfigurationSource) CookieThemeResolver(org.springframework.web.servlet.theme.CookieThemeResolver) TypeMismatchException(org.springframework.beans.TypeMismatchException) StandardCharsets(java.nio.charset.StandardCharsets) NumberFormat(org.springframework.format.annotation.NumberFormat) CssLinkResourceTransformer(org.springframework.web.servlet.resource.CssLinkResourceTransformer) ResourceResolver(org.springframework.web.servlet.resource.ResourceResolver) LocaleChangeInterceptor(org.springframework.web.servlet.i18n.LocaleChangeInterceptor) DeferredResultProcessingInterceptor(org.springframework.web.context.request.async.DeferredResultProcessingInterceptor) ScriptTemplateViewResolver(org.springframework.web.servlet.view.script.ScriptTemplateViewResolver) FlashMapManager(org.springframework.web.servlet.FlashMapManager) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) Ordered(org.springframework.core.Ordered) Errors(org.springframework.validation.Errors) ResourceUrlProviderExposingInterceptor(org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor) ThemeResolver(org.springframework.web.servlet.ThemeResolver) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) AbstractJackson2HttpMessageConverter(org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter) CookieLocaleResolver(org.springframework.web.servlet.i18n.CookieLocaleResolver) BindingResult(org.springframework.validation.BindingResult) FreeMarkerViewResolver(org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver) CachingResourceResolver(org.springframework.web.servlet.resource.CachingResourceResolver) CacheManager(org.springframework.cache.CacheManager) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) Nullable(org.springframework.lang.Nullable) ConversionService(org.springframework.core.convert.ConversionService) Validated(org.springframework.validation.annotation.Validated) ViewResolver(org.springframework.web.servlet.ViewResolver) PathMatcher(org.springframework.util.PathMatcher) ViewResolverComposite(org.springframework.web.servlet.view.ViewResolverComposite) Target(java.lang.annotation.Target) WebJarsResourceResolver(org.springframework.web.servlet.resource.WebJarsResourceResolver) BeanNameViewResolver(org.springframework.web.servlet.view.BeanNameViewResolver) GroovyMarkupViewResolver(org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver) ThemeChangeInterceptor(org.springframework.web.servlet.theme.ThemeChangeInterceptor) FormattingConversionServiceFactoryBean(org.springframework.format.support.FormattingConversionServiceFactoryBean) UrlPathHelper(org.springframework.web.util.UrlPathHelper) MockRequestDispatcher(org.springframework.web.testfixture.servlet.MockRequestDispatcher) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) DefaultRequestToViewNameTranslator(org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator) RequestDispatcher(jakarta.servlet.RequestDispatcher) VersionResourceResolver(org.springframework.web.servlet.resource.VersionResourceResolver) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) InternalResourceView(org.springframework.web.servlet.view.InternalResourceView) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) DateTimeFormat(org.springframework.format.annotation.DateTimeFormat) SessionFlashMapManager(org.springframework.web.servlet.support.SessionFlashMapManager) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) RedirectView(org.springframework.web.servlet.view.RedirectView) Locale(java.util.Locale) BOOLEAN(org.assertj.core.api.InstanceOfAssertFactories.BOOLEAN) HandlerMappingIntrospector(org.springframework.web.servlet.handler.HandlerMappingIntrospector) EncodedResourceResolver(org.springframework.web.servlet.resource.EncodedResourceResolver) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) WebApplicationContext(org.springframework.web.context.WebApplicationContext) ISO(org.springframework.format.annotation.DateTimeFormat.ISO) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) ModelAndView(org.springframework.web.servlet.ModelAndView) List(java.util.List) ConcurrentMapCache(org.springframework.cache.concurrent.ConcurrentMapCache) UserRoleAuthorizationInterceptor(org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) XmlWebApplicationContext(org.springframework.web.context.support.XmlWebApplicationContext) ConcurrentTaskExecutor(org.springframework.scheduling.concurrent.ConcurrentTaskExecutor) ConversionServiceExposingInterceptor(org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor) FreeMarkerConfigurer(org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer) CachingResourceTransformer(org.springframework.web.servlet.resource.CachingResourceTransformer) ContentVersionStrategy(org.springframework.web.servlet.resource.ContentVersionStrategy) GroovyMarkupConfigurer(org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer) MappedInterceptor(org.springframework.web.servlet.handler.MappedInterceptor) Cache(org.springframework.cache.Cache) InternalResourceViewResolver(org.springframework.web.servlet.view.InternalResourceViewResolver) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) NotNull(jakarta.validation.constraints.NotNull) Controller(org.springframework.stereotype.Controller) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Retention(java.lang.annotation.Retention) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) DefaultServletHttpRequestHandler(org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler) StaticApplicationContext(org.springframework.context.support.StaticApplicationContext) RequestToViewNameTranslator(org.springframework.web.servlet.RequestToViewNameTranslator) Charset(java.nio.charset.Charset) CompositeUriComponentsContributor(org.springframework.web.method.support.CompositeUriComponentsContributor) ScriptTemplateConfigurer(org.springframework.web.servlet.view.script.ScriptTemplateConfigurer) SimpleControllerHandlerAdapter(org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter) HttpRequestHandlerAdapter(org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter) CallableProcessingInterceptor(org.springframework.web.context.request.async.CallableProcessingInterceptor) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) ParameterizableViewController(org.springframework.web.servlet.mvc.ParameterizableViewController) ElementType(java.lang.annotation.ElementType) TimeUnit(java.util.concurrent.TimeUnit) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) BeanNameUrlHandlerMapping(org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) FixedVersionStrategy(org.springframework.web.servlet.resource.FixedVersionStrategy) Comparator(java.util.Comparator) Collections(java.util.Collections) RetentionPolicy(java.lang.annotation.RetentionPolicy) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) HttpRequestHandlerAdapter(org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter) BeanNameUrlHandlerMapping(org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) ResourceUrlProvider(org.springframework.web.servlet.resource.ResourceUrlProvider) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 13 with MockHttpServletResponse

use of org.springframework.web.testfixture.servlet.MockHttpServletResponse in project spring-framework by spring-projects.

the class MvcNamespaceTests method testCustomConversionService.

@Test
public void testCustomConversionService() throws Exception {
    loadBeanDefinitions("mvc-config-custom-conversion-service.xml");
    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    assertThat(mapping).isNotNull();
    mapping.setDefaultHandler(handlerMethod);
    // default web binding initializer behavior test
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
    request.setRequestURI("/accounts/12345");
    request.addParameter("date", "2009-10-31");
    MockHttpServletResponse response = new MockHttpServletResponse();
    HandlerExecutionChain chain = mapping.getHandler(request);
    assertThat(chain.getInterceptorList().size()).isEqualTo(1);
    assertThat(chain.getInterceptorList().get(0) instanceof ConversionServiceExposingInterceptor).isTrue();
    ConversionServiceExposingInterceptor interceptor = (ConversionServiceExposingInterceptor) chain.getInterceptorList().get(0);
    interceptor.preHandle(request, response, handler);
    assertThat(request.getAttribute(ConversionService.class.getName())).isSameAs(appContext.getBean("conversionService"));
    RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
    assertThat(adapter).isNotNull();
    assertThatExceptionOfType(TypeMismatchException.class).isThrownBy(() -> adapter.handle(request, response, handlerMethod));
}
Also used : HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) ConversionServiceExposingInterceptor(org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ConversionService(org.springframework.core.convert.ConversionService) TypeMismatchException(org.springframework.beans.TypeMismatchException) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 14 with MockHttpServletResponse

use of org.springframework.web.testfixture.servlet.MockHttpServletResponse in project spring-framework by spring-projects.

the class MvcNamespaceTests method testDefaultServletHandlerWithOptionalAttributes.

@Test
public void testDefaultServletHandlerWithOptionalAttributes() throws Exception {
    loadBeanDefinitions("mvc-config-default-servlet-optional-attrs.xml");
    HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class);
    assertThat(adapter).isNotNull();
    DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class);
    assertThat(handler).isNotNull();
    SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class);
    assertThat(mapping).isNotNull();
    assertThat(mapping.getOrder()).isEqualTo(Ordered.LOWEST_PRECEDENCE);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/foo.css");
    request.setMethod("GET");
    HandlerExecutionChain chain = mapping.getHandler(request);
    assertThat(chain.getHandler() instanceof DefaultServletHttpRequestHandler).isTrue();
    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView mv = adapter.handle(request, response, chain.getHandler());
    assertThat((Object) mv).isNull();
}
Also used : HttpRequestHandlerAdapter(org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) DefaultServletHttpRequestHandler(org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 15 with MockHttpServletResponse

use of org.springframework.web.testfixture.servlet.MockHttpServletResponse in project spring-framework by spring-projects.

the class ViewResolutionIntegrationTests method runTest.

private MockHttpServletResponse runTest(Class<?> configClass) throws ServletException, IOException {
    String basePath = "org/springframework/web/servlet/config/annotation";
    MockServletContext servletContext = new MockServletContext(basePath);
    MockServletConfig servletConfig = new MockServletConfig(servletContext);
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
    MockHttpServletResponse response = new MockHttpServletResponse();
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(configClass);
    context.setServletContext(servletContext);
    context.refresh();
    DispatcherServlet servlet = new DispatcherServlet(context);
    servlet.init(servletConfig);
    servlet.service(request, response);
    return response;
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) DispatcherServlet(org.springframework.web.servlet.DispatcherServlet) MockServletConfig(org.springframework.web.testfixture.servlet.MockServletConfig) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse)

Aggregations

MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)415 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)364 Test (org.junit.jupiter.api.Test)203 PathPatternsParameterizedTest (org.springframework.web.servlet.handler.PathPatternsParameterizedTest)143 BeforeEach (org.junit.jupiter.api.BeforeEach)54 ModelAndView (org.springframework.web.servlet.ModelAndView)47 MockServletContext (org.springframework.web.testfixture.servlet.MockServletContext)38 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)36 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)29 HashMap (java.util.HashMap)27 FilterChain (jakarta.servlet.FilterChain)24 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)24 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)23 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)23 StaticWebApplicationContext (org.springframework.web.context.support.StaticWebApplicationContext)20 ServletException (jakarta.servlet.ServletException)18 Cookie (jakarta.servlet.http.Cookie)16 Locale (java.util.Locale)15 MockFilterConfig (org.springframework.web.testfixture.servlet.MockFilterConfig)15 MockServletConfig (org.springframework.web.testfixture.servlet.MockServletConfig)13