org.springframework.mock.web.test.MockServletContext Java Examples
The following examples show how to use
org.springframework.mock.web.test.MockServletContext.
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: ResourceUrlProviderJavaConfigTests.java From spring-analysis-note with MIT License | 6 votes |
@Before @SuppressWarnings("resource") public void setup() throws Exception { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setServletContext(new MockServletContext()); context.register(WebConfig.class); context.refresh(); this.request = new MockHttpServletRequest("GET", "/"); this.request.setContextPath("/myapp"); this.response = new MockHttpServletResponse(); this.filterChain = new MockFilterChain(this.servlet, new ResourceUrlEncodingFilter(), (request, response, chain) -> { Object urlProvider = context.getBean(ResourceUrlProvider.class); request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, urlProvider); chain.doFilter(request, response); }); }
Example #2
Source File: RequestContextListenerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void requestContextListenerWithSameThread() { RequestContextListener listener = new RequestContextListener(); MockServletContext context = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); assertNull(RequestContextHolder.getRequestAttributes()); listener.requestInitialized(new ServletRequestEvent(context, request)); assertNotNull(RequestContextHolder.getRequestAttributes()); assertEquals("value", RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); listener.requestDestroyed(new ServletRequestEvent(context, request)); assertNull(RequestContextHolder.getRequestAttributes()); assertTrue(runnable.wasExecuted()); }
Example #3
Source File: Spr8510Tests.java From spring-analysis-note with MIT License | 6 votes |
/** * If setConfigLocation has not been called explicitly against the application context, * then fall back to the ContextLoaderListener init-param if present. */ @Test public void abstractRefreshableWAC_fallsBackToInitParam() { XmlWebApplicationContext ctx = new XmlWebApplicationContext(); //ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically ContextLoaderListener cll = new ContextLoaderListener(ctx); MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); try { cll.contextInitialized(new ServletContextEvent(sc)); fail("expected exception"); } catch (Throwable t) { // assert that an attempt was made to load the correct XML assertTrue(t.getMessage().endsWith( "Could not open ServletContext resource [/from-init-param.xml]")); } }
Example #4
Source File: InternalResourceViewTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void forward() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myservlet/handler.do"); request.setContextPath("/mycontext"); request.setServletPath("/myservlet"); request.setPathInfo(";mypathinfo"); request.setQueryString("?param1=value1"); view.setUrl(url); view.setServletContext(new MockServletContext() { @Override public int getMinorVersion() { return 4; } }); view.render(model, request, response); assertEquals(url, response.getForwardedUrl()); model.keySet().stream().forEach( key -> assertEquals("Values for model key '" + key + "' must match", model.get(key), request.getAttribute(key)) ); }
Example #5
Source File: TilesViewTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { MockServletContext servletContext = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(servletContext); wac.refresh(); request = new MockHttpServletRequest(); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); response = new MockHttpServletResponse(); renderer = mock(Renderer.class); view = new TilesView(); view.setServletContext(servletContext); view.setRenderer(renderer); view.setUrl(VIEW_PATH); view.afterPropertiesSet(); }
Example #6
Source File: XmlWebApplicationContextTests.java From spring-analysis-note with MIT License | 6 votes |
@Test @SuppressWarnings("resource") public void withoutMessageSource() throws Exception { MockServletContext sc = new MockServletContext(""); XmlWebApplicationContext wac = new XmlWebApplicationContext(); wac.setParent(root); wac.setServletContext(sc); wac.setNamespace("testNamespace"); wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"}); wac.refresh(); try { wac.getMessage("someMessage", null, Locale.getDefault()); fail("Should have thrown NoSuchMessageException"); } catch (NoSuchMessageException ex) { // expected; } String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault()); assertTrue("Default message returned", "default".equals(msg)); }
Example #7
Source File: ViewResolverTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testXmlViewResolverDefaultLocation() { StaticWebApplicationContext wac = new StaticWebApplicationContext() { @Override protected Resource getResourceByPath(String path) { assertTrue("Correct default location", XmlViewResolver.DEFAULT_LOCATION.equals(path)); return super.getResourceByPath(path); } }; wac.setServletContext(new MockServletContext()); wac.refresh(); XmlViewResolver vr = new XmlViewResolver(); try { vr.setApplicationContext(wac); vr.afterPropertiesSet(); fail("Should have thrown BeanDefinitionStoreException"); } catch (BeanDefinitionStoreException ex) { // expected } }
Example #8
Source File: ThemeResolverTests.java From spring-analysis-note with MIT License | 6 votes |
private void internalTest(ThemeResolver themeResolver, boolean shouldSet, String defaultName) { // create mocks MockServletContext context = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(context); MockHttpServletResponse response = new MockHttpServletResponse(); // check original theme String themeName = themeResolver.resolveThemeName(request); assertEquals(themeName, defaultName); // set new theme name try { themeResolver.setThemeName(request, response, TEST_THEME_NAME); if (!shouldSet) fail("should not be able to set Theme name"); // check new theme namelocale themeName = themeResolver.resolveThemeName(request); assertEquals(TEST_THEME_NAME, themeName); themeResolver.setThemeName(request, response, null); themeName = themeResolver.resolveThemeName(request); assertEquals(themeName, defaultName); } catch (UnsupportedOperationException ex) { if (shouldSet) fail("should be able to set Theme name"); } }
Example #9
Source File: CharacterEncodingFilterTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void withBeanInitialization() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getCharacterEncoding()).willReturn(null); given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding(ENCODING); filter.setBeanName(FILTER_NAME); filter.setServletContext(new MockServletContext()); filter.doFilter(request, response, filterChain); verify(request).setCharacterEncoding(ENCODING); verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE); verify(request).removeAttribute(filteredName(FILTER_NAME)); verify(filterChain).doFilter(request, response); }
Example #10
Source File: Spr8510Tests.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * If a contextConfigLocation init-param has been specified for the ContextLoaderListener, * then it should take precedence. This is generally not a recommended practice, but * when it does happen, the init-param should be considered more specific than the * programmatic configuration, given that it still quite possibly externalized in * hybrid web.xml + WebApplicationInitializer cases. */ @Test public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() { XmlWebApplicationContext ctx = new XmlWebApplicationContext(); ctx.setConfigLocation("programmatic.xml"); ContextLoaderListener cll = new ContextLoaderListener(ctx); MockServletContext sc = new MockServletContext(); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml"); try { cll.contextInitialized(new ServletContextEvent(sc)); fail("expected exception"); } catch (Throwable t) { // assert that an attempt was made to load the correct XML assertTrue(t.getMessage(), t.getMessage().endsWith( "Could not open ServletContext resource [/from-init-param.xml]")); } }
Example #11
Source File: ViewResolverTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void testCacheRemoval() throws Exception { StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(new MockServletContext()); wac.refresh(); InternalResourceViewResolver vr = new InternalResourceViewResolver(); vr.setViewClass(JstlView.class); vr.setApplicationContext(wac); View view = vr.resolveViewName("example1", Locale.getDefault()); View cached = vr.resolveViewName("example1", Locale.getDefault()); if (view != cached) { fail("Caching doesn't work"); } vr.removeFromCache("example1", Locale.getDefault()); cached = vr.resolveViewName("example1", Locale.getDefault()); if (view == cached) { // the chance of having the same reference (hashCode) twice if negligible). fail("View wasn't removed from cache"); } }
Example #12
Source File: FreeMarkerMacroTests.java From spring-analysis-note 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 #13
Source File: HtmlEscapeTagTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void htmlEscapeTagWithContextParamTrue() throws JspException { PageContext pc = createPageContext(); MockServletContext sc = (MockServletContext) pc.getServletContext(); sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "true"); HtmlEscapeTag tag = new HtmlEscapeTag(); tag.setDefaultHtmlEscape(false); tag.setPageContext(pc); tag.doStartTag(); assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape()); tag.setDefaultHtmlEscape(true); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape()); tag.setDefaultHtmlEscape(false); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape()); }
Example #14
Source File: ResourceHttpRequestHandlerTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-13658 public void getResourceWithRegisteredMediaType() throws Exception { ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean(); factory.addMediaType("bar", new MediaType("foo", "bar")); factory.afterPropertiesSet(); ContentNegotiationManager manager = factory.getObject(); List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass())); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setServletContext(new MockServletContext()); handler.setLocations(paths); handler.setContentNegotiationManager(manager); handler.afterPropertiesSet(); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.bar"); handler.handleRequest(this.request, this.response); assertEquals("foo/bar", this.response.getContentType()); assertEquals("h1 { color:red; }", this.response.getContentAsString()); }
Example #15
Source File: FreeMarkerMacroTests.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(); fc = new FreeMarkerConfigurer(); fc.setTemplateLoaderPaths("classpath:/", "file://" + System.getProperty("java.io.tmpdir")); 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 #16
Source File: InternalResourceViewTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void forward() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myservlet/handler.do"); request.setContextPath("/mycontext"); request.setServletPath("/myservlet"); request.setPathInfo(";mypathinfo"); request.setQueryString("?param1=value1"); view.setUrl(url); view.setServletContext(new MockServletContext() { @Override public int getMinorVersion() { return 4; } }); view.render(model, request, response); assertEquals(url, response.getForwardedUrl()); model.forEach((key, value) -> assertEquals("Values for model key '" + key + "' must match", value, request.getAttribute(key))); }
Example #17
Source File: ViewResolverTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testXmlViewResolverDefaultLocation() { StaticWebApplicationContext wac = new StaticWebApplicationContext() { @Override protected Resource getResourceByPath(String path) { assertTrue("Correct default location", XmlViewResolver.DEFAULT_LOCATION.equals(path)); return super.getResourceByPath(path); } }; wac.setServletContext(new MockServletContext()); wac.refresh(); XmlViewResolver vr = new XmlViewResolver(); try { vr.setApplicationContext(wac); vr.afterPropertiesSet(); fail("Should have thrown BeanDefinitionStoreException"); } catch (BeanDefinitionStoreException ex) { // expected } }
Example #18
Source File: RequestContextListenerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void requestContextListenerWithSameThreadAndAttributesGone() { RequestContextListener listener = new RequestContextListener(); MockServletContext context = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(context); request.setAttribute("test", "value"); assertNull(RequestContextHolder.getRequestAttributes()); listener.requestInitialized(new ServletRequestEvent(context, request)); assertNotNull(RequestContextHolder.getRequestAttributes()); assertEquals("value", RequestContextHolder.getRequestAttributes().getAttribute("test", RequestAttributes.SCOPE_REQUEST)); MockRunnable runnable = new MockRunnable(); RequestContextHolder.getRequestAttributes().registerDestructionCallback( "test", runnable, RequestAttributes.SCOPE_REQUEST); request.clearAttributes(); listener.requestDestroyed(new ServletRequestEvent(context, request)); assertNull(RequestContextHolder.getRequestAttributes()); assertTrue(runnable.wasExecuted()); }
Example #19
Source File: HtmlEscapeTagTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void htmlEscapeTagWithContextParamTrue() throws JspException { PageContext pc = createPageContext(); MockServletContext sc = (MockServletContext) pc.getServletContext(); sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "true"); HtmlEscapeTag tag = new HtmlEscapeTag(); tag.setDefaultHtmlEscape(false); tag.setPageContext(pc); tag.doStartTag(); assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape()); tag.setDefaultHtmlEscape(true); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape()); tag.setDefaultHtmlEscape(false); assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE); assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape()); }
Example #20
Source File: ResourceHttpRequestHandlerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test // SPR-14577 public void getMediaTypeWithFavorPathExtensionOff() throws Exception { ContentNegotiationManagerFactoryBean factory = new ContentNegotiationManagerFactoryBean(); factory.setFavorPathExtension(false); factory.afterPropertiesSet(); ContentNegotiationManager manager = factory.getObject(); List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass())); ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler(); handler.setServletContext(new MockServletContext()); handler.setLocations(paths); handler.setContentNegotiationManager(manager); handler.afterPropertiesSet(); this.request.addHeader("Accept", "application/json,text/plain,*/*"); this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "foo.html"); handler.handleRequest(this.request, this.response); assertEquals("text/html", this.response.getContentType()); }
Example #21
Source File: MvcUriComponentsBuilderTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testFromMappingName() throws Exception { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setServletContext(new MockServletContext()); context.register(WebConfig.class); context.refresh(); this.request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, context); this.request.setServerName("example.org"); this.request.setServerPort(9999); this.request.setContextPath("/base"); String mappingName = "PAC#getAddressesForCountry"; String url = MvcUriComponentsBuilder.fromMappingName(mappingName).arg(0, "DE").buildAndExpand(123); assertEquals("/base/people/123/addresses/DE", url); }
Example #22
Source File: ServletContextPropertyUtilsTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void fallbackToSystemProperties() { MockServletContext servletContext = new MockServletContext(); System.setProperty("test.prop", "bar"); try { String resolved = ServletContextPropertyUtils.resolvePlaceholders("${test.prop:foo}", servletContext); assertEquals("bar", resolved); } finally { System.clearProperty("test.prop"); } }
Example #23
Source File: ContextLoaderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testContextLoaderWithDefaultLocation() throws Exception { MockServletContext sc = new MockServletContext(""); ServletContextListener listener = new ContextLoaderListener(); ServletContextEvent event = new ServletContextEvent(sc); try { listener.contextInitialized(event); fail("Should have thrown BeanDefinitionStoreException"); } catch (BeanDefinitionStoreException ex) { // expected assertTrue(ex.getCause() instanceof IOException); assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml")); } }
Example #24
Source File: BaseViewTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void dynamicModelOverridesStaticAttributesIfCollision() 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); tv.setApplicationContext(wac); Properties p = new Properties(); p.setProperty("one", "bar"); p.setProperty("something", "else"); tv.setAttributes(p); Map<String, Object> model = new HashMap<>(); model.put("one", new HashMap<>()); model.put("two", new Object()); tv.render(model, request, response); // Check it contains all checkContainsAll(model, tv.model); assertEquals(3, tv.model.size()); assertEquals("else", tv.model.get("something")); assertTrue(tv.initialized); }
Example #25
Source File: ServletContextSupportTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testServletContextResourcePatternResolverWithUnboundedPatternPath() throws IOException { final Set<String> dirs = new HashSet<>(); dirs.add("/WEB-INF/mydir1/"); dirs.add("/WEB-INF/mydir2/"); final Set<String> paths = new HashSet<>(); paths.add("/WEB-INF/mydir2/context2.xml"); paths.add("/WEB-INF/mydir2/mydir3/"); MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") { @Override public Set<String> getResourcePaths(String path) { if ("/WEB-INF/".equals(path)) { return dirs; } if ("/WEB-INF/mydir1/".equals(path)) { return Collections.singleton("/WEB-INF/mydir1/context1.xml"); } if ("/WEB-INF/mydir2/".equals(path)) { return paths; } if ("/WEB-INF/mydir2/mydir3/".equals(path)) { return Collections.singleton("/WEB-INF/mydir2/mydir3/context3.xml"); } return null; } }; ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc); Resource[] found = rpr.getResources("/WEB-INF/**/*.xml"); Set<String> foundPaths = new HashSet<>(); for (Resource resource : found) { foundPaths.add(((ServletContextResource) resource).getPath()); } assertEquals(3, foundPaths.size()); assertTrue(foundPaths.contains("/WEB-INF/mydir1/context1.xml")); assertTrue(foundPaths.contains("/WEB-INF/mydir2/context2.xml")); assertTrue(foundPaths.contains("/WEB-INF/mydir2/mydir3/context3.xml")); }
Example #26
Source File: ServletContextSupportTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testServletContextAttributeExporter() { TestBean tb = new TestBean(); Map<String, Object> attributes = new HashMap<>(); attributes.put("attr1", "value1"); attributes.put("attr2", tb); MockServletContext sc = new MockServletContext(); ServletContextAttributeExporter exporter = new ServletContextAttributeExporter(); exporter.setAttributes(attributes); exporter.setServletContext(sc); assertEquals("value1", sc.getAttribute("attr1")); assertSame(tb, sc.getAttribute("attr2")); }
Example #27
Source File: ServletContextAwareProcessorTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void servletConfigAwareWithServletContextAndServletConfig() { ServletContext servletContext = new MockServletContext(); ServletConfig servletConfig = new MockServletConfig(servletContext); ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, servletConfig); ServletConfigAwareBean bean = new ServletConfigAwareBean(); assertNull(bean.getServletConfig()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNotNull("ServletConfig should have been set", bean.getServletConfig()); assertEquals(servletConfig, bean.getServletConfig()); }
Example #28
Source File: WebApplicationContextScopeTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
private WebApplicationContext initApplicationContext(String scope) { MockServletContext sc = new MockServletContext(); GenericWebApplicationContext ac = new GenericWebApplicationContext(sc); GenericBeanDefinition bd = new GenericBeanDefinition(); bd.setBeanClass(DerivedTestBean.class); bd.setScope(scope); ac.registerBeanDefinition(NAME, bd); ac.refresh(); return ac; }
Example #29
Source File: DispatcherServletTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void dispatcherServletRefresh() throws ServletException { MockServletContext servletContext = new MockServletContext("org/springframework/web/context"); DispatcherServlet servlet = new DispatcherServlet(); servlet.init(new MockServletConfig(servletContext, "empty")); ServletContextAwareBean contextBean = (ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean"); ServletConfigAwareBean configBean = (ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean"); assertSame(servletContext, contextBean.getServletContext()); assertSame(servlet.getServletConfig(), configBean.getServletConfig()); MultipartResolver multipartResolver = servlet.getMultipartResolver(); assertNotNull(multipartResolver); servlet.refresh(); ServletContextAwareBean contextBean2 = (ServletContextAwareBean) servlet.getWebApplicationContext().getBean("servletContextAwareBean"); ServletConfigAwareBean configBean2 = (ServletConfigAwareBean) servlet.getWebApplicationContext().getBean("servletConfigAwareBean"); assertSame(servletContext, contextBean2.getServletContext()); assertSame(servlet.getServletConfig(), configBean2.getServletConfig()); assertNotSame(contextBean, contextBean2); assertNotSame(configBean, configBean2); MultipartResolver multipartResolver2 = servlet.getMultipartResolver(); assertNotSame(multipartResolver, multipartResolver2); servlet.destroy(); }
Example #30
Source File: ContextLoaderTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testContextLoaderWithInvalidLocation() throws Exception { MockServletContext sc = new MockServletContext(""); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml"); ServletContextListener listener = new ContextLoaderListener(); ServletContextEvent event = new ServletContextEvent(sc); try { listener.contextInitialized(event); fail("Should have thrown BeanDefinitionStoreException"); } catch (BeanDefinitionStoreException ex) { // expected assertTrue(ex.getCause() instanceof FileNotFoundException); } }