1 package org
.argeo
.slc
.spring
.unit
;
5 import org
.argeo
.api
.cms
.CmsLog
;
6 import org
.argeo
.slc
.SlcException
;
7 import org
.springframework
.beans
.factory
.BeanFactoryUtils
;
8 import org
.springframework
.beans
.factory
.ListableBeanFactory
;
9 import org
.springframework
.context
.ConfigurableApplicationContext
;
10 import org
.springframework
.context
.support
.ClassPathXmlApplicationContext
;
12 import junit
.framework
.TestCase
;
14 /** Helper for tests using a Spring application co,text. */
15 public abstract class AbstractSpringTestCase
extends TestCase
{
16 protected final CmsLog log
= CmsLog
.getLog(getClass());
17 private ConfigurableApplicationContext context
;
20 * Gets (and create if necessary) the application context to use. Default
21 * implementation uses a class path xml application context and calls
22 * {@link #getApplicationContextLocation()}.
24 protected ConfigurableApplicationContext
getContext() {
25 if (context
== null) {
26 context
= new ClassPathXmlApplicationContext(
27 getApplicationContextLocation());
28 if (getIsStartContext())
35 protected void tearDown() throws Exception
{
36 if (context
!= null && context
.isActive())
41 /** Whether the context should be started after being created. */
42 protected Boolean
getIsStartContext() {
46 /** Returns a bean from the underlying context */
47 @SuppressWarnings(value
= { "unchecked" })
48 protected <T
> T
getBean(String beanId
) {
49 return (T
) getContext().getBean(beanId
);
52 protected <T
> T
getBean(Class
<?
extends T
> clss
) {
53 T bean
= loadSingleFromContext(getContext(), clss
);
55 throw new SlcException("Cannot retrieve a unique bean of type "
63 * Th location of the application to load. The default implementation
64 * returns <i>applicationContext.xml</i> found in the same package as the
67 protected String
getApplicationContextLocation() {
68 return inPackage("applicationContext.xml");
72 * Prefixes the package of the class after converting the '.' to '/' in
73 * order to have a resource path.
75 protected String
inPackage(String suffix
) {
76 String prefix
= getClass().getPackage().getName().replace('.', '/');
77 return prefix
+ '/' + suffix
;
80 @SuppressWarnings(value
= { "unchecked" })
81 protected <T
> T
loadSingleFromContext(ListableBeanFactory context
,
83 Map
<String
, T
> beans
= BeanFactoryUtils
.beansOfTypeIncludingAncestors(
84 context
, clss
, false, false);
85 if (beans
.size() == 1) {
86 return beans
.values().iterator().next();
87 } else if (beans
.size() > 1) {
88 if (log
.isDebugEnabled()) {
90 .debug(("Found more that on bean for type " + clss
91 + ": " + beans
.keySet()));