1 package org
.argeo
.slc
.unit
;
5 import junit
.framework
.TestCase
;
7 import org
.apache
.commons
.logging
.Log
;
8 import org
.apache
.commons
.logging
.LogFactory
;
9 import org
.argeo
.slc
.SlcException
;
10 import org
.springframework
.beans
.factory
.BeanFactoryUtils
;
11 import org
.springframework
.beans
.factory
.ListableBeanFactory
;
12 import org
.springframework
.context
.ConfigurableApplicationContext
;
13 import org
.springframework
.context
.support
.ClassPathXmlApplicationContext
;
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
;
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())
36 protected void tearDown() throws Exception
{
37 if (context
!= null && context
.isActive())
42 /** Whether the context should be started after being created. */
43 protected Boolean
getIsStartContext() {
47 /** Returns a bean from the underlying context */
48 @SuppressWarnings(value
= { "unchecked" })
49 protected <T
> T
getBean(String beanId
) {
50 return (T
) getContext().getBean(beanId
);
53 protected <T
> T
getBean(Class
<?
extends T
> clss
) {
54 T bean
= loadSingleFromContext(getContext(), clss
);
56 throw new SlcException("Cannot retrieve a unique bean of type "
64 * Th location of the application to load. The default implementation
65 * returns <i>applicationContext.xml</i> found in the same package as the
68 protected String
getApplicationContextLocation() {
69 return inPackage("applicationContext.xml");
73 * Prefixes the package of the class after converting the '.' to '/' in
74 * order to have a resource path.
76 protected String
inPackage(String suffix
) {
77 String prefix
= getClass().getPackage().getName().replace('.', '/');
78 return prefix
+ '/' + suffix
;
81 @SuppressWarnings(value
= { "unchecked" })
82 protected <T
> T
loadSingleFromContext(ListableBeanFactory context
,
84 Map
<String
, T
> beans
= BeanFactoryUtils
.beansOfTypeIncludingAncestors(
85 context
, clss
, false, false);
86 if (beans
.size() == 1) {
87 return beans
.values().iterator().next();
88 } else if (beans
.size() > 1) {
89 if (log
.isDebugEnabled()) {
91 .debug(("Found more that on bean for type " + clss
92 + ": " + beans
.keySet()));