-package org.argeo.slc.unit.internal;\r
-\r
-import java.util.Map;\r
-\r
-import junit.framework.TestCase;\r
-\r
-import org.apache.commons.logging.Log;\r
-import org.apache.commons.logging.LogFactory;\r
-import org.argeo.slc.SlcException;\r
-import org.springframework.beans.factory.BeanFactoryUtils;\r
-import org.springframework.beans.factory.ListableBeanFactory;\r
-import org.springframework.context.ConfigurableApplicationContext;\r
-import org.springframework.context.support.ClassPathXmlApplicationContext;\r
-\r
-/** Helper for tests using a Spring application co,text. */\r
-public abstract class AbstractSpringTestCase extends TestCase {\r
- protected final Log log = LogFactory.getLog(getClass());\r
- private ConfigurableApplicationContext context;\r
-\r
- /**\r
- * Gets (and create if necessary) the application context to use. Default\r
- * implementation uses a class path xml application context and calls\r
- * {@link #getApplicationContextLocation()}.\r
- */\r
- protected ConfigurableApplicationContext getContext() {\r
- if (context == null) {\r
- context = new ClassPathXmlApplicationContext(\r
- getApplicationContextLocation());\r
- if (getIsStartContext())\r
- context.start();\r
- }\r
- return context;\r
- }\r
-\r
- /** Whether the context should be started after being created. */\r
- protected Boolean getIsStartContext() {\r
- return false;\r
- }\r
-\r
- /** Returns a bean from the underlying context */\r
- @SuppressWarnings(value = { "unchecked" })\r
- protected <T> T getBean(String beanId) {\r
- return (T) getContext().getBean(beanId);\r
- }\r
-\r
- protected <T> T getBean(Class<? extends T> clss) {\r
- T bean = loadSingleFromContext(getContext(), clss);\r
- if (bean == null) {\r
- throw new SlcException("Cannot retrieve a unique bean of type "\r
- + clss);\r
- } else {\r
- return bean;\r
- }\r
- }\r
-\r
- /**\r
- * Th location of the application to load. The default implementation\r
- * returns <i>applicationContext.xml</i> found in the same package as the\r
- * test.\r
- */\r
- protected String getApplicationContextLocation() {\r
- return inPackage("applicationContext.xml");\r
- }\r
-\r
- /**\r
- * Prefixes the package of the class after converting the '.' to '/' in\r
- * order to have a resource path.\r
- */\r
- protected String inPackage(String suffix) {\r
- String prefix = getClass().getPackage().getName().replace('.', '/');\r
- return prefix + '/' + suffix;\r
- }\r
-\r
- @SuppressWarnings(value = { "unchecked" })\r
- protected <T> T loadSingleFromContext(ListableBeanFactory context,\r
- Class<T> clss) {\r
- Map<String, T> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(\r
- context, clss, false, false);\r
- if (beans.size() == 1) {\r
- return beans.values().iterator().next();\r
- } else if (beans.size() > 1) {\r
- if (log.isDebugEnabled()) {\r
- log\r
- .debug(("Found more that on bean for type " + clss\r
- + ": " + beans.keySet()));\r
- }\r
- return null;\r
- } else {\r
- return null;\r
- }\r
- }\r
-\r
-}\r