]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/main/java/org/argeo/slc/unit/AbstractSpringTestCase.java
Introduce Hibernate lazy loading
[gpl/argeo-slc.git] / org.argeo.slc.core / 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.springframework.context.ApplicationContext;
6 import org.springframework.context.ConfigurableApplicationContext;
7 import org.springframework.context.support.ClassPathXmlApplicationContext;
8
9 import org.apache.commons.logging.Log;
10 import org.apache.commons.logging.LogFactory;
11
12 import org.argeo.slc.core.SlcException;
13 import org.argeo.slc.spring.SpringUtils;
14
15 /** Helper for tests using a Spring application co,text. */
16 public abstract class AbstractSpringTestCase extends TestCase {
17 protected final Log log = LogFactory.getLog(getClass());
18 private ConfigurableApplicationContext context;
19
20 /**
21 * Gets (and create if necessary) the application context to use. Default
22 * implementation uses a class path xml application context and calls
23 * {@link #getApplicationContextLocation()}.
24 */
25 protected ConfigurableApplicationContext getContext() {
26 if (context == null) {
27 context = new ClassPathXmlApplicationContext(
28 getApplicationContextLocation());
29 }
30 return context;
31 }
32
33 /** Returns a bean from the underlying context */
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 = SpringUtils.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 }