Search in sources :

Example 46 with MockHttpServletRequest

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

the class WebMvcConfigurationSupportExtensionTests method handlerMappings.

@Test
public void handlerMappings() throws Exception {
    RequestMappingHandlerMapping rmHandlerMapping = this.config.requestMappingHandlerMapping(this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(), this.config.mvcResourceUrlProvider());
    rmHandlerMapping.setApplicationContext(this.context);
    rmHandlerMapping.afterPropertiesSet();
    assertThat(rmHandlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class);
    assertThat(rmHandlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class);
    HandlerExecutionChain chain = rmHandlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
    assertThat(chain).isNotNull();
    HandlerInterceptor[] interceptors = chain.getInterceptors();
    assertThat(interceptors).isNotNull();
    assertThat(interceptors.length).isEqualTo(4);
    assertThat(interceptors[0].getClass().getSimpleName()).isEqualTo("CorsInterceptor");
    assertThat(interceptors[1].getClass()).isEqualTo(LocaleChangeInterceptor.class);
    assertThat(interceptors[2].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class);
    assertThat(interceptors[3].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class);
    Map<RequestMappingInfo, HandlerMethod> map = rmHandlerMapping.getHandlerMethods();
    assertThat(map.size()).isEqualTo(2);
    RequestMappingInfo info = map.entrySet().stream().filter(entry -> entry.getValue().getBeanType().equals(UserController.class)).findFirst().orElseThrow(() -> new AssertionError("UserController bean not found")).getKey();
    assertThat(info.getPatternValues()).isEqualTo(Collections.singleton("/api/user/{id}"));
    AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) this.config.viewControllerHandlerMapping(this.config.mvcConversionService(), this.config.mvcResourceUrlProvider());
    handlerMapping.setApplicationContext(this.context);
    assertThat(handlerMapping).isNotNull();
    assertThat(handlerMapping.getOrder()).isEqualTo(1);
    assertThat(handlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class);
    assertThat(handlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class);
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/path"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/bad"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/old"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    handlerMapping = (AbstractHandlerMapping) this.config.resourceHandlerMapping(this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(), this.config.mvcResourceUrlProvider());
    handlerMapping.setApplicationContext(this.context);
    assertThat(handlerMapping).isNotNull();
    assertThat(handlerMapping.getOrder()).isEqualTo((Integer.MAX_VALUE - 1));
    assertThat(handlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class);
    assertThat(handlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class);
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    interceptors = chain.getInterceptors();
    assertThat(interceptors.length).as(Arrays.toString(interceptors)).isEqualTo(5);
    assertThat(interceptors[0].getClass().getSimpleName()).isEqualTo("CorsInterceptor");
    // PathExposingHandlerInterceptor at interceptors[1]
    assertThat(interceptors[2].getClass()).isEqualTo(LocaleChangeInterceptor.class);
    assertThat(interceptors[3].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class);
    assertThat(interceptors[4].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class);
    handlerMapping = (AbstractHandlerMapping) this.config.defaultServletHandlerMapping();
    handlerMapping.setApplicationContext(this.context);
    assertThat(handlerMapping).isNotNull();
    assertThat(handlerMapping.getOrder()).isEqualTo(Integer.MAX_VALUE);
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/anyPath"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) DEFAULT_VIEW_INCLUSION(com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION) Validator(org.springframework.validation.Validator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) APPLICATION_XML(org.springframework.http.MediaType.APPLICATION_XML) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) FAIL_ON_UNKNOWN_PROPERTIES(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) HandlerExceptionResolverComposite(org.springframework.web.servlet.handler.HandlerExceptionResolverComposite) BOOLEAN(org.assertj.core.api.InstanceOfAssertFactories.BOOLEAN) Map(java.util.Map) TestBean(org.springframework.beans.testfixture.beans.TestBean) AntPathMatcher(org.springframework.util.AntPathMatcher) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) ContentNegotiatingViewResolver(org.springframework.web.servlet.view.ContentNegotiatingViewResolver) FormatterRegistry(org.springframework.format.FormatterRegistry) HandlerMethodArgumentResolver(org.springframework.web.method.support.HandlerMethodArgumentResolver) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) RestController(org.springframework.web.bind.annotation.RestController) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) Test(org.junit.jupiter.api.Test) List(java.util.List) DefaultMessageCodesResolver(org.springframework.validation.DefaultMessageCodesResolver) LocaleChangeInterceptor(org.springframework.web.servlet.i18n.LocaleChangeInterceptor) Principal(java.security.Principal) HandlerExceptionResolver(org.springframework.web.servlet.HandlerExceptionResolver) DeferredResultProcessingInterceptor(org.springframework.web.context.request.async.DeferredResultProcessingInterceptor) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) ConcurrentTaskExecutor(org.springframework.scheduling.concurrent.ConcurrentTaskExecutor) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) ConversionServiceExposingInterceptor(org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor) ResponseStatusExceptionResolver(org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) HandlerMethodReturnValueHandler(org.springframework.web.method.support.HandlerMethodReturnValueHandler) Mockito.mock(org.mockito.Mockito.mock) Ordered(org.springframework.core.Ordered) SimpleMappingExceptionResolver(org.springframework.web.servlet.handler.SimpleMappingExceptionResolver) Errors(org.springframework.validation.Errors) ResourceUrlProviderExposingInterceptor(org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor) ModelAttributeMethodProcessor(org.springframework.web.method.annotation.ModelAttributeMethodProcessor) InternalResourceViewResolver(org.springframework.web.servlet.view.InternalResourceViewResolver) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Controller(org.springframework.stereotype.Controller) FileSystemResourceLoader(org.springframework.core.io.FileSystemResourceLoader) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) MappingJackson2JsonView(org.springframework.web.servlet.view.json.MappingJackson2JsonView) GetMapping(org.springframework.web.bind.annotation.GetMapping) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) Nullable(org.springframework.lang.Nullable) MessageCodesResolver(org.springframework.validation.MessageCodesResolver) APPLICATION_JSON(org.springframework.http.MediaType.APPLICATION_JSON) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) CallableProcessingInterceptor(org.springframework.web.context.request.async.CallableProcessingInterceptor) ViewResolver(org.springframework.web.servlet.ViewResolver) ViewResolverComposite(org.springframework.web.servlet.view.ViewResolverComposite) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) HttpStatus(org.springframework.http.HttpStatus) View(org.springframework.web.servlet.View) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) UrlPathHelper(org.springframework.web.util.UrlPathHelper) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) HandlerTypePredicate(org.springframework.web.method.HandlerTypePredicate) Collections(java.util.Collections) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) HandlerMethod(org.springframework.web.method.HandlerMethod) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Test(org.junit.jupiter.api.Test)

