KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > beans > factory > AbstractBeanFactoryTests


1 /*
2  * Copyright 2002-2005 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.beans.factory;
18
19 import java.beans.PropertyEditorSupport JavaDoc;
20 import java.util.StringTokenizer JavaDoc;
21
22 import junit.framework.TestCase;
23
24 import org.springframework.beans.BeansException;
25 import org.springframework.beans.FatalBeanException;
26 import org.springframework.beans.PropertyAccessExceptionsException;
27 import org.springframework.beans.TestBean;
28 import org.springframework.beans.factory.support.AbstractBeanFactory;
29
30 /**
31  * Subclasses must implement setUp() to initialize bean factory
32  * and any other variables they need.
33  *
34  * @author Rod Johnson
35  */

36 public abstract class AbstractBeanFactoryTests extends TestCase {
37
38     protected abstract BeanFactory getBeanFactory();
39
40     /**
41      * Roderick beans inherits from rod,
42      * overriding name only.
43      */

44     public void testInheritance() {
45         assertTrue(getBeanFactory().containsBean("rod"));
46         assertTrue(getBeanFactory().containsBean("roderick"));
47         TestBean rod = (TestBean) getBeanFactory().getBean("rod");
48         TestBean roderick = (TestBean) getBeanFactory().getBean("roderick");
49         assertTrue("not == ", rod != roderick);
50         assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
51         assertTrue("rod.age is 31", rod.getAge() == 31);
52         assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick"));
53         assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge());
54     }
55     
56     public void testGetBeanWithNullArg() {
57         try {
58             getBeanFactory().getBean(null);
59             fail("Can't get null bean");
60         }
61         catch (IllegalArgumentException JavaDoc ex) {
62             // OK
63
}
64     }
65     
66     /**
67      * Test that InitializingBean objects receive the
68      * afterPropertiesSet() callback
69      */

70     public void testInitializingBeanCallback() {
71         MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized");
72         // The dummy business method will throw an exception if the
73
// afterPropertiesSet() callback wasn't invoked
74
mbi.businessMethod();
75     }
76     
77     /**
78      * Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the
79      * afterPropertiesSet() callback before BeanFactoryAware callbacks
80      */

81     public void testLifecycleCallbacks() {
82         LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle");
83         assertEquals("lifecycle", lb.getBeanName());
84         // The dummy business method will throw an exception if the
85
// necessary callbacks weren't invoked in the right order.
86
lb.businessMethod();
87         assertTrue("Not destroyed", !lb.isDestroyed());
88     }
89     
90     public void testFindsValidInstance() {
91         try {
92             Object JavaDoc o = getBeanFactory().getBean("rod");
93             assertTrue("Rod bean is a TestBean", o instanceof TestBean);
94             TestBean rod = (TestBean) o;
95             assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
96             assertTrue("rod.age is 31", rod.getAge() == 31);
97         }
98         catch (Exception JavaDoc ex) {
99             ex.printStackTrace();
100             fail("Shouldn't throw exception on getting valid instance");
101         }
102     }
103     
104     public void testGetInstanceByMatchingClass() {
105         try {
106             Object JavaDoc o = getBeanFactory().getBean("rod", TestBean.class);
107             assertTrue("Rod bean is a TestBean", o instanceof TestBean);
108         }
109         catch (Exception JavaDoc ex) {
110             ex.printStackTrace();
111             fail("Shouldn't throw exception on getting valid instance with matching class");
112         }
113     }
114
115     public void testGetInstanceByNonmatchingClass() {
116         try {
117             Object JavaDoc o = getBeanFactory().getBean("rod", BeanFactory.class);
118             fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
119         }
120         catch (BeanNotOfRequiredTypeException ex) {
121             // So far, so good
122
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
123             assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
124             assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
125             assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
126         }
127         catch (Exception JavaDoc ex) {
128             ex.printStackTrace();
129             fail("Shouldn't throw exception on getting valid instance");
130         }
131     }
132     
133     public void testGetSharedInstanceByMatchingClass() {
134         try {
135             Object JavaDoc o = getBeanFactory().getBean("rod", TestBean.class);
136             assertTrue("Rod bean is a TestBean", o instanceof TestBean);
137         }
138         catch (Exception JavaDoc ex) {
139             ex.printStackTrace();
140             fail("Shouldn't throw exception on getting valid instance with matching class");
141         }
142     }
143     
144     public void testGetSharedInstanceByMatchingClassNoCatch() {
145         Object JavaDoc o = getBeanFactory().getBean("rod", TestBean.class);
146         assertTrue("Rod bean is a TestBean", o instanceof TestBean);
147     }
148     
149     public void testGetSharedInstanceByNonmatchingClass() {
150         try {
151             Object JavaDoc o = getBeanFactory().getBean("rod", BeanFactory.class);
152             fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
153         }
154         catch (BeanNotOfRequiredTypeException ex) {
155             // So far, so good
156
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
157             assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
158             assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
159         }
160         catch (Exception JavaDoc ex) {
161             ex.printStackTrace();
162             fail("Shouldn't throw exception on getting valid instance");
163         }
164     }
165
166     public void testSharedInstancesAreEqual() {
167         try {
168             Object JavaDoc o = getBeanFactory().getBean("rod");
169             assertTrue("Rod bean1 is a TestBean", o instanceof TestBean);
170             Object JavaDoc o1 = getBeanFactory().getBean("rod");
171             assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean);
172             assertTrue("Object equals applies", o == o1);
173         }
174         catch (Exception JavaDoc ex) {
175             ex.printStackTrace();
176             fail("Shouldn't throw exception on getting valid instance");
177         }
178     }
179     
180     public void testPrototypeInstancesAreIndependent() {
181         TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy");
182         TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy");
183         assertTrue("ref equal DOES NOT apply", tb1 != tb2);
184         assertTrue("object equal true", tb1.equals(tb2));
185         tb1.setAge(1);
186         tb2.setAge(2);
187         assertTrue("1 age independent = 1", tb1.getAge() == 1);
188         assertTrue("2 age independent = 2", tb2.getAge() == 2);
189         assertTrue("object equal now false", !tb1.equals(tb2));
190     }
191
192     public void testNotThere() {
193         assertFalse(getBeanFactory().containsBean("Mr Squiggle"));
194         try {
195             Object JavaDoc o = getBeanFactory().getBean("Mr Squiggle");
196             fail("Can't find missing bean");
197         }
198         catch (BeansException ex) {
199             //ex.printStackTrace();
200
//fail("Shouldn't throw exception on getting valid instance");
201
}
202     }
203
204     public void testValidEmpty() {
205         try {
206             Object JavaDoc o = getBeanFactory().getBean("validEmpty");
207             assertTrue("validEmpty bean is a TestBean", o instanceof TestBean);
208             TestBean ve = (TestBean) o;
209             assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null);
210         }
211         catch (BeansException ex) {
212             ex.printStackTrace();
213             fail("Shouldn't throw exception on valid empty");
214         }
215     }
216
217     public void testTypeMismatch() {
218         try {
219             Object JavaDoc o = getBeanFactory().getBean("typeMismatch");
220             fail("Shouldn't succeed with type mismatch");
221         }
222         catch (BeanCreationException wex) {
223             assertEquals("typeMismatch", wex.getBeanName());
224             assertTrue(wex.getCause() instanceof PropertyAccessExceptionsException);
225             PropertyAccessExceptionsException ex = (PropertyAccessExceptionsException) wex.getCause();
226             // Further tests
227
assertTrue("Has one error ", ex.getExceptionCount() == 1);
228             assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null);
229
230             TestBean tb = (TestBean) ex.getBeanWrapper().getWrappedInstance();
231             assertTrue("Age still has default", tb.getAge() == 0);
232             assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x"));
233             assertTrue("valid name stuck", tb.getName().equals("typeMismatch"));
234             assertTrue("valid spouse stuck", tb.getSpouse().getName().equals("Rod"));
235         }
236     }
237
238     public void testGrandparentDefinitionFoundInBeanFactory() throws Exception JavaDoc {
239         TestBean dad = (TestBean) getBeanFactory().getBean("father");
240         assertTrue("Dad has correct name", dad.getName().equals("Albert"));
241     }
242
243     public void testFactorySingleton() throws Exception JavaDoc {
244         assertTrue(getBeanFactory().isSingleton("&singletonFactory"));
245         assertTrue(getBeanFactory().isSingleton("singletonFactory"));
246         TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
247         assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME));
248         DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
249         TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory");
250         assertTrue("Singleton references ==", tb == tb2);
251         assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null);
252     }
253     
254     public void testFactoryPrototype() throws Exception JavaDoc {
255         assertTrue(getBeanFactory().isSingleton("&prototypeFactory"));
256         assertFalse(getBeanFactory().isSingleton("prototypeFactory"));
257         TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory");
258         assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME));
259         TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory");
260         assertTrue("Prototype references !=", tb != tb2);
261     }
262     
263     /**
264      * Check that we can get the factory bean itself.
265      * This is only possible if we're dealing with a factory
266      * @throws Exception
267      */

