]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/unit/AbstractSpringTestCase.java
Introduce org.argeo.slc.support.simple
[gpl/argeo-slc.git] / runtime / org.argeo.slc.support.simple / src / main / java / org / argeo / slc / unit / AbstractSpringTestCase.java
1 package org.argeo.slc.unit;
2
3 import junit.framework.TestCase;
4
5 import org.apache.commons.logging.Log;
6 import org.apache.commons.logging.LogFactory;
7 import org.argeo.slc.core.SlcException;
8 import org.argeo.slc.spring.SpringUtils;
9 import org.springframework.context.ConfigurableApplicationContext;
10 import org.springframework.context.support.ClassPathXmlApplicationContext;
11
12 /** Helper for tests using a Spring application co,text. */
13 public abstract class AbstractSpringTestCase extends TestCase {
14 protected final Log log = LogFactory.getLog(getClass());
15 private ConfigurableApplicationContext context;
16
17 /**
18 * Gets (and create if necessary) the application context to use. Default
19 * implementation uses a class path xml application context and calls
20 * {@link #getApplicationContextLocation()}.
21 */
22 protected ConfigurableApplicationContext getContext() {
23 if (context == null) {
24 context = new ClassPathXmlApplicationContext(
25 getApplicationContextLocation());
26 }
27 return context;
28 }
29
30 /** Returns a bean from the underlying context */
31 protected <T> T getBean(String beanId) {
32 return (T) getContext().getBean(beanId);
33 }
34
35 protected <T> T getBean(Class<? extends T> clss) {
36 T bean = SpringUtils.loadSingleFromContext(getContext(), clss);
37 if (bean == null) {
38 throw new SlcException("Cannot retrieve a unique bean of type "
39 + clss);
40 } else {
41 return bean;
42 }
43 }
44
45 /**
46 * Th location of the application to load. The default implementation
47 * returns <i>applicationContext.xml</i> found in the same package as the
48 * test.
49 */
50 protected String getApplicationContextLocation() {
51 return inPackage("applicationContext.xml");
52 }
53
54 /**
55 * Prefixes the package of the class after converting the '.' to '/' in
56 * order to have a resource path.
57 */
58 protected String inPackage(String suffix) {
59 String prefix = getClass().getPackage().getName().replace('.', '/');
60 return prefix + '/' + suffix;
61 }
62 }