]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.support.simple/src/main/java/org/argeo/slc/unit/AbstractSpringTestCase.java
Attachments management
[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.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 if(getIsStartContext())
27 context.start();
28 }
29 return context;
30 }
31
32 /** Whether the context should be started after being created. */
33 protected Boolean getIsStartContext(){
34 return false;
35 }
36
37 /** Returns a bean from the underlying context */
38 protected <T> T getBean(String beanId) {
39 return (T) getContext().getBean(beanId);
40 }
41
42 protected <T> T getBean(Class<? extends T> clss) {
43 T bean = SpringUtils.loadSingleFromContext(getContext(), clss);
44 if (bean == null) {
45 throw new SlcException("Cannot retrieve a unique bean of type "
46 + clss);
47 } else {
48 return bean;
49 }
50 }
51
52 /**
53 * Th location of the application to load. The default implementation
54 * returns <i>applicationContext.xml</i> found in the same package as the
55 * test.
56 */
57 protected String getApplicationContextLocation() {
58 return inPackage("applicationContext.xml");
59 }
60
61 /**
62 * Prefixes the package of the class after converting the '.' to '/' in
63 * order to have a resource path.
64 */
65 protected String inPackage(String suffix) {
66 String prefix = getClass().getPackage().getName().replace('.', '/');
67 return prefix + '/' + suffix;
68 }
69 }