268     public void testGetFactoryItself() throws Exception JavaDoc {
269         DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
270         assertTrue(factory != null);
271     }
272     
273     /**
274      * Check that afterPropertiesSet gets called on factory
275      * @throws Exception
276      */

277     public void testFactoryIsInitialized() throws Exception JavaDoc {
278         TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
279         DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
280         assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized());
281     }
282     
283     /**
284      * It should be illegal to dereference a normal bean
285      * as a factory
286      */

287     public void testRejectsFactoryGetOnNormalBean() {
288         try {
289             getBeanFactory().getBean("&rod");
290             fail("Shouldn't permit factory get on normal bean");
291         }
292         catch (BeanIsNotAFactoryException ex) {
293             // Ok
294
}
295     }
296     
297     // TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory)
298
// and rename this class
299
public void testAliasing() {
300         if (!(getBeanFactory() instanceof AbstractBeanFactory))
301             return;
302         
303         String JavaDoc alias = "rods alias";
304         try {
305             getBeanFactory().getBean(alias);
306             fail("Shouldn't permit factory get on normal bean");
307         }
308         catch (NoSuchBeanDefinitionException ex) {
309             // Ok
310
assertTrue(alias.equals(ex.getBeanName()));
311         }
312         
313         // Create alias
314
((AbstractBeanFactory) getBeanFactory()).registerAlias("rod", alias);
315         Object JavaDoc rod = getBeanFactory().getBean("rod");
316         Object JavaDoc aliasRod = getBeanFactory().getBean(alias);
317         assertTrue(rod == aliasRod);
318
319         try {
320             ((AbstractBeanFactory) getBeanFactory()).registerAlias("father", alias);
321             fail("Should have thrown FatalBeanException");
322         }
323         catch (FatalBeanException ex) {
324             // expected
325
}
326
327         // TODO: check prototype support
328
}
329
330
331     public static class TestBeanEditor extends PropertyEditorSupport JavaDoc {
332
333         public void setAsText(String JavaDoc text) {
334             TestBean tb = new TestBean();
335             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(text, "_");
336             tb.setName(st.nextToken());
337             tb.setAge(Integer.parseInt(st.nextToken()));
338             setValue(tb);
339         }
340     }
341
342 }
343
Popular Tags