1 package org
.argeo
.slc
.core
.test
.context
;
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 context. */
16 public abstract class AbstractInternalSpringTestCase
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());
33 /** Returns a bean from the underlying context */
34 @SuppressWarnings(value
= { "unchecked" })
35 protected <T
> T
getBean(String beanId
) {
36 return (T
) getContext().getBean(beanId
);
39 protected <T
> T
getBean(Class
<?
extends T
> clss
) {
40 T bean
= loadSingleFromContext(getContext(), clss
);
42 throw new SlcException("Cannot retrieve a unique bean of type "
50 * Th location of the application to load. The default implementation
51 * returns <i>applicationContext.xml</i> found in the same package as the
54 protected String
getApplicationContextLocation() {
55 return inPackage("applicationContext.xml");
59 * Prefixes the package of the class after converting the '.' to '/' in
60 * order to have a resource path.
62 protected String
inPackage(String suffix
) {
63 String prefix
= getClass().getPackage().getName().replace('.', '/');
64 return prefix
+ '/' + suffix
;
67 @SuppressWarnings(value
= { "unchecked" })
68 protected <T
> T
loadSingleFromContext(ListableBeanFactory context
,
70 Map
<String
, T
> beans
= BeanFactoryUtils
.beansOfTypeIncludingAncestors(
71 context
, clss
, false, false);
72 if (beans
.size() == 1) {
73 return beans
.values().iterator().next();
74 } else if (beans
.size() > 1) {
75 if (log
.isDebugEnabled()) {
77 .debug(("Found more that on bean for type " + clss
78 + ": " + beans
.keySet()));