1 package org
.argeo
.support
.junit
;
5 import junit
.framework
.TestCase
;
7 import org
.apache
.commons
.logging
.Log
;
8 import org
.apache
.commons
.logging
.LogFactory
;
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
;
15 /** Helper for tests using a Spring application context. */
16 public abstract class AbstractSpringTestCase
extends TestCase
{
17 protected final Log log
= LogFactory
.getLog(getClass());
18 private ConfigurableApplicationContext context
;
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()}.
25 protected ConfigurableApplicationContext
getContext() {
26 if (context
== null) {
27 context
= new ClassPathXmlApplicationContext(
28 getApplicationContextLocation());
29 if (getIsStartContext())
35 /** Whether the context should be started after being created. */
36 protected Boolean
getIsStartContext() {
40 /** Returns a bean from the underlying context */
41 @SuppressWarnings(value
= { "unchecked" })
42 protected <T
> T
getBean(String beanId
) {
43 return (T
) getContext().getBean(beanId
);
46 protected <T
> T
getBean(Class
<?
extends T
> clss
) {
47 T bean
= loadSingleFromContext(getContext(), clss
);
49 throw new RuntimeException("Cannot retrieve a unique bean of type "
57 * Th location of the application to load. The default implementation
58 * returns <i>applicationContext.xml</i> found in the same package as the
61 protected String
getApplicationContextLocation() {
62 return inPackage("applicationContext.xml");
66 * Prefixes the package of the class after converting the '.' to '/' in
67 * order to have a resource path.
69 protected String
inPackage(String suffix
) {
70 String prefix
= getClass().getPackage().getName().replace('.', '/');
71 return prefix
+ '/' + suffix
;
74 @SuppressWarnings(value
= { "unchecked" })
75 protected <T
> T
loadSingleFromContext(ListableBeanFactory context
,
77 Map
<String
, T
> beans
= BeanFactoryUtils
.beansOfTypeIncludingAncestors(
78 context
, clss
, false, false);
79 if (beans
.size() == 1) {
80 return beans
.values().iterator().next();
81 } else if (beans
.size() > 1) {
82 if (log
.isDebugEnabled()) {
84 .debug(("Found more that on bean for type " + clss
85 + ": " + beans
.keySet()));