]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.core/src/main/java/org/argeo/slc/unit/AbstractSpringTestCase.java
5166242b4626c9c4873997565af672068eea715f
[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 java.util.Map;
4
5 import junit.framework.TestCase;
6
7 import org.springframework.context.ApplicationContext;
8 import org.springframework.context.support.ClassPathXmlApplicationContext;
9
10 import org.argeo.slc.core.SlcException;
11 import org.argeo.slc.core.process.SlcExecution;
12
13 /** Helper for tests using a Spring application co,text. */
14 public abstract class AbstractSpringTestCase extends TestCase {
15 private ApplicationContext 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 ApplicationContext 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 Map<String, T> map = getContext().getBeansOfType(clss);
37 if (map.size() == 1) {
38 return map.values().iterator().next();
39 } else {
40 throw new SlcException("Cannot retrieve a unique bean of type "
41 + clss);
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 }