org.springframework.mock.web.test.MockHttpServletResponse Java Examples
The following examples show how to use
org.springframework.mock.web.test.MockHttpServletResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServletAnnotationControllerHandlerMethodTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void methodNotAllowed() throws Exception { initServletWithControllers(MethodNotAllowedController.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals("Invalid response status", HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus()); String allowHeader = response.getHeader("Allow"); assertNotNull("No Allow header", allowHeader); Set<String> allowedMethods = new HashSet<String>(); allowedMethods.addAll(Arrays.asList(StringUtils.delimitedListToStringArray(allowHeader, ", "))); assertEquals("Invalid amount of supported methods", 6, allowedMethods.size()); assertTrue("PUT not allowed", allowedMethods.contains("PUT")); assertTrue("DELETE not allowed", allowedMethods.contains("DELETE")); assertTrue("HEAD not allowed", allowedMethods.contains("HEAD")); assertTrue("TRACE not allowed", allowedMethods.contains("TRACE")); assertTrue("OPTIONS not allowed", allowedMethods.contains("OPTIONS")); assertTrue("POST not allowed", allowedMethods.contains("POST")); }
Example #2
Source File: BaseViewTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void renderWithoutStaticAttributes() throws Exception { WebApplicationContext wac = mock(WebApplicationContext.class); given(wac.getServletContext()).willReturn(new MockServletContext()); HttpServletRequest request = new MockHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); TestView tv = new TestView(wac); // Check superclass handles duplicate init tv.setApplicationContext(wac); tv.setApplicationContext(wac); Map<String, Object> model = new HashMap<>(); model.put("foo", "bar"); model.put("something", new Object()); tv.render(model, request, response); checkContainsAll(model, tv.model); assertTrue(tv.initialized); }
Example #3
Source File: DelegatingFilterProxyTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testDelegatingFilterProxyWithFilterName() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); MockFilterConfig proxyConfig = new MockFilterConfig(sc, "targetFilter"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertNull(targetFilter.filterConfig); assertEquals(Boolean.TRUE, request.getAttribute("called")); filterProxy.destroy(); assertNull(targetFilter.filterConfig); }
Example #4
Source File: ShallowEtagHeaderFilterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void filterFlushResponse() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { assertEquals("Invalid request passed", request, filterRequest); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); filterResponse.flushBuffer(); }; filter.doFilter(request, response, filterChain); assertEquals("Invalid status", 200, response.getStatus()); assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); assertTrue("Invalid Content-Length header", response.getContentLength() > 0); assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); }
Example #5
Source File: RequestResponseBodyMethodProcessorMockTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Before public void setUp() throws Exception { messageConverter = mock(HttpMessageConverter.class); given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN)); processor = new RequestResponseBodyMethodProcessor(Collections.<HttpMessageConverter<?>>singletonList(messageConverter)); Method methodHandle1 = getClass().getMethod("handle1", String.class, Integer.TYPE); paramRequestBodyString = new MethodParameter(methodHandle1, 0); paramInt = new MethodParameter(methodHandle1, 1); returnTypeString = new MethodParameter(methodHandle1, -1); returnTypeInt = new MethodParameter(getClass().getMethod("handle2"), -1); returnTypeStringProduces = new MethodParameter(getClass().getMethod("handle3"), -1); paramValidBean = new MethodParameter(getClass().getMethod("handle4", SimpleBean.class), 0); paramStringNotRequired = new MethodParameter(getClass().getMethod("handle5", String.class), 0); mavContainer = new ModelAndViewContainer(); servletRequest = new MockHttpServletRequest(); servletRequest.setMethod("POST"); webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse()); }
Example #6
Source File: ForwardedHeaderFilterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void forwardedRequestInRemoveOnlyMode() throws Exception { this.request.setRequestURI("/mvc-showcase"); this.request.addHeader(X_FORWARDED_PROTO, "https"); this.request.addHeader(X_FORWARDED_HOST, "84.198.58.199"); this.request.addHeader(X_FORWARDED_PORT, "443"); this.request.addHeader(X_FORWARDED_SSL, "on"); this.request.addHeader("foo", "bar"); this.filter.setRemoveOnly(true); this.filter.doFilter(this.request, new MockHttpServletResponse(), this.filterChain); HttpServletRequest actual = (HttpServletRequest) this.filterChain.getRequest(); assertEquals("http://localhost/mvc-showcase", actual.getRequestURL().toString()); assertEquals("http", actual.getScheme()); assertEquals("localhost", actual.getServerName()); assertEquals(80, actual.getServerPort()); assertFalse(actual.isSecure()); assertNull(actual.getHeader(X_FORWARDED_PROTO)); assertNull(actual.getHeader(X_FORWARDED_HOST)); assertNull(actual.getHeader(X_FORWARDED_PORT)); assertNull(actual.getHeader(X_FORWARDED_SSL)); assertEquals("bar", actual.getHeader("foo")); }
Example #7
Source File: ResourceHandlerFunctionTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void get() throws IOException, ServletException { MockHttpServletRequest servletRequest = new MockHttpServletRequest("GET", "/"); ServerRequest request = new DefaultServerRequest(servletRequest, Collections.singletonList(messageConverter)); ServerResponse response = this.handlerFunction.handle(request); assertEquals(HttpStatus.OK, response.statusCode()); assertTrue(response instanceof EntityResponse); @SuppressWarnings("unchecked") EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response; assertEquals(this.resource, entityResponse.entity()); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); ModelAndView mav = response.writeTo(servletRequest, servletResponse, this.context); assertNull(mav); assertEquals(200, servletResponse.getStatus()); byte[] expectedBytes = Files.readAllBytes(this.resource.getFile().toPath()); byte[] actualBytes = servletResponse.getContentAsByteArray(); assertArrayEquals(expectedBytes, actualBytes); assertEquals(MediaType.TEXT_PLAIN_VALUE, servletResponse.getContentType()); assertEquals(this.resource.contentLength(),servletResponse.getContentLength()); }
Example #8
Source File: DispatcherServletTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void cleanupAfterIncludeWithRestore() 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.service(request, response); assertEquals("value1", request.getAttribute("test1")); assertEquals("value2", request.getAttribute("test2")); assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)); }
Example #9
Source File: ServletAnnotationControllerHandlerMethodTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void mavResolver() throws ServletException, IOException { initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() { @Override public void initialize(GenericWebApplicationContext wac) { RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); ModelAndViewResolver[] mavResolvers = new ModelAndViewResolver[] {new MyModelAndViewResolver()}; adapterDef.getPropertyValues().add("modelAndViewResolvers", mavResolvers); wac.registerBeanDefinition("handlerAdapter", adapterDef); } }, ModelAndViewResolverController.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals("myValue", response.getContentAsString()); }
Example #10
Source File: MvcNamespaceTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void testDefaultServletHandlerWithOptionalAttributes() throws Exception { loadBeanDefinitions("mvc-config-default-servlet-optional-attrs.xml"); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); assertNotNull(adapter); DefaultServletHttpRequestHandler handler = appContext.getBean(DefaultServletHttpRequestHandler.class); assertNotNull(handler); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(mapping); assertEquals(Ordered.LOWEST_PRECEDENCE, mapping.getOrder()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); assertTrue(chain.getHandler() instanceof DefaultServletHttpRequestHandler); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mv = adapter.handle(request, response, chain.getHandler()); assertNull(mv); }
Example #11
Source File: CookieLocaleResolverTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void testSetLocaleToNull() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addPreferredLocale(Locale.TAIWAN); Cookie cookie = new Cookie(CookieLocaleResolver.DEFAULT_COOKIE_NAME, Locale.UK.toString()); request.setCookies(cookie); MockHttpServletResponse response = new MockHttpServletResponse(); CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setLocale(request, response, null); Locale locale = (Locale) request.getAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME); assertEquals(Locale.TAIWAN, locale); Cookie[] cookies = response.getCookies(); assertEquals(1, cookies.length); Cookie localeCookie = cookies[0]; assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, localeCookie.getName()); assertEquals("", localeCookie.getValue()); }
Example #12
Source File: ShallowEtagHeaderFilterTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-12960 public void filterWriterWithDisabledCaching() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { assertEquals("Invalid request passed", request, filterRequest); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); }; ShallowEtagHeaderFilter.disableContentCaching(request); this.filter.doFilter(request, response, filterChain); assertEquals(200, response.getStatus()); assertNull(response.getHeader("ETag")); assertArrayEquals(responseBody, response.getContentAsByteArray()); }
Example #13
Source File: DispatcherServletTests.java From spring-analysis-note with MIT License | 6 votes |
@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); assertEquals("value1", request.getAttribute("test1")); assertEquals("value2", request.getAttribute("test2")); assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE)); }
Example #14
Source File: HandlerMethodAnnotationDetectionTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testRequestMappingMethod() throws Exception { String datePattern = "MM:dd:yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); String dateA = "11:01:2011"; String dateB = "11:02:2011"; MockHttpServletRequest request = new MockHttpServletRequest("POST", "/path1/path2"); request.setParameter("datePattern", datePattern); request.addHeader("header1", dateA); request.addHeader("header2", dateB); HandlerExecutionChain chain = handlerMapping.getHandler(request); assertNotNull(chain); ModelAndView mav = handlerAdapter.handle(request, new MockHttpServletResponse(), chain.getHandler()); assertEquals("model attr1:", dateFormat.parse(dateA), mav.getModel().get("attr1")); assertEquals("model attr2:", dateFormat.parse(dateB), mav.getModel().get("attr2")); MockHttpServletResponse response = new MockHttpServletResponse(); exceptionResolver.resolveException(request, response, chain.getHandler(), new Exception("failure")); assertEquals("text/plain;charset=ISO-8859-1", response.getHeader("Content-Type")); assertEquals("failure", response.getContentAsString()); }
Example #15
Source File: ServletAnnotationControllerHandlerMethodTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-6877 public void overlappingMessageConvertersRequestBody() throws Exception { initServlet(wac -> { RootBeanDefinition adapterDef = new RootBeanDefinition(RequestMappingHandlerAdapter.class); List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new StringHttpMessageConverter()); messageConverters .add(new SimpleMessageConverter(new MediaType("application","json"), MediaType.ALL)); adapterDef.getPropertyValues().add("messageConverters", messageConverters); wac.registerBeanDefinition("handlerAdapter", adapterDef); }, RequestResponseBodyController.class); MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); request.setContent("Hello World".getBytes("UTF-8")); request.addHeader("Content-Type", "text/plain; charset=utf-8"); request.addHeader("Accept", "application/json, text/javascript, */*"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals("Invalid content-type", "application/json;charset=ISO-8859-1", response.getHeader("Content-Type")); }
Example #16
Source File: ServletAnnotationControllerHandlerMethodTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void formController() throws Exception { initServlet(new ApplicationContextInitializer<GenericWebApplicationContext>() { @Override public void initialize(GenericWebApplicationContext wac) { wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); } }, MyFormController.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); request.addParameter("name", "name1"); request.addParameter("age", "value2"); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); }
Example #17
Source File: ShallowEtagHeaderFilterTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void filterNoMatch() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { assertEquals("Invalid request passed", request, filterRequest); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); }; filter.doFilter(request, response, filterChain); assertEquals("Invalid status", 200, response.getStatus()); assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); assertTrue("Invalid Content-Length header", response.getContentLength() > 0); assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); }
Example #18
Source File: ShallowEtagHeaderFilterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void filterSendRedirect() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); MockHttpServletResponse response = new MockHttpServletResponse(); final byte[] responseBody = "Hello World".getBytes("UTF-8"); FilterChain filterChain = (filterRequest, filterResponse) -> { assertEquals("Invalid request passed", request, filterRequest); response.setContentLength(100); FileCopyUtils.copy(responseBody, filterResponse.getOutputStream()); ((HttpServletResponse) filterResponse).sendRedirect("https://www.google.com"); }; filter.doFilter(request, response, filterChain); assertEquals("Invalid status", 302, response.getStatus()); assertNull("Invalid ETag header", response.getHeader("ETag")); assertEquals("Invalid Content-Length header", 100, response.getContentLength()); assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray()); assertEquals("Invalid redirect URL", "https://www.google.com", response.getRedirectedUrl()); }
Example #19
Source File: VelocityMacroTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); final Template expectedTemplate = new Template(); VelocityConfig vc = new VelocityConfig() { @Override public VelocityEngine getVelocityEngine() { return new TestVelocityEngine(TEMPLATE_FILE, expectedTemplate); } }; wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc); wac.refresh(); request = new MockHttpServletRequest(); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver()); request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, new FixedThemeResolver()); response = new MockHttpServletResponse(); }
Example #20
Source File: ArgumentTagTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void argumentWithValueThenReleaseThenBodyValue() throws JspException { tag.setValue("value3"); int action = tag.doEndTag(); assertEquals(Tag.EVAL_PAGE, action); assertEquals("value3", parent.getArgument()); tag.release(); parent = new MockArgumentSupportTag(); tag.setPageContext(createPageContext()); tag.setParent(parent); tag.setBodyContent(new MockBodyContent("value4", new MockHttpServletResponse())); action = tag.doEndTag(); assertEquals(Tag.EVAL_PAGE, action); assertEquals("value4", parent.getArgument()); }
Example #21
Source File: RequestResponseBodyMethodProcessorTests.java From java-technology-stack with MIT License | 6 votes |
private void assertContentDisposition(RequestResponseBodyMethodProcessor processor, boolean expectContentDisposition, String requestURI, String comment) throws Exception { this.servletRequest.setRequestURI(requestURI); processor.handleReturnValue("body", this.returnTypeString, this.container, this.request); String header = servletResponse.getHeader("Content-Disposition"); if (expectContentDisposition) { assertEquals("Expected 'Content-Disposition' header. Use case: '" + comment + "'", "inline;filename=f.txt", header); } else { assertNull("Did not expect 'Content-Disposition' header. Use case: '" + comment + "'", header); } this.servletRequest = new MockHttpServletRequest(); this.servletResponse = new MockHttpServletResponse(); this.request = new ServletWebRequest(servletRequest, servletResponse); }
Example #22
Source File: DispatcherServletTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void modelAndViewDefiningException() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do"); request.addPreferredLocale(Locale.CANADA); request.addUserRole("role1"); request.addParameter("fail", "yes"); MockHttpServletResponse response = new MockHttpServletResponse(); try { complexDispatcherServlet.service(request, response); assertEquals(200, response.getStatus()); assertTrue("forwarded to failed", "failed1.jsp".equals(response.getForwardedUrl())); } catch (ServletException ex) { fail("Should not have thrown ServletException: " + ex.getMessage()); } }
Example #23
Source File: FreeMarkerMacroTests.java From java-technology-stack with MIT License | 6 votes |
@Before public void setUp() throws Exception { ServletContext sc = new MockServletContext(); wac = new StaticWebApplicationContext(); wac.setServletContext(sc); // final Template expectedTemplate = new Template(); fc = new FreeMarkerConfigurer(); fc.setTemplateLoaderPaths("classpath:/", "file://" + System.getProperty("java.io.tmpdir")); fc.setServletContext(sc); fc.afterPropertiesSet(); wac.getDefaultListableBeanFactory().registerSingleton("freeMarkerConfigurer", fc); wac.refresh(); request = new MockHttpServletRequest(); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver()); request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, new FixedThemeResolver()); response = new MockHttpServletResponse(); }
Example #24
Source File: ShallowEtagHeaderFilterTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void filterWriter() throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\""; request.addHeader("If-None-Match", etag); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = (filterRequest, filterResponse) -> { assertEquals("Invalid request passed", request, filterRequest); ((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK); String responseBody = "Hello World"; FileCopyUtils.copy(responseBody, filterResponse.getWriter()); }; filter.doFilter(request, response, filterChain); assertEquals("Invalid status", 304, response.getStatus()); assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag")); assertFalse("Response has Content-Length header", response.containsHeader("Content-Length")); assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray()); }
Example #25
Source File: UriTemplateServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("serial") public void suppressDefaultSuffixPattern() throws Exception { servlet = new DispatcherServlet() { @Override protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException { GenericWebApplicationContext wac = new GenericWebApplicationContext(); wac.registerBeanDefinition("controller", new RootBeanDefinition(VariableNamesController.class)); RootBeanDefinition mappingDef = new RootBeanDefinition(DefaultAnnotationHandlerMapping.class); mappingDef.getPropertyValues().add("useDefaultSuffixPattern", false); wac.registerBeanDefinition("handlerMapping", mappingDef); wac.refresh(); return wac; } }; servlet.init(new MockServletConfig()); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/[email protected]"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("[email protected]", response.getContentAsString()); }
Example #26
Source File: ContentNegotiatingViewResolverTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void resolveViewNoMatchUseUnacceptableStatus() throws Exception { viewResolver.setUseNotAcceptableStatusCode(true); request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/pdf"); View result = viewResolver.resolveViewName(viewName, locale); assertNotNull("Invalid view", result); MockHttpServletResponse response = new MockHttpServletResponse(); result.render(null, request, response); assertEquals("Invalid status code set", 406, response.getStatus()); }
Example #27
Source File: DelegatingFilterProxyTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testDelegatingFilterProxyInjectedPreferred() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.refresh(); sc.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); StaticWebApplicationContext injectedWac = new StaticWebApplicationContext(); injectedWac.setServletContext(sc); String beanName = "targetFilter"; injectedWac.registerSingleton(beanName, MockFilter.class); injectedWac.refresh(); MockFilter targetFilter = (MockFilter) injectedWac.getBean(beanName); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(beanName, injectedWac); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertNull(targetFilter.filterConfig); assertEquals(Boolean.TRUE, request.getAttribute("called")); filterProxy.destroy(); assertNull(targetFilter.filterConfig); }
Example #28
Source File: ServletAnnotationControllerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void responseStatus() throws ServletException, IOException { initServlet(ResponseStatusController.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("something", response.getContentAsString()); assertEquals(201, response.getStatus()); assertEquals("It's alive!", response.getErrorMessage()); }
Example #29
Source File: ResourceUrlEncodingFilterTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void encodeContextPathUrlWithSuffix() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/context/"); request.setContextPath("/context"); request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.resourceUrlProvider); MockHttpServletResponse response = new MockHttpServletResponse(); this.filter.doFilterInternal(request, response, (request1, response1) -> { String result = ((HttpServletResponse) response1).encodeURL("/context/resources/bar.css"); assertEquals("/context/resources/bar-11e16cf79faee7ac698c805cf28248d2.css", result); }); }
Example #30
Source File: JdkProxyControllerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void typeAndMethodLevel() throws Exception { initServlet(TypeAndMethodLevelImpl.class); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/bookings"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); assertEquals("doIt", response.getContentAsString()); }