Example 47 with MockHttpServletRequest

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

the class DefaultEntityResponseBuilderTests method notModifiedLastModified.

@Test
public void notModifiedLastModified() throws ServletException, IOException {
    ZonedDateTime now = ZonedDateTime.now();
    ZonedDateTime oneMinuteBeforeNow = now.minus(1, ChronoUnit.MINUTES);
    EntityResponse<String> entityResponse = EntityResponse.fromObject("bar").lastModified(oneMinuteBeforeNow).build();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "https://example.com");
    mockRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateTimeFormatter.RFC_1123_DATE_TIME.format(now));
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    ModelAndView mav = entityResponse.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT);
    assertThat(mav).isNull();
    assertThat(mockResponse.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value());
}
Also used : ZonedDateTime(java.time.ZonedDateTime) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 48 with MockHttpServletRequest

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

the class DefaultEntityResponseBuilderTests method notModifiedEtag.

@Test
public void notModifiedEtag() throws Exception {
    String etag = "\"foo\"";
    EntityResponse<String> entityResponse = EntityResponse.fromObject("bar").eTag(etag).build();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "https://example.com");
    mockRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etag);
    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    ModelAndView mav = entityResponse.writeTo(mockRequest, mockResponse, EMPTY_CONTEXT);
    assertThat(mav).isNull();
    assertThat(mockResponse.getStatus()).isEqualTo(HttpStatus.NOT_MODIFIED.value());
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 49 with MockHttpServletRequest

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

the class DispatcherServletTests method anotherLocaleRequest.

@Test
public void anotherLocaleRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
    request.addPreferredLocale(Locale.CANADA);
    request.addUserRole("role1");
    MockHttpServletResponse response = new MockHttpServletResponse();
    complexDispatcherServlet.service(request, response);
    assertThat(response.getForwardedUrl() == null).as("Not forwarded").isTrue();
    assertThat(request.getAttribute("test1") != null).isTrue();
    assertThat(request.getAttribute("test1x") == null).isTrue();
    assertThat(request.getAttribute("test1y") == null).isTrue();
    assertThat(request.getAttribute("test2") != null).isTrue();
    assertThat(request.getAttribute("test2x") == null).isTrue();
    assertThat(request.getAttribute("test2y") == null).isTrue();
    assertThat(request.getAttribute("test3") != null).isTrue();
    assertThat(request.getAttribute("test3x") != null).isTrue();
    assertThat(request.getAttribute("test3y") != null).isTrue();
    assertThat(response.getHeader("Last-Modified")).isEqualTo("Wed, 01 Apr 2015 00:00:01 GMT");
}
Also used : MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 50 with MockHttpServletRequest

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

the class DispatcherServletTests method noCleanupAfterInclude.

@Test
public void noCleanupAfterInclude() throws ServletException, IOException {
    MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.setAttribute("test1", "value1");
    request.setAttribute("test2", "value2");
    WebApplicationContext wac = new StaticWebApplicationContext();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    TestBean command = new TestBean();
    request.setAttribute("command", command);
    request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
    simpleDispatcherServlet.setCleanupAfterInclude(false);
    simpleDispatcherServlet.service(request, response);
    assertThat(request.getAttribute("test1")).isEqualTo("value1");
    assertThat(request.getAttribute("test2")).isEqualTo("value2");
    assertThat(request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)).isSameAs(wac);
}
Also used : TestBean(org.springframework.beans.testfixture.beans.TestBean) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) MockHttpServletResponse(org.springframework.web.testfixture.servlet.MockHttpServletResponse) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) WebApplicationContext(org.springframework.web.context.WebApplicationContext) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) ConfigurableWebApplicationContext(org.springframework.web.context.ConfigurableWebApplicationContext) Test(org.junit.jupiter.api.Test)

Aggregations

MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)752 Test (org.junit.jupiter.api.Test)458 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)359 PathPatternsParameterizedTest (org.springframework.web.servlet.handler.PathPatternsParameterizedTest)180 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)83 BeforeEach (org.junit.jupiter.api.BeforeEach)73 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)57 ModelAndView (org.springframework.web.servlet.ModelAndView)45 MockServletContext (org.springframework.web.testfixture.servlet.MockServletContext)45 ServletServerHttpRequest (org.springframework.http.server.ServletServerHttpRequest)39 RootBeanDefinition (org.springframework.beans.factory.support.RootBeanDefinition)38 HandlerExecutionChain (org.springframework.web.servlet.HandlerExecutionChain)38 TestBean (org.springframework.beans.testfixture.beans.TestBean)36 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)35 StaticWebApplicationContext (org.springframework.web.context.support.StaticWebApplicationContext)31 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)29 Cookie (jakarta.servlet.http.Cookie)27 HttpRequest (org.springframework.http.HttpRequest)27 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)26 ITestBean (org.springframework.beans.testfixture.beans.ITestBean)25