moving unit tests from .testsuite -> .web.servlet

This commit is contained in:
Chris Beams 2008-12-15 22:49:08 +00:00
parent b8a8ceae91
commit 489427c3be
58 changed files with 1687 additions and 90 deletions

View File

@ -1,35 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context;
import javax.servlet.ServletContext;
/**
* @author Juergen Hoeller
*/
public class ServletContextAwareBean implements ServletContextAware {
private ServletContext servletContext;
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
public ServletContext getServletContext() {
return servletContext;
}
}

View File

@ -0,0 +1,197 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.context;
import java.util.Locale;
import javax.servlet.ServletException;
import org.springframework.beans.BeansException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.AbstractApplicationContextTests;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.TestListener;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
/**
* Should ideally be eliminated. Copied when splitting .testsuite up into individual bundles.
*
* @see org.springframework.web.context.XmlWebApplicationContextTests
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
*/
public abstract class AbstractXmlWebApplicationContextTests extends AbstractApplicationContextTests {
private ConfigurableWebApplicationContext root;
protected ConfigurableApplicationContext createContext() throws Exception {
InitAndIB.constructed = false;
root = new XmlWebApplicationContext();
MockServletContext sc = new MockServletContext("");
root.setServletContext(sc);
root.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"});
root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof TestBean) {
((TestBean) bean).getFriends().add("myFriend");
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
return bean;
}
});
}
});
root.refresh();
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.setParent(root);
wac.setServletContext(sc);
wac.setNamespace("test-servlet");
wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
wac.refresh();
return wac;
}
/**
* Overridden as we can't trust superclass method
* @see org.springframework.context.AbstractApplicationContextTests#testEvents()
*/
public void testEvents() throws Exception {
TestListener listener = (TestListener) this.applicationContext.getBean("testListener");
listener.zeroCounter();
TestListener parentListener = (TestListener) this.applicationContext.getParent().getBean("parentListener");
parentListener.zeroCounter();
parentListener.zeroCounter();
assertTrue("0 events before publication", listener.getEventCount() == 0);
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
}
public void testCount() {
assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(),
this.applicationContext.getBeanDefinitionCount() == 14);
}
public void testWithoutMessageSource() 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));
}
public void testContextNesting() {
TestBean father = (TestBean) this.applicationContext.getBean("father");
assertTrue("Bean from root context", father != null);
assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend"));
TestBean rod = (TestBean) this.applicationContext.getBean("rod");
assertTrue("Bean from child context", "Rod".equals(rod.getName()));
assertTrue("Bean has external reference", rod.getSpouse() == father);
assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend"));
rod = (TestBean) this.root.getBean("rod");
assertTrue("Bean from root context", "Roderick".equals(rod.getName()));
assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend"));
}
public void testInitializingBeanAndInitMethod() throws Exception {
assertFalse(InitAndIB.constructed);
InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib");
assertTrue(InitAndIB.constructed);
assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked);
assertTrue(!iib.destroyed && !iib.customDestroyed);
this.applicationContext.close();
assertTrue(!iib.destroyed && !iib.customDestroyed);
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) this.applicationContext.getParent();
parent.close();
assertTrue(iib.destroyed && iib.customDestroyed);
parent.close();
assertTrue(iib.destroyed && iib.customDestroyed);
}
public static class InitAndIB implements InitializingBean, DisposableBean {
public static boolean constructed;
public boolean afterPropertiesSetInvoked, initMethodInvoked, destroyed, customDestroyed;
public InitAndIB() {
constructed = true;
}
public void afterPropertiesSet() {
if (this.initMethodInvoked)
fail();
this.afterPropertiesSetInvoked = true;
}
/** Init method */
public void customInit() throws ServletException {
if (!this.afterPropertiesSetInvoked)
fail();
this.initMethodInvoked = true;
}
public void destroy() {
if (this.customDestroyed)
fail();
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
this.destroyed = true;
}
public void customDestroy() {
if (!this.destroyed)
fail();
if (this.customDestroyed) {
throw new IllegalStateException("Already customDestroyed");
}
this.customDestroyed = true;
}
}
}

View File

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/portlet/context/WEB-INF/contextInclude.xml">
]>
<beans>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/../resources/themeSource.xml"/>
<bean id="lifecyclePostProcessor" class="org.springframework.beans.factory.LifecycleBean$PostProcessor"/>
<!--
<bean
name="performanceMonitor" class="org.springframework.context.support.TestListener"
/>
-->
<!--
<bean name="aca" class="org.springframework.context.ACATest">
</bean>
<bean name="aca-prototype" class="org.springframework.context.ACATest" scope="prototype">
</bean>
-->
<bean id="beanThatListens" class="org.springframework.context.BeanThatListens"/>
<bean id="parentListener" class="org.springframework.context.TestListener"/>
<!-- Inherited tests -->
<!-- name and age values will be overridden by myinit.properties" -->
<bean id="rod" class="org.springframework.beans.TestBean">
<property name="name">
<value>dummy</value>
</property>
<property name="age">
<value>-1</value>
</property>
</bean>
<!--
Tests of lifecycle callbacks
-->
<bean id="mustBeInitialized"
class="org.springframework.beans.factory.MustBeInitialized">
</bean>
<bean id="lifecycle"
class="org.springframework.context.LifecycleContextBean"
init-method="declaredInitMethod">
<property name="initMethodDeclared"><value>true</value></property>
</bean>
&contextInclude;
<bean id="myOverride" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location">
<value>/org/springframework/web/portlet/context/WEB-INF/myoverride.properties</value>
</property>
</bean>
<bean id="myPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/org/springframework/web/portlet/context/WEB-INF/myplace*.properties</value>
<value>classpath:/org/springframework/web/portlet/context/WEB-INF/myover*.properties</value>
</list>
</property>
</bean>
<bean id="init-and-ib"
class="org.springframework.web.portlet.context.AbstractXmlWebApplicationContextTests$InitAndIB"
lazy-init="true"
init-method="customInit"
destroy-method="customDestroy"
/>
</beans>

View File

@ -0,0 +1,4 @@
useCodeAsDefaultMessage=false
message-file=context-messages
objectName=test:service=myservice
theme-base=org/springframework/web/portlet/context/WEB-INF/

View File

@ -3,7 +3,7 @@
<beans> <beans>
<import resource="classpath:/org/springframework/web/context/WEB-INF/test-servlet.xml"/> <import resource="classpath:/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml"/>
<bean id="portletContextAwareBean" class="org.springframework.web.portlet.context.PortletContextAwareBean"/> <bean id="portletContextAwareBean" class="org.springframework.web.portlet.context.PortletContextAwareBean"/>

View File

@ -30,14 +30,14 @@ import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException; import org.springframework.context.NoSuchMessageException;
import org.springframework.mock.web.portlet.MockPortletConfig; import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext; import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.web.context.XmlWebApplicationContextTests;
/** /**
* @author Rod Johnson * @author Rod Johnson
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Mark Fisher * @author Mark Fisher
* @author Chris Beams
*/ */
public class XmlPortletApplicationContextTests extends XmlWebApplicationContextTests { public class XmlPortletApplicationContextTests extends AbstractXmlWebApplicationContextTests {
private ConfigurablePortletApplicationContext root; private ConfigurablePortletApplicationContext root;
@ -46,7 +46,7 @@ public class XmlPortletApplicationContextTests extends XmlWebApplicationContextT
PortletContext portletContext = new MockPortletContext(); PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext); PortletConfig portletConfig = new MockPortletConfig(portletContext);
root.setPortletConfig(portletConfig); root.setPortletConfig(portletConfig);
root.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"}); root.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml"});
root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.addBeanPostProcessor(new BeanPostProcessor() { beanFactory.addBeanPostProcessor(new BeanPostProcessor() {

View File

@ -0,0 +1,172 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
/**
* Simple factory to allow testing of FactoryBean support in AbstractBeanFactory.
* Depending on whether its singleton property is set, it will return a singleton
* or a prototype instance.
*
* <p>Implements InitializingBean interface, so we can check that
* factories get this lifecycle callback if they want.
*
* @author Rod Johnson
* @since 10.03.2003
*/
public class DummyFactory
implements FactoryBean, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
public static final String SINGLETON_NAME = "Factory singleton";
private static boolean prototypeCreated;
/**
* Clear static state.
*/
public static void reset() {
prototypeCreated = false;
}
/**
* Default is for factories to return a singleton instance.
*/
private boolean singleton = true;
private String beanName;
private AutowireCapableBeanFactory beanFactory;
private boolean postProcessed;
private boolean initialized;
private TestBean testBean;
private TestBean otherTestBean;
public DummyFactory() {
this.testBean = new TestBean();
this.testBean.setName(SINGLETON_NAME);
this.testBean.setAge(25);
}
/**
* Return if the bean managed by this factory is a singleton.
* @see FactoryBean#isSingleton()
*/
public boolean isSingleton() {
return this.singleton;
}
/**
* Set if the bean managed by this factory is a singleton.
*/
public void setSingleton(boolean singleton) {
this.singleton = singleton;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = (AutowireCapableBeanFactory) beanFactory;
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(this.testBean, this.beanName);
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() {
return postProcessed;
}
public void setOtherTestBean(TestBean otherTestBean) {
this.otherTestBean = otherTestBean;
this.testBean.setSpouse(otherTestBean);
}
public TestBean getOtherTestBean() {
return otherTestBean;
}
public void afterPropertiesSet() {
if (initialized) {
throw new RuntimeException("Cannot call afterPropertiesSet twice on the one bean");
}
this.initialized = true;
}
/**
* Was this initialized by invocation of the
* afterPropertiesSet() method from the InitializingBean interface?
*/
public boolean wasInitialized() {
return initialized;
}
public static boolean wasPrototypeCreated() {
return prototypeCreated;
}
/**
* Return the managed object, supporting both singleton
* and prototype mode.
* @see FactoryBean#getObject()
*/
public Object getObject() throws BeansException {
if (isSingleton()) {
return this.testBean;
}
else {
TestBean prototype = new TestBean("prototype created at " + System.currentTimeMillis(), 11);
if (this.beanFactory != null) {
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(prototype, this.beanName);
}
prototypeCreated = true;
return prototype;
}
}
public Class getObjectType() {
return TestBean.class;
}
public void destroy() {
if (this.testBean != null) {
this.testBean.setName(null);
}
}
}

View File

@ -0,0 +1,158 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* Simple test of BeanFactory initialization and lifecycle callbacks.
*
* @author Rod Johnson
* @author Colin Sampaleanu
* @since 12.03.2003
*/
public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
protected boolean initMethodDeclared = false;
protected String beanName;
protected BeanFactory owningFactory;
protected boolean postProcessedBeforeInit;
protected boolean inited;
protected boolean initedViaDeclaredInitMethod;
protected boolean postProcessedAfterInit;
protected boolean destroyed;
public void setInitMethodDeclared(boolean initMethodDeclared) {
this.initMethodDeclared = initMethodDeclared;
}
public boolean isInitMethodDeclared() {
return initMethodDeclared;
}
public void setBeanName(String name) {
this.beanName = name;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.owningFactory = beanFactory;
}
public void postProcessBeforeInit() {
if (this.inited || this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet");
}
if (this.postProcessedBeforeInit) {
throw new RuntimeException("Factory called postProcessBeforeInit twice");
}
this.postProcessedBeforeInit = true;
}
public void afterPropertiesSet() {
if (this.owningFactory == null) {
throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean");
}
if (!this.postProcessedBeforeInit) {
throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet");
}
if (this.inited) {
throw new RuntimeException("Factory called afterPropertiesSet twice");
}
this.inited = true;
}
public void declaredInitMethod() {
if (!this.inited) {
throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called declared init method twice");
}
this.initedViaDeclaredInitMethod = true;
}
public void postProcessAfterInit() {
if (!this.inited) {
throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet");
}
if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method");
}
if (this.postProcessedAfterInit) {
throw new RuntimeException("Factory called postProcessAfterInit twice");
}
this.postProcessedAfterInit = true;
}
/**
* Dummy business method that will fail unless the factory
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) ||
!this.postProcessedAfterInit) {
throw new RuntimeException("Factory didn't initialize lifecycle object correctly");
}
}
public void destroy() {
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
this.destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
public static class PostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessBeforeInit();
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessAfterInit();
}
return bean;
}
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.factory.InitializingBean;
/**
* Simple test of BeanFactory initialization
* @author Rod Johnson
* @since 12.03.2003
*/
public class MustBeInitialized implements InitializingBean {
private boolean inited;
/**
* @see InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
this.inited = true;
}
/**
* Dummy business method that will fail unless the factory
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited)
throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
}
}

View File

@ -0,0 +1,75 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.access;
import java.util.List;
/**
* Scrap bean for use in tests.
*
* @author Colin Sampaleanu
*/
public class TestBean {
private String name;
private List list;
private Object objRef;
/**
* @return Returns the name.
*/
public String getName() {
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name) {
this.name = name;
}
/**
* @return Returns the list.
*/
public List getList() {
return list;
}
/**
* @param list The list to set.
*/
public void setList(List list) {
this.list = list;
}
/**
* @return Returns the object.
*/
public Object getObjRef() {
return objRef;
}
/**
* @param object The object to set.
*/
public void setObjRef(Object object) {
this.objRef = object;
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.NoSuchMessageException;
public class ACATester implements ApplicationContextAware {
private ApplicationContext ac;
public void setApplicationContext(ApplicationContext ctx) throws ApplicationContextException {
// check reinitialization
if (this.ac != null) {
throw new IllegalStateException("Already initialized");
}
// check message source availability
if (ctx != null) {
try {
ctx.getMessage("code1", null, Locale.getDefault());
}
catch (NoSuchMessageException ex) {
// expected
}
}
this.ac = ctx;
}
public ApplicationContext getApplicationContext() {
return ac;
}
}

View File

@ -14,22 +14,26 @@
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.context; package org.springframework.context;
import javax.servlet.ServletConfig; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
*/ */
public class ServletConfigAwareBean implements ServletConfigAware { public class BeanThatBroadcasts implements ApplicationContextAware {
private ServletConfig servletConfig; public ApplicationContext applicationContext;
public void setServletConfig(ServletConfig servletConfig) { public int receivedCount;
this.servletConfig = servletConfig;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
if (applicationContext.getDisplayName().indexOf("listener") != -1) {
applicationContext.getBean("listener");
}
} }
public ServletConfig getServletConfig() {
return servletConfig;
}
} }

View File

@ -0,0 +1,61 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.Map;
/**
* A stub {@link ApplicationListener}.
*
* @author Thomas Risberg
* @author Juergen Hoeller
*/
public class BeanThatListens implements ApplicationListener {
private BeanThatBroadcasts beanThatBroadcasts;
private int eventCount;
public BeanThatListens() {
}
public BeanThatListens(BeanThatBroadcasts beanThatBroadcasts) {
this.beanThatBroadcasts = beanThatBroadcasts;
Map beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class);
if (!beans.isEmpty()) {
throw new IllegalStateException("Shouldn't have found any BeanThatListens instances");
}
}
public void onApplicationEvent(ApplicationEvent event) {
eventCount++;
if (beanThatBroadcasts != null) {
beanThatBroadcasts.receivedCount++;
}
}
public int getEventCount() {
return eventCount;
}
public void zero() {
eventCount = 0;
}
}

View File

@ -0,0 +1,37 @@
package org.springframework.context;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.LifecycleBean;
/**
* Simple bean to test ApplicationContext lifecycle methods for beans
*
* @author Colin Sampaleanu
* @since 03.07.2004
*/
public class LifecycleContextBean extends LifecycleBean implements ApplicationContextAware {
protected ApplicationContext owningContext;
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
if (this.owningContext != null)
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
}
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (this.owningContext == null)
throw new RuntimeException("Factory didn't call setAppliationContext before afterPropertiesSet on lifecycle bean");
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.owningFactory == null)
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
this.owningContext = applicationContext;
}
}

View File

@ -0,0 +1,28 @@
package org.springframework.context;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
/**
* Listener that maintains a global count of events.
*
* @author Rod Johnson
* @since January 21, 2001
*/
public class TestListener implements ApplicationListener {
private int eventCount;
public int getEventCount() {
return eventCount;
}
public void zeroCounter() {
eventCount = 0;
}
public void onApplicationEvent(ApplicationEvent e) {
++eventCount;
}
}

View File

@ -0,0 +1,146 @@
package org.springframework.web.context;
import java.util.Locale;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.LifecycleBean;
import org.springframework.context.ACATester;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.BeanThatListens;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.TestListener;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractApplicationContextTests extends AbstractListableBeanFactoryTests {
/** Must be supplied as XML */
public static final String TEST_NAMESPACE = "testNamespace";
protected ConfigurableApplicationContext applicationContext;
/** Subclass must register this */
protected TestListener listener = new TestListener();
protected TestListener parentListener = new TestListener();
protected void setUp() throws Exception {
this.applicationContext = createContext();
}
protected BeanFactory getBeanFactory() {
return applicationContext;
}
protected ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* Must register a TestListener.
* Must register standard beans.
* Parent must register rod with name Roderick
* and father with name Albert.
*/
protected abstract ConfigurableApplicationContext createContext() throws Exception;
public void testContextAwareSingletonWasCalledBack() throws Exception {
ACATester aca = (ACATester) applicationContext.getBean("aca");
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
Object aca2 = applicationContext.getBean("aca");
assertTrue("Same instance", aca == aca2);
assertTrue("Says is singleton", applicationContext.isSingleton("aca"));
}
public void testContextAwarePrototypeWasCalledBack() throws Exception {
ACATester aca = (ACATester) applicationContext.getBean("aca-prototype");
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
Object aca2 = applicationContext.getBean("aca-prototype");
assertTrue("NOT Same instance", aca != aca2);
assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype"));
}
public void testParentNonNull() {
assertTrue("parent isn't null", applicationContext.getParent() != null);
}
public void testGrandparentNull() {
assertTrue("grandparent is null", applicationContext.getParent().getParent() == null);
}
public void testOverrideWorked() throws Exception {
TestBean rod = (TestBean) applicationContext.getParent().getBean("rod");
assertTrue("Parent's name differs", rod.getName().equals("Roderick"));
}
public void testGrandparentDefinitionFound() throws Exception {
TestBean dad = (TestBean) applicationContext.getBean("father");
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testGrandparentTypedDefinitionFound() throws Exception {
TestBean dad = (TestBean) applicationContext.getBean("father", TestBean.class);
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testCloseTriggersDestroy() {
LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle");
assertTrue("Not destroyed", !lb.isDestroyed());
applicationContext.close();
if (applicationContext.getParent() != null) {
((ConfigurableApplicationContext) applicationContext.getParent()).close();
}
assertTrue("Destroyed", lb.isDestroyed());
applicationContext.close();
if (applicationContext.getParent() != null) {
((ConfigurableApplicationContext) applicationContext.getParent()).close();
}
assertTrue("Destroyed", lb.isDestroyed());
}
public void testMessageSource() throws NoSuchMessageException {
assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault()));
assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault()));
try {
applicationContext.getMessage("code0", null, Locale.getDefault());
fail("looking for code0 should throw a NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// that's how it should be
}
}
public void testEvents() throws Exception {
listener.zeroCounter();
parentListener.zeroCounter();
assertTrue("0 events before publication", listener.getEventCount() == 0);
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
}
public void testBeanAutomaticallyHearsEvents() throws Exception {
//String[] listenerNames = ((ListableBeanFactory) applicationContext).getBeanDefinitionNames(ApplicationListener.class);
//assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens"));
BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens");
b.zero();
assertTrue("0 events before publication", b.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + b.getEventCount(), b.getEventCount() == 1);
}
public static class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}
}

View File

@ -0,0 +1,321 @@
package org.springframework.web.context;
import java.beans.PropertyEditorSupport;
import java.util.StringTokenizer;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyBatchUpdateException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanIsNotAFactoryException;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.DummyFactory;
import org.springframework.beans.factory.LifecycleBean;
import org.springframework.beans.factory.MustBeInitialized;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
/**
* Subclasses must implement setUp() to initialize bean factory
* and any other variables they need.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractBeanFactoryTests extends TestCase {
protected abstract BeanFactory getBeanFactory();
/**
* Roderick beans inherits from rod, overriding name only.
*/
public void testInheritance() {
assertTrue(getBeanFactory().containsBean("rod"));
assertTrue(getBeanFactory().containsBean("roderick"));
TestBean rod = (TestBean) getBeanFactory().getBean("rod");
TestBean roderick = (TestBean) getBeanFactory().getBean("roderick");
assertTrue("not == ", rod != roderick);
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
assertTrue("rod.age is 31", rod.getAge() == 31);
assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick"));
assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge());
}
public void testGetBeanWithNullArg() {
try {
getBeanFactory().getBean(null);
fail("Can't get null bean");
}
catch (IllegalArgumentException ex) {
// OK
}
}
/**
* Test that InitializingBean objects receive the afterPropertiesSet() callback
*/
public void testInitializingBeanCallback() {
MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized");
// The dummy business method will throw an exception if the
// afterPropertiesSet() callback wasn't invoked
mbi.businessMethod();
}
/**
* Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the
* afterPropertiesSet() callback before BeanFactoryAware callbacks
*/
public void testLifecycleCallbacks() {
LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle");
Assert.assertEquals("lifecycle", lb.getBeanName());
// The dummy business method will throw an exception if the
// necessary callbacks weren't invoked in the right order.
lb.businessMethod();
assertTrue("Not destroyed", !lb.isDestroyed());
}
public void testFindsValidInstance() {
try {
Object o = getBeanFactory().getBean("rod");
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
TestBean rod = (TestBean) o;
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
assertTrue("rod.age is 31", rod.getAge() == 31);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testGetInstanceByMatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance with matching class");
}
}
public void testGetInstanceByNonmatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testGetSharedInstanceByMatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance with matching class");
}
}
public void testGetSharedInstanceByMatchingClassNoCatch() {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
public void testGetSharedInstanceByNonmatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testSharedInstancesAreEqual() {
try {
Object o = getBeanFactory().getBean("rod");
assertTrue("Rod bean1 is a TestBean", o instanceof TestBean);
Object o1 = getBeanFactory().getBean("rod");
assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean);
assertTrue("Object equals applies", o == o1);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testPrototypeInstancesAreIndependent() {
TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy");
TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy");
assertTrue("ref equal DOES NOT apply", tb1 != tb2);
assertTrue("object equal true", tb1.equals(tb2));
tb1.setAge(1);
tb2.setAge(2);
assertTrue("1 age independent = 1", tb1.getAge() == 1);
assertTrue("2 age independent = 2", tb2.getAge() == 2);
assertTrue("object equal now false", !tb1.equals(tb2));
}
public void testNotThere() {
assertFalse(getBeanFactory().containsBean("Mr Squiggle"));
try {
Object o = getBeanFactory().getBean("Mr Squiggle");
fail("Can't find missing bean");
}
catch (BeansException ex) {
//ex.printStackTrace();
//fail("Shouldn't throw exception on getting valid instance");
}
}
public void testValidEmpty() {
try {
Object o = getBeanFactory().getBean("validEmpty");
assertTrue("validEmpty bean is a TestBean", o instanceof TestBean);
TestBean ve = (TestBean) o;
assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null);
}
catch (BeansException ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on valid empty");
}
}
public void xtestTypeMismatch() {
try {
Object o = getBeanFactory().getBean("typeMismatch");
fail("Shouldn't succeed with type mismatch");
}
catch (BeanCreationException wex) {
assertEquals("typeMismatch", wex.getBeanName());
assertTrue(wex.getCause() instanceof PropertyBatchUpdateException);
PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause();
// Further tests
assertTrue("Has one error ", ex.getExceptionCount() == 1);
assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null);
assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x"));
}
}
public void testGrandparentDefinitionFoundInBeanFactory() throws Exception {
TestBean dad = (TestBean) getBeanFactory().getBean("father");
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testFactorySingleton() throws Exception {
assertTrue(getBeanFactory().isSingleton("&singletonFactory"));
assertTrue(getBeanFactory().isSingleton("singletonFactory"));
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME));
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory");
assertTrue("Singleton references ==", tb == tb2);
assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null);
}
public void testFactoryPrototype() throws Exception {
assertTrue(getBeanFactory().isSingleton("&prototypeFactory"));
assertFalse(getBeanFactory().isSingleton("prototypeFactory"));
TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory");
assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME));
TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory");
assertTrue("Prototype references !=", tb != tb2);
}
/**
* Check that we can get the factory bean itself.
* This is only possible if we're dealing with a factory
* @throws Exception
*/
public void testGetFactoryItself() throws Exception {
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
assertTrue(factory != null);
}
/**
* Check that afterPropertiesSet gets called on factory
* @throws Exception
*/
public void testFactoryIsInitialized() throws Exception {
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized());
}
/**
* It should be illegal to dereference a normal bean
* as a factory
*/
public void testRejectsFactoryGetOnNormalBean() {
try {
getBeanFactory().getBean("&rod");
fail("Shouldn't permit factory get on normal bean");
}
catch (BeanIsNotAFactoryException ex) {
// Ok
}
}
// TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory)
// and rename this class
public void testAliasing() {
BeanFactory bf = getBeanFactory();
if (!(bf instanceof ConfigurableBeanFactory)) {
return;
}
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;
String alias = "rods alias";
try {
cbf.getBean(alias);
fail("Shouldn't permit factory get on normal bean");
}
catch (NoSuchBeanDefinitionException ex) {
// Ok
assertTrue(alias.equals(ex.getBeanName()));
}
// Create alias
cbf.registerAlias("rod", alias);
Object rod = getBeanFactory().getBean("rod");
Object aliasRod = getBeanFactory().getBean(alias);
assertTrue(rod == aliasRod);
}
public static class TestBeanEditor extends PropertyEditorSupport {
public void setAsText(String text) {
TestBean tb = new TestBean();
StringTokenizer st = new StringTokenizer(text, "_");
tb.setName(st.nextToken());
tb.setAge(Integer.parseInt(st.nextToken()));
setValue(tb);
}
}
}

View File

@ -0,0 +1,73 @@
package org.springframework.web.context;
import junit.framework.Assert;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.ListableBeanFactory;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests {
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
BeanFactory bf = getBeanFactory();
if (!(bf instanceof ListableBeanFactory)) {
throw new IllegalStateException("ListableBeanFactory required");
}
return (ListableBeanFactory) bf;
}
/**
* Subclasses can override this.
*/
public void testCount() {
assertCount(13);
}
protected final void assertCount(int count) {
String[] defnames = getListableBeanFactory().getBeanDefinitionNames();
Assert.assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count);
}
public void assertTestBeanCount(int count) {
String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false);
Assert.assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " +
defNames.length, defNames.length == count);
int countIncludingFactoryBeans = count + 2;
String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true);
Assert.assertTrue("We should have " + countIncludingFactoryBeans +
" beans for class org.springframework.beans.TestBean, not " + names.length,
names.length == countIncludingFactoryBeans);
}
public void testGetDefinitionsForNoSuchClass() {
String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class);
Assert.assertTrue("No string definitions", defnames.length == 0);
}
/**
* Check that count refers to factory class, not bean class. (We don't know
* what type factories may return, and it may even change over time.)
*/
public void testGetCountForFactoryClass() {
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
}
public void testContainsBeanDefinition() {
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("rod"));
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("roderick"));
}
}

View File

@ -16,17 +16,16 @@
package org.springframework.web.context; package org.springframework.web.context;
import static org.junit.Assert.*;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.TestBean; import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
@ -43,17 +42,18 @@ import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.SimpleWebApplicationContext; import org.springframework.web.servlet.SimpleWebApplicationContext;
/** /**
* JUnit 3.8 based tests for {@link ContextLoader}, * Tests for {@link ContextLoader}, {@link ContextLoaderListener},
* {@link ContextLoaderListener}, {@link ContextLoaderServlet}, and related * {@link ContextLoaderServlet}, and related classes.
* classes.
* *
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Sam Brannen * @author Sam Brannen
* @author Chris Beams
* @since 12.08.2003 * @since 12.08.2003
*/ */
public class ContextLoaderTests extends TestCase { public class ContextLoaderTests {
public void testContextLoaderListenerWithDefaultContext() throws Exception { @Test
public void testContextLoaderListenerWithDefaultContext() {
MockServletContext sc = new MockServletContext(""); MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"/org/springframework/web/context/WEB-INF/applicationContext.xml " "/org/springframework/web/context/WEB-INF/applicationContext.xml "
@ -81,7 +81,8 @@ public class ContextLoaderTests extends TestCase {
* target="_blank">SPR-4008</a>: <em>Supply an opportunity to customize * target="_blank">SPR-4008</a>: <em>Supply an opportunity to customize
* context before calling refresh in ContextLoaders</em>. * context before calling refresh in ContextLoaders</em>.
*/ */
public void testContextLoaderListenerWithCustomizedContextLoader() throws Exception { @Test
public void testContextLoaderListenerWithCustomizedContextLoader() {
final StringBuffer buffer = new StringBuffer(); final StringBuffer buffer = new StringBuffer();
final String expectedContents = "customizeContext() was called"; final String expectedContents = "customizeContext() was called";
final MockServletContext sc = new MockServletContext(""); final MockServletContext sc = new MockServletContext("");
@ -103,13 +104,14 @@ public class ContextLoaderTests extends TestCase {
assertEquals("customizeContext() should have been called.", expectedContents, buffer.toString()); assertEquals("customizeContext() should have been called.", expectedContents, buffer.toString());
} }
@Test
public void testContextLoaderWithDefaultContextAndParent() throws Exception { public void testContextLoaderWithDefaultContextAndParent() throws Exception {
MockServletContext sc = new MockServletContext(""); MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"/org/springframework/web/context/WEB-INF/applicationContext.xml " "/org/springframework/web/context/WEB-INF/applicationContext.xml "
+ "/org/springframework/web/context/WEB-INF/context-addition.xml"); + "/org/springframework/web/context/WEB-INF/context-addition.xml");
sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_SELECTOR_PARAM, sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_SELECTOR_PARAM,
"classpath:org/springframework/beans/factory/access/ref1.xml"); "classpath:org/springframework/web/context/ref1.xml");
sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_KEY_PARAM, "a.qualified.name.of.some.sort"); sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_KEY_PARAM, "a.qualified.name.of.some.sort");
ServletContextListener listener = new ContextLoaderListener(); ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc); ServletContextEvent event = new ServletContextEvent(sc);
@ -130,6 +132,7 @@ public class ContextLoaderTests extends TestCase {
assertTrue("Destroyed", lb.isDestroyed()); assertTrue("Destroyed", lb.isDestroyed());
} }
@Test
public void testContextLoaderWithCustomContext() throws Exception { public void testContextLoaderWithCustomContext() throws Exception {
MockServletContext sc = new MockServletContext(""); MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM, sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
@ -141,6 +144,7 @@ public class ContextLoaderTests extends TestCase {
assertTrue("Correct WebApplicationContext exposed in ServletContext", wc instanceof SimpleWebApplicationContext); assertTrue("Correct WebApplicationContext exposed in ServletContext", wc instanceof SimpleWebApplicationContext);
} }
@Test
public void testContextLoaderWithInvalidLocation() throws Exception { public void testContextLoaderWithInvalidLocation() throws Exception {
MockServletContext sc = new MockServletContext(""); MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml"); sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml");
@ -156,6 +160,7 @@ public class ContextLoaderTests extends TestCase {
} }
} }
@Test
public void testContextLoaderWithInvalidContext() throws Exception { public void testContextLoaderWithInvalidContext() throws Exception {
MockServletContext sc = new MockServletContext(""); MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM, sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
@ -172,6 +177,7 @@ public class ContextLoaderTests extends TestCase {
} }
} }
@Test
public void testContextLoaderWithDefaultLocation() throws Exception { public void testContextLoaderWithDefaultLocation() throws Exception {
MockServletContext sc = new MockServletContext(""); MockServletContext sc = new MockServletContext("");
ServletContextListener listener = new ContextLoaderListener(); ServletContextListener listener = new ContextLoaderListener();
@ -187,6 +193,7 @@ public class ContextLoaderTests extends TestCase {
} }
} }
@Test
public void testFrameworkServletWithDefaultLocation() throws Exception { public void testFrameworkServletWithDefaultLocation() throws Exception {
DispatcherServlet servlet = new DispatcherServlet(); DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextClass(XmlWebApplicationContext.class); servlet.setContextClass(XmlWebApplicationContext.class);
@ -201,6 +208,7 @@ public class ContextLoaderTests extends TestCase {
} }
} }
@Test
public void testFrameworkServletWithCustomLocation() throws Exception { public void testFrameworkServletWithCustomLocation() throws Exception {
DispatcherServlet servlet = new DispatcherServlet(); DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextConfigLocation("/org/springframework/web/context/WEB-INF/testNamespace.xml " servlet.setContextConfigLocation("/org/springframework/web/context/WEB-INF/testNamespace.xml "
@ -210,6 +218,7 @@ public class ContextLoaderTests extends TestCase {
assertTrue(servlet.getWebApplicationContext().containsBean("kerryX")); assertTrue(servlet.getWebApplicationContext().containsBean("kerryX"));
} }
@Test
public void testClassPathXmlApplicationContext() throws IOException { public void testClassPathXmlApplicationContext() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext( ApplicationContext context = new ClassPathXmlApplicationContext(
"/org/springframework/web/context/WEB-INF/applicationContext.xml"); "/org/springframework/web/context/WEB-INF/applicationContext.xml");
@ -227,6 +236,7 @@ public class ContextLoaderTests extends TestCase {
assertTrue("Has kerry", context.containsBean("kerry")); assertTrue("Has kerry", context.containsBean("kerry"));
} }
@Test
public void testSingletonDestructionOnStartupFailure() throws IOException { public void testSingletonDestructionOnStartupFailure() throws IOException {
try { try {
new ClassPathXmlApplicationContext(new String[] { new ClassPathXmlApplicationContext(new String[] {

View File

@ -19,7 +19,6 @@ package org.springframework.web.context;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import org.springframework.context.AbstractApplicationContextTests;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSource; import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException; import org.springframework.context.NoSuchMessageException;

View File

@ -0,0 +1,6 @@
code1=message1
code2=message2
# Example taken from the javadocs for the java.text.MessageFormat class
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
message.format.example2=This is a test message in the message catalog with no args.

View File

@ -0,0 +1,2 @@
# Example taken from the javadocs for the java.text.MessageFormat class
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on station number {0,number,integer}.

View File

@ -0,0 +1,5 @@
code1=message1
# Example taken from the javadocs for the java.text.MessageFormat class
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
message.format.example2=This is a test message in the message catalog with no args.

View File

@ -0,0 +1,6 @@
<!-- Include snippet to be loaded via entity reference in applicationContext.xml -->
<bean id="father" class="org.springframework.beans.TestBean">
<property name="name"><value>yetanotherdummy</value></property>
</bean>

View File

@ -0,0 +1,3 @@
father.name=Albert
rod.age=31
rod.name=Roderick

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename"><value>org/springframework/web/context/WEB-INF/test-messages</value></property>
</bean>
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
<property name="basenamePrefix"><value>org/springframework/web/context/WEB-INF/test-</value></property>
</bean>
<bean id="aca" class="org.springframework.context.ACATester"/>
<bean id="aca-prototype" class="org.springframework.context.ACATester" scope="prototype"/>
<bean id="rod" class="org.springframework.beans.TestBean">
<property name="name"><value>Rod</value></property>
<property name="age"><value>31</value></property>
<property name="spouse"><ref bean="father"/></property>
</bean>
<bean id="testListener" class="org.springframework.context.TestListener"/>
<bean id="roderick" parent="rod">
<property name="name"><value>Roderick</value></property>
<property name="age"><value>31</value></property>
</bean>
<bean id="kathy" class="org.springframework.beans.TestBean" scope="prototype"/>
<bean id="kerry" class="org.springframework.beans.TestBean">
<property name="name"><value>Kerry</value></property>
<property name="age"><value>34</value></property>
<property name="spouse"><ref local="rod"/></property>
</bean>
<bean id="typeMismatch" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name"><value>typeMismatch</value></property>
<property name="age"><value>34x</value></property>
<property name="spouse"><ref local="rod"/></property>
</bean>
<bean id="singletonFactory" class="org.springframework.beans.factory.DummyFactory">
</bean>
<bean id="prototypeFactory" class="org.springframework.beans.factory.DummyFactory">
<property name="singleton"><value>false</value></property>
</bean>
<bean id="listenerVeto" class="org.springframework.beans.TestBean">
<property name="name"><value>listenerVeto</value></property>
<property name="age"><value>66</value></property>
</bean>
<bean id="validEmpty" class="org.springframework.beans.TestBean"/>
</beans>

View File

@ -27,7 +27,6 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.AbstractApplicationContextTests;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException; import org.springframework.context.NoSuchMessageException;
import org.springframework.context.TestListener; import org.springframework.context.TestListener;

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: beans1.xml,v 1.3 2006/08/20 19:08:40 jhoeller Exp $ -->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="beans1.bean1" class="org.springframework.beans.factory.access.TestBean">
<property name="name"><value>beans1.bean1</value></property>
</bean>
<bean id="beans1.bean2" class="org.springframework.beans.factory.access.TestBean">
<property name="name"><value>bean2</value></property>
<property name="objRef"><ref bean="beans1.bean2"/></property>
</bean>
</beans>

View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<!-- We are only using one definition file for the purposes of this test, since we do not have multiple
classloaders available in the environment to allow combining multiple files of the same name, but
of course the contents within could be spread out across multiple files of the same name withing
different jars -->
<beans>
<!-- this definition could be inside one beanRefFactory.xml file -->
<bean id="a.qualified.name.of.some.sort"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<property name="configLocation" value="org/springframework/web/context/beans1.xml"/>
</bean>
<!-- while the following two could be inside another, also on the classpath,
perhaps coming from another component jar -->
<bean id="another.qualified.name"
class="org.springframework.context.support.ClassPathXmlApplicationContext">
<property name="configLocation" value="org/springframework/web/context/beans1.xml"/>
<property name="parent" ref="a.qualified.name.of.some.sort"/>
</bean>
<alias name="another.qualified.name" alias="a.qualified.name.which.is.an.alias"/>
</beans>

View File

@ -16,6 +16,8 @@
package org.springframework.web.context.support; package org.springframework.web.context.support;
import static org.junit.Assert.*;
import java.io.IOException; import java.io.IOException;
import javax.servlet.Servlet; import javax.servlet.Servlet;
@ -23,8 +25,7 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase; import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig; import org.springframework.mock.web.MockServletConfig;
@ -34,10 +35,12 @@ import org.springframework.web.context.WebApplicationContext;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Chris Beams
* @since 2.0 * @since 2.0
*/ */
public class HttpRequestHandlerTests extends TestCase { public class HttpRequestHandlerTests {
@Test
public void testHttpRequestHandlerServletPassThrough() throws Exception { public void testHttpRequestHandlerServletPassThrough() throws Exception {
MockServletContext servletContext = new MockServletContext(); MockServletContext servletContext = new MockServletContext();
final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletRequest request = new MockHttpServletRequest();

View File

@ -16,6 +16,8 @@
package org.springframework.web.context.support; package org.springframework.web.context.support;
import static org.junit.Assert.*;
import java.io.IOException; import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -24,8 +26,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import junit.framework.TestCase; import org.junit.Test;
import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean; import org.springframework.beans.TestBean;
import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationException;
@ -44,10 +45,12 @@ import org.springframework.mock.web.MockServletContext;
* Tests for various ServletContext-related support classes. * Tests for various ServletContext-related support classes.
* *
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Chris Beams
* @since 22.12.2004 * @since 22.12.2004
*/ */
public class ServletContextSupportTests extends TestCase { public class ServletContextSupportTests {
@Test
public void testServletContextFactoryBean() { public void testServletContextFactoryBean() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
@ -61,6 +64,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals(sc, value); assertEquals(sc, value);
} }
@Test
public void testServletContextAttributeFactoryBean() { public void testServletContextAttributeFactoryBean() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
sc.setAttribute("myAttr", "myValue"); sc.setAttribute("myAttr", "myValue");
@ -76,6 +80,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals("myValue", value); assertEquals("myValue", value);
} }
@Test
public void testServletContextAttributeFactoryBeanWithAttributeNotFound() { public void testServletContextAttributeFactoryBeanWithAttributeNotFound() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
@ -96,6 +101,7 @@ public class ServletContextSupportTests extends TestCase {
} }
} }
@Test
public void testServletContextParameterFactoryBean() { public void testServletContextParameterFactoryBean() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
sc.addInitParameter("myParam", "myValue"); sc.addInitParameter("myParam", "myValue");
@ -111,6 +117,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals("myValue", value); assertEquals("myValue", value);
} }
@Test
public void testServletContextParameterFactoryBeanWithAttributeNotFound() { public void testServletContextParameterFactoryBeanWithAttributeNotFound() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
@ -131,9 +138,10 @@ public class ServletContextSupportTests extends TestCase {
} }
} }
@Test
public void testServletContextAttributeExporter() { public void testServletContextAttributeExporter() {
TestBean tb = new TestBean(); TestBean tb = new TestBean();
Map attributes = new HashMap(); Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("attr1", "value1"); attributes.put("attr1", "value1");
attributes.put("attr2", tb); attributes.put("attr2", tb);
@ -146,6 +154,7 @@ public class ServletContextSupportTests extends TestCase {
assertSame(tb, sc.getAttribute("attr2")); assertSame(tb, sc.getAttribute("attr2"));
} }
@Test
public void testServletContextPropertyPlaceholderConfigurer() { public void testServletContextPropertyPlaceholderConfigurer() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
sc.addInitParameter("key4", "mykey4"); sc.addInitParameter("key4", "mykey4");
@ -175,6 +184,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals(tb2, tb1.getSpouse()); assertEquals(tb2, tb1.getSpouse());
} }
@Test
public void testServletContextPropertyPlaceholderConfigurerWithLocalOverriding() { public void testServletContextPropertyPlaceholderConfigurerWithLocalOverriding() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
sc.addInitParameter("key4", "mykey4"); sc.addInitParameter("key4", "mykey4");
@ -204,6 +214,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals(tb2, tb1.getSpouse()); assertEquals(tb2, tb1.getSpouse());
} }
@Test
public void testServletContextPropertyPlaceholderConfigurerWithContextOverride() { public void testServletContextPropertyPlaceholderConfigurerWithContextOverride() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
sc.addInitParameter("key4", "mykey4"); sc.addInitParameter("key4", "mykey4");
@ -234,6 +245,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals(tb2, tb1.getSpouse()); assertEquals(tb2, tb1.getSpouse());
} }
@Test
public void testServletContextPropertyPlaceholderConfigurerWithContextOverrideAndAttributes() { public void testServletContextPropertyPlaceholderConfigurerWithContextOverrideAndAttributes() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
sc.addInitParameter("key4", "mykey4"); sc.addInitParameter("key4", "mykey4");
@ -266,6 +278,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals(tb2, tb1.getSpouse()); assertEquals(tb2, tb1.getSpouse());
} }
@Test
public void testServletContextPropertyPlaceholderConfigurerWithAttributes() { public void testServletContextPropertyPlaceholderConfigurerWithAttributes() {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
sc.addInitParameter("key4", "mykey4"); sc.addInitParameter("key4", "mykey4");
@ -284,17 +297,17 @@ public class ServletContextSupportTests extends TestCase {
cas.addGenericArgumentValue("${var}name${age}"); cas.addGenericArgumentValue("${var}name${age}");
pvs = new MutablePropertyValues(); pvs = new MutablePropertyValues();
List friends = new ManagedList(); List<Object> friends = new ManagedList<Object>();
friends.add("na${age}me"); friends.add("na${age}me");
friends.add(new RuntimeBeanReference("${ref}")); friends.add(new RuntimeBeanReference("${ref}"));
pvs.addPropertyValue("friends", friends); pvs.addPropertyValue("friends", friends);
Set someSet = new ManagedSet(); Set<Object> someSet = new ManagedSet<Object>();
someSet.add("na${age}me"); someSet.add("na${age}me");
someSet.add(new RuntimeBeanReference("${ref}")); someSet.add(new RuntimeBeanReference("${ref}"));
pvs.addPropertyValue("someSet", someSet); pvs.addPropertyValue("someSet", someSet);
Map someMap = new ManagedMap(); Map<String, Object> someMap = new ManagedMap<String, Object>();
someMap.put("key1", new RuntimeBeanReference("${ref}")); someMap.put("key1", new RuntimeBeanReference("${ref}"));
someMap.put("key2", "${age}name"); someMap.put("key2", "${age}name");
MutablePropertyValues innerPvs = new MutablePropertyValues(); MutablePropertyValues innerPvs = new MutablePropertyValues();
@ -341,6 +354,7 @@ public class ServletContextSupportTests extends TestCase {
assertEquals(System.getProperty("os.name"), inner2.getTouchy()); assertEquals(System.getProperty("os.name"), inner2.getTouchy());
} }
@Test
public void testServletContextResourceLoader() { public void testServletContextResourceLoader() {
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context"); MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context");
ServletContextResourceLoader rl = new ServletContextResourceLoader(sc); ServletContextResourceLoader rl = new ServletContextResourceLoader(sc);
@ -350,13 +364,14 @@ public class ServletContextSupportTests extends TestCase {
assertTrue(rl.getResource("/../context/WEB-INF/web.xml").exists()); assertTrue(rl.getResource("/../context/WEB-INF/web.xml").exists());
} }
@Test
public void testServletContextResourcePatternResolver() throws IOException { public void testServletContextResourcePatternResolver() throws IOException {
final Set paths = new HashSet(); final Set<String> paths = new HashSet<String>();
paths.add("/WEB-INF/context1.xml"); paths.add("/WEB-INF/context1.xml");
paths.add("/WEB-INF/context2.xml"); paths.add("/WEB-INF/context2.xml");
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") { MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
public Set getResourcePaths(String path) { public Set<String> getResourcePaths(String path) {
if ("/WEB-INF/".equals(path)) { if ("/WEB-INF/".equals(path)) {
return paths; return paths;
} }
@ -366,7 +381,7 @@ public class ServletContextSupportTests extends TestCase {
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc); ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
Resource[] found = rpr.getResources("/WEB-INF/*.xml"); Resource[] found = rpr.getResources("/WEB-INF/*.xml");
Set foundPaths = new HashSet(); Set<String> foundPaths = new HashSet<String>();
for (int i = 0; i < found.length; i++) { for (int i = 0; i < found.length; i++) {
foundPaths.add(((ServletContextResource) found[i]).getPath()); foundPaths.add(((ServletContextResource) found[i]).getPath());
} }
@ -375,13 +390,14 @@ public class ServletContextSupportTests extends TestCase {
assertTrue(foundPaths.contains("/WEB-INF/context2.xml")); assertTrue(foundPaths.contains("/WEB-INF/context2.xml"));
} }
@Test
public void testServletContextResourcePatternResolverWithPatternPath() throws IOException { public void testServletContextResourcePatternResolverWithPatternPath() throws IOException {
final Set dirs = new HashSet(); final Set<String> dirs = new HashSet<String>();
dirs.add("/WEB-INF/mydir1/"); dirs.add("/WEB-INF/mydir1/");
dirs.add("/WEB-INF/mydir2/"); dirs.add("/WEB-INF/mydir2/");
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") { MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
public Set getResourcePaths(String path) { public Set<String> getResourcePaths(String path) {
if ("/WEB-INF/".equals(path)) { if ("/WEB-INF/".equals(path)) {
return dirs; return dirs;
} }
@ -397,7 +413,7 @@ public class ServletContextSupportTests extends TestCase {
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc); ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
Resource[] found = rpr.getResources("/WEB-INF/*/*.xml"); Resource[] found = rpr.getResources("/WEB-INF/*/*.xml");
Set foundPaths = new HashSet(); Set<String> foundPaths = new HashSet<String>();
for (int i = 0; i < found.length; i++) { for (int i = 0; i < found.length; i++) {
foundPaths.add(((ServletContextResource) found[i]).getPath()); foundPaths.add(((ServletContextResource) found[i]).getPath());
} }
@ -406,17 +422,18 @@ public class ServletContextSupportTests extends TestCase {
assertTrue(foundPaths.contains("/WEB-INF/mydir2/context2.xml")); assertTrue(foundPaths.contains("/WEB-INF/mydir2/context2.xml"));
} }
@Test
public void testServletContextResourcePatternResolverWithUnboundedPatternPath() throws IOException { public void testServletContextResourcePatternResolverWithUnboundedPatternPath() throws IOException {
final Set dirs = new HashSet(); final Set<String> dirs = new HashSet<String>();
dirs.add("/WEB-INF/mydir1/"); dirs.add("/WEB-INF/mydir1/");
dirs.add("/WEB-INF/mydir2/"); dirs.add("/WEB-INF/mydir2/");
final Set paths = new HashSet(); final Set<String> paths = new HashSet<String>();
paths.add("/WEB-INF/mydir2/context2.xml"); paths.add("/WEB-INF/mydir2/context2.xml");
paths.add("/WEB-INF/mydir2/mydir3/"); paths.add("/WEB-INF/mydir2/mydir3/");
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") { MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
public Set getResourcePaths(String path) { public Set<String> getResourcePaths(String path) {
if ("/WEB-INF/".equals(path)) { if ("/WEB-INF/".equals(path)) {
return dirs; return dirs;
} }
@ -435,7 +452,7 @@ public class ServletContextSupportTests extends TestCase {
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc); ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
Resource[] found = rpr.getResources("/WEB-INF/**/*.xml"); Resource[] found = rpr.getResources("/WEB-INF/**/*.xml");
Set foundPaths = new HashSet(); Set<String> foundPaths = new HashSet<String>();
for (int i = 0; i < found.length; i++) { for (int i = 0; i < found.length; i++) {
foundPaths.add(((ServletContextResource) found[i]).getPath()); foundPaths.add(((ServletContextResource) found[i]).getPath());
} }
@ -445,14 +462,15 @@ public class ServletContextSupportTests extends TestCase {
assertTrue(foundPaths.contains("/WEB-INF/mydir2/mydir3/context3.xml")); assertTrue(foundPaths.contains("/WEB-INF/mydir2/mydir3/context3.xml"));
} }
@Test
public void testServletContextResourcePatternResolverWithAbsolutePaths() throws IOException { public void testServletContextResourcePatternResolverWithAbsolutePaths() throws IOException {
final Set paths = new HashSet(); final Set<String> paths = new HashSet<String>();
paths.add("C:/webroot/WEB-INF/context1.xml"); paths.add("C:/webroot/WEB-INF/context1.xml");
paths.add("C:/webroot/WEB-INF/context2.xml"); paths.add("C:/webroot/WEB-INF/context2.xml");
paths.add("C:/webroot/someOtherDirThatDoesntContainPath"); paths.add("C:/webroot/someOtherDirThatDoesntContainPath");
MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") { MockServletContext sc = new MockServletContext("classpath:org/springframework/web/context") {
public Set getResourcePaths(String path) { public Set<String> getResourcePaths(String path) {
if ("/WEB-INF/".equals(path)) { if ("/WEB-INF/".equals(path)) {
return paths; return paths;
} }
@ -462,7 +480,7 @@ public class ServletContextSupportTests extends TestCase {
ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc); ServletContextResourcePatternResolver rpr = new ServletContextResourcePatternResolver(sc);
Resource[] found = rpr.getResources("/WEB-INF/*.xml"); Resource[] found = rpr.getResources("/WEB-INF/*.xml");
Set foundPaths = new HashSet(); Set<String> foundPaths = new HashSet<String>();
for (int i = 0; i < found.length; i++) { for (int i = 0; i < found.length; i++) {
foundPaths.add(((ServletContextResource) found[i]).getPath()); foundPaths.add(((ServletContextResource) found[i]).getPath());
} }

View File

@ -16,10 +16,11 @@
package org.springframework.web.context.support; package org.springframework.web.context.support;
import static org.junit.Assert.*;
import java.io.File; import java.io.File;
import junit.framework.TestCase; import org.junit.Test;
import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.StaticApplicationContext; import org.springframework.context.support.StaticApplicationContext;
import org.springframework.mock.web.MockServletContext; import org.springframework.mock.web.MockServletContext;
@ -27,10 +28,12 @@ import org.springframework.web.util.WebUtils;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Chris Beams
* @since 28.08.2003 * @since 28.08.2003
*/ */
public class WebApplicationObjectSupportTests extends TestCase { public class WebApplicationObjectSupportTests {
@Test
public void testWebApplicationObjectSupport() { public void testWebApplicationObjectSupport() {
StaticWebApplicationContext wac = new StaticWebApplicationContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext()); wac.setServletContext(new MockServletContext());
@ -43,6 +46,7 @@ public class WebApplicationObjectSupportTests extends TestCase {
assertEquals(wao.getTempDir(), tempDir); assertEquals(wao.getTempDir(), tempDir);
} }
@Test
public void testWebApplicationObjectSupportWithWrongContext() { public void testWebApplicationObjectSupportWithWrongContext() {
StaticApplicationContext ac = new StaticApplicationContext(); StaticApplicationContext ac = new StaticApplicationContext();
ac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class)); ac.registerBeanDefinition("test", new RootBeanDefinition(TestWebApplicationObject.class));

View File

@ -16,6 +16,8 @@
package org.springframework.web.servlet.view; package org.springframework.web.servlet.view;
import static org.junit.Assert.*;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -31,8 +33,7 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.jstl.core.Config; import javax.servlet.jsp.jstl.core.Config;
import javax.servlet.jsp.jstl.fmt.LocalizationContext; import javax.servlet.jsp.jstl.fmt.LocalizationContext;
import junit.framework.TestCase; import org.junit.Test;
import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValue;
import org.springframework.beans.TestBean; import org.springframework.beans.TestBean;
@ -55,10 +56,12 @@ import org.springframework.web.servlet.theme.FixedThemeResolver;
/** /**
* @author Juergen Hoeller * @author Juergen Hoeller
* @author Chris Beams
* @since 18.06.2003 * @since 18.06.2003
*/ */
public class ViewResolverTests extends TestCase { public class ViewResolverTests {
@Test
public void testBeanNameViewResolver() throws ServletException { public void testBeanNameViewResolver() throws ServletException {
StaticWebApplicationContext wac = new StaticWebApplicationContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext()); wac.setServletContext(new MockServletContext());
@ -81,6 +84,7 @@ public class ViewResolverTests extends TestCase {
assertEquals("Correct URL", "/example2.jsp", ((JstlView) view).getUrl()); assertEquals("Correct URL", "/example2.jsp", ((JstlView) view).getUrl());
} }
@Test
public void testUrlBasedViewResolverWithNullViewClass() { public void testUrlBasedViewResolverWithNullViewClass() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver(); UrlBasedViewResolver resolver = new UrlBasedViewResolver();
try { try {
@ -92,22 +96,26 @@ public class ViewResolverTests extends TestCase {
} }
} }
@Test
public void testUrlBasedViewResolverWithoutPrefixes() throws Exception { public void testUrlBasedViewResolverWithoutPrefixes() throws Exception {
UrlBasedViewResolver vr = new UrlBasedViewResolver(); UrlBasedViewResolver vr = new UrlBasedViewResolver();
vr.setViewClass(JstlView.class); vr.setViewClass(JstlView.class);
doTestUrlBasedViewResolverWithoutPrefixes(vr); doTestUrlBasedViewResolverWithoutPrefixes(vr);
} }
@Test
public void testUrlBasedViewResolverWithPrefixes() throws Exception { public void testUrlBasedViewResolverWithPrefixes() throws Exception {
UrlBasedViewResolver vr = new UrlBasedViewResolver(); UrlBasedViewResolver vr = new UrlBasedViewResolver();
vr.setViewClass(JstlView.class); vr.setViewClass(JstlView.class);
doTestUrlBasedViewResolverWithPrefixes(vr); doTestUrlBasedViewResolverWithPrefixes(vr);
} }
@Test
public void testInternalResourceViewResolverWithoutPrefixes() throws Exception { public void testInternalResourceViewResolverWithoutPrefixes() throws Exception {
doTestUrlBasedViewResolverWithoutPrefixes(new InternalResourceViewResolver()); doTestUrlBasedViewResolverWithoutPrefixes(new InternalResourceViewResolver());
} }
@Test
public void testInternalResourceViewResolverWithPrefixes() throws Exception { public void testInternalResourceViewResolverWithPrefixes() throws Exception {
doTestUrlBasedViewResolverWithPrefixes(new InternalResourceViewResolver()); doTestUrlBasedViewResolverWithPrefixes(new InternalResourceViewResolver());
} }
@ -176,6 +184,7 @@ public class ViewResolverTests extends TestCase {
assertEquals("Correct URL", "myUrl", ((InternalResourceView) view).getUrl()); assertEquals("Correct URL", "myUrl", ((InternalResourceView) view).getUrl());
} }
@Test
public void testInternalResourceViewResolverWithAttributes() throws Exception { public void testInternalResourceViewResolverWithAttributes() throws Exception {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext();
@ -219,6 +228,7 @@ public class ViewResolverTests extends TestCase {
assertEquals(new Integer(2), request.getAttribute("key2")); assertEquals(new Integer(2), request.getAttribute("key2"));
} }
@Test
public void testInternalResourceViewResolverWithContextBeans() throws Exception { public void testInternalResourceViewResolverWithContextBeans() throws Exception {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
final StaticWebApplicationContext wac = new StaticWebApplicationContext(); final StaticWebApplicationContext wac = new StaticWebApplicationContext();
@ -256,6 +266,7 @@ public class ViewResolverTests extends TestCase {
view.render(new HashMap(), request, response); view.render(new HashMap(), request, response);
} }
@Test
public void testInternalResourceViewResolverWithSpecificContextBeans() throws Exception { public void testInternalResourceViewResolverWithSpecificContextBeans() throws Exception {
MockServletContext sc = new MockServletContext(); MockServletContext sc = new MockServletContext();
final StaticWebApplicationContext wac = new StaticWebApplicationContext(); final StaticWebApplicationContext wac = new StaticWebApplicationContext();
@ -293,6 +304,7 @@ public class ViewResolverTests extends TestCase {
view.render(new HashMap(), request, response); view.render(new HashMap(), request, response);
} }
@Test
public void testInternalResourceViewResolverWithJstl() throws Exception { public void testInternalResourceViewResolverWithJstl() throws Exception {
Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH; Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH;
@ -330,6 +342,7 @@ public class ViewResolverTests extends TestCase {
assertEquals("messageX", lc.getResourceBundle().getString("code1")); assertEquals("messageX", lc.getResourceBundle().getString("code1"));
} }
@Test
public void testInternalResourceViewResolverWithJstlAndContextParam() throws Exception { public void testInternalResourceViewResolverWithJstlAndContextParam() throws Exception {
Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH; Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH;
@ -369,6 +382,7 @@ public class ViewResolverTests extends TestCase {
assertEquals("message2", lc.getResourceBundle().getString("code2")); assertEquals("message2", lc.getResourceBundle().getString("code2"));
} }
@Test
public void testXmlViewResolver() throws Exception { public void testXmlViewResolver() throws Exception {
StaticWebApplicationContext wac = new StaticWebApplicationContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.registerSingleton("testBean", TestBean.class); wac.registerSingleton("testBean", TestBean.class);
@ -413,6 +427,7 @@ public class ViewResolverTests extends TestCase {
assertTrue("Correct test2 attribute", "testvalue2".equals(request.getAttribute("test2"))); assertTrue("Correct test2 attribute", "testvalue2".equals(request.getAttribute("test2")));
} }
@Test
public void testXmlViewResolverDefaultLocation() { public void testXmlViewResolverDefaultLocation() {
StaticWebApplicationContext wac = new StaticWebApplicationContext() { StaticWebApplicationContext wac = new StaticWebApplicationContext() {
protected Resource getResourceByPath(String path) { protected Resource getResourceByPath(String path) {
@ -432,6 +447,7 @@ public class ViewResolverTests extends TestCase {
} }
} }
@Test
public void testXmlViewResolverWithoutCache() throws Exception { public void testXmlViewResolverWithoutCache() throws Exception {
StaticWebApplicationContext wac = new StaticWebApplicationContext() { StaticWebApplicationContext wac = new StaticWebApplicationContext() {
protected Resource getResourceByPath(String path) { protected Resource getResourceByPath(String path) {
@ -458,6 +474,7 @@ public class ViewResolverTests extends TestCase {
} }
} }
@Test
public void testCacheRemoval() throws Exception { public void testCacheRemoval() throws Exception {
StaticWebApplicationContext wac = new StaticWebApplicationContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext()); wac.setServletContext(new MockServletContext());