]> git.argeo.org Git - gpl/argeo-slc.git/blob - legacy/org.argeo.slc.spring/ext/test/org/argeo/slc/core/test/context/AbstractInternalSpringTestCase.java
Prepare next development cacle
[gpl/argeo-slc.git] / legacy / org.argeo.slc.spring / ext / test / org / argeo / slc / core / test / context / AbstractInternalSpringTestCase.java
1 package org.argeo.slc.core.test.context;
2
3 import java.util.Map;
4
5 import junit.framework.TestCase;
6
7 import org.argeo.api.cms.CmsLog;
8 import org.argeo.slc.SlcException;
9 import org.springframework.beans.factory.BeanFactoryUtils;
10 import org.springframework.beans.factory.ListableBeanFactory;
11 import org.springframework.context.ConfigurableApplicationContext;
12 import org.springframework.context.support.ClassPathXmlApplicationContext;
13
14 /** Helper for tests using a Spring application context. */
15 public abstract class AbstractInternalSpringTestCase extends TestCase {
16 protected final CmsLog log = CmsLog.getLog(getClass());
17 private ConfigurableApplicationContext context;
18
19 /**
20 * Gets (and create if necessary) the application context to use. Default
21 * implementation uses a class path xml application context and calls
22 * {@link #getApplicationContextLocation()}.
23 */
24 protected ConfigurableApplicationContext getContext() {
25 if (context == null) {
26 context = new ClassPathXmlApplicationContext(
27 getApplicationContextLocation());
28 }
29 return context;
30 }
31
32 /** Returns a bean from the underlying context */
33 @SuppressWarnings(value = { "unchecked" })
34 protected <T> T getBean(String beanId) {
35 return (T) getContext().getBean(beanId);
36 }
37
38 protected <T> T getBean(Class<? extends T> clss) {
39 T bean = loadSingleFromContext(getContext(), clss);
40 if (bean == null) {
41 throw new SlcException("Cannot retrieve a unique bean of type "
42 + clss);
43 } else {
44 return bean;
45 }
46 }
47
48 /**
49 * Th location of the application to load. The default implementation
50 * returns <i>applicationContext.xml</i> found in the same package as the
51 * test.
52 */
53 protected String getApplicationContextLocation() {
54 return inPackage("applicationContext.xml");
55 }
56
57 /**
58 * Prefixes the package of the class after converting the '.' to '/' in
59 * order to have a resource path.
60 */
61 protected String inPackage(String suffix) {
62 String prefix = getClass().getPackage().getName().replace('.', '/');
63 return prefix + '/' + suffix;
64 }
65
66 @SuppressWarnings(value = { "unchecked" })
67 protected <T> T loadSingleFromContext(ListableBeanFactory context,
68 Class<T> clss) {
69 Map<String, T> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
70 context, clss, false, false);
71 if (beans.size() == 1) {
72 return beans.values().iterator().next();
73 } else if (beans.size() > 1) {
74 if (log.isDebugEnabled()) {
75 log
76 .debug(("Found more that on bean for type " + clss
77 + ": " + beans.keySet()));
78 }
79 return null;
80 } else {
81 return null;
82 }
83 }
84
85 }