KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > context > support > StaticMessageSourceTests


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.context.support;
18
19 import java.util.Date JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Locale JavaDoc;
22 import java.util.Map JavaDoc;
23
24 import org.springframework.beans.MutablePropertyValues;
25 import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
26 import org.springframework.context.ACATest;
27 import org.springframework.context.AbstractApplicationContextTests;
28 import org.springframework.context.BeanThatListens;
29 import org.springframework.context.ConfigurableApplicationContext;
30 import org.springframework.context.MessageSourceResolvable;
31 import org.springframework.context.NoSuchMessageException;
32 import org.springframework.core.io.ClassPathResource;
33
34 /**
35  * @author Rod Johnson
36  */

37 public class StaticMessageSourceTests extends AbstractApplicationContextTests {
38
39     protected static final String JavaDoc MSG_TXT1_US =
40             "At '{1,time}' on \"{1,date}\", there was \"{2}\" on planet {0,number,integer}.";
41     protected static final String JavaDoc MSG_TXT1_UK =
42             "At '{1,time}' on \"{1,date}\", there was \"{2}\" on station number {0,number,integer}.";
43     protected static final String JavaDoc MSG_TXT2_US =
44             "This is a test message in the message catalog with no args.";
45     protected static final String JavaDoc MSG_TXT3_US =
46             "This is another test message in the message catalog with no args.";
47
48     protected StaticApplicationContext sac;
49
50     /** Overridden */
51     public void testCount() {
52         // These are only checked for current Ctx (not parent ctx)
53
assertCount(15);
54     }
55
56     public void testMessageSource() throws NoSuchMessageException {
57         // Do nothing here since super is looking for errorCodes we
58
// do NOT have in the Context
59
}
60
61     public void testGetMessageWithDefaultPassedInAndFoundInMsgCatalog() {
62         // Try with Locale.US
63
assertTrue("valid msg from staticMsgSource with default msg passed in returned msg from msg catalog for Locale.US",
64                 sac.getMessage("message.format.example2", null, "This is a default msg if not found in MessageSource.", Locale.US)
65                 .equals("This is a test message in the message catalog with no args."));
66     }
67
68     public void testGetMessageWithDefaultPassedInAndNotFoundInMsgCatalog() {
69         // Try with Locale.US
70
assertTrue("bogus msg from staticMsgSource with default msg passed in returned default msg for Locale.US",
71                 sac.getMessage("bogus.message", null, "This is a default msg if not found in MessageSource.", Locale.US)
72                 .equals("This is a default msg if not found in MessageSource."));
73     }
74
75     /**
76      * We really are testing the AbstractMessageSource class here.
77      * The underlying implementation uses a hashMap to cache messageFormats
78      * once a message has been asked for. This test is an attempt to
79      * make sure the cache is being used properly.
80      * @see org.springframework.context.support.AbstractMessageSource for more details.
81      */

82     public void testGetMessageWithMessageAlreadyLookedFor() {
83         Object JavaDoc[] arguments = {
84             new Integer JavaDoc(7), new Date JavaDoc(System.currentTimeMillis()),
85             "a disturbance in the Force"
86         };
87
88         // The first time searching, we don't care about for this test
89
// Try with Locale.US
90
sac.getMessage("message.format.example1", arguments, Locale.US);
91
92         // Now msg better be as expected
93
assertTrue("2nd search within MsgFormat cache returned expected message for Locale.US",
94                 sac.getMessage("message.format.example1", arguments, Locale.US).indexOf(
95                         "there was \"a disturbance in the Force\" on planet 7.") != -1);
96
97         Object JavaDoc[] newArguments = {
98             new Integer JavaDoc(8), new Date JavaDoc(System.currentTimeMillis()),
99             "a disturbance in the Force"
100         };
101
102         // Now msg better be as expected even with different args
103
assertTrue("2nd search within MsgFormat cache with different args returned expected message for Locale.US",
104                 sac.getMessage("message.format.example1", newArguments, Locale.US)
105                 .indexOf("there was \"a disturbance in the Force\" on planet 8.") != -1);
106     }
107
108     /**
109      * Example taken from the javadocs for the java.text.MessageFormat class
110      */

111     public void testGetMessageWithNoDefaultPassedInAndFoundInMsgCatalog() {
112         Object JavaDoc[] arguments = {
113             new Integer JavaDoc(7), new Date JavaDoc(System.currentTimeMillis()),
114             "a disturbance in the Force"
115         };
116
117         /*
118          Try with Locale.US
119          Since the msg has a time value in it, we will use String.indexOf(...)
120          to just look for a substring without the time. This is because it is
121          possible that by the time we store a time variable in this method
122          and the time the ResourceBundleMessageSource resolves the msg the
123          minutes of the time might not be the same.
124          */

125         assertTrue("msg from staticMsgSource for Locale.US substituting args for placeholders is as expected",
126                 sac.getMessage("message.format.example1", arguments, Locale.US)
127                 .indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1);
128
129         // Try with Locale.UK
130
assertTrue("msg from staticMsgSource for Locale.UK substituting args for placeholders is as expected",
131                 sac.getMessage("message.format.example1", arguments, Locale.UK)
132                 .indexOf("there was \"a disturbance in the Force\" on station number 7.") != -1);
133
134         // Try with Locale.US - Use a different test msg that requires no args
135
assertTrue("msg from staticMsgSource for Locale.US that requires no args is as expected",
136                 sac.getMessage("message.format.example2", null, Locale.US)
137                 .equals("This is a test message in the message catalog with no args."));
138     }
139
140     public void testGetMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() {
141         // Expecting an exception
142
try {
143             // Try with Locale.US
144
sac.getMessage("bogus.message", null, Locale.US);
145
146             fail("bogus msg from staticMsgSource for Locale.US without default msg should have thrown exception");
147         }
148         catch (NoSuchMessageException tExcept) {
149             assertTrue("bogus msg from staticMsgSource for Locale.US without default msg threw expected exception", true);
150         }
151     }
152
153     public void testMessageSourceResolvable() {
154         // first code valid
155
String JavaDoc[] codes1 = new String JavaDoc[] {"message.format.example3", "message.format.example2"};
156         MessageSourceResolvable resolvable1 = new DefaultMessageSourceResolvable(codes1, null, "default");
157         try {
158             assertTrue("correct message retrieved", MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US)));
159         }
160         catch (NoSuchMessageException ex) {
161             fail("Should not throw NoSuchMessageException");
162         }
163
164         // only second code valid
165
String JavaDoc[] codes2 = new String JavaDoc[] {"message.format.example99", "message.format.example2"};
166         MessageSourceResolvable resolvable2 = new DefaultMessageSourceResolvable(codes2, null, "default");
167         try {
168             assertTrue("correct message retrieved", MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US)));
169         }
170         catch (NoSuchMessageException ex) {
171             fail("Should not throw NoSuchMessageException");
172         }
173
174         // no code valid, but default given
175
String JavaDoc[] codes3 = new String JavaDoc[] {"message.format.example99", "message.format.example98"};
176         MessageSourceResolvable resolvable3 = new DefaultMessageSourceResolvable(codes3, null, "default");
177         try {
178             assertTrue("correct message retrieved", "default".equals(sac.getMessage(resolvable3, Locale.US)));
179         }
180         catch (NoSuchMessageException ex) {
181             fail("Should not throw NoSuchMessageException");
182         }
183
184         // no code valid, no default
185
String JavaDoc[] codes4 = new String JavaDoc[] {"message.format.example99", "message.format.example98"};
186         MessageSourceResolvable resolvable4 = new DefaultMessageSourceResolvable(codes4);
187         try {
188             sac.getMessage(resolvable4, Locale.US);
189             fail("Should have thrown NoSuchMessageException");
190         }
191         catch (NoSuchMessageException ex) {
192             // expected
193
}
194     }
195
196     /** Run for each test */
197     protected ConfigurableApplicationContext createContext() throws Exception JavaDoc {
198         StaticApplicationContext parent = new StaticApplicationContext();
199
200         Map JavaDoc m = new HashMap JavaDoc();
201         m.put("name", "Roderick");
202         parent.registerPrototype("rod", org.springframework.beans.TestBean.class, new MutablePropertyValues(m));
203         m.put("name", "Albert");
204         parent.registerPrototype("father", org.springframework.beans.TestBean.class, new MutablePropertyValues(m));
205
206         parent.refresh();
207         parent.addListener(parentListener);
208
209         this.sac = new StaticApplicationContext(parent);
210
211         sac.registerSingleton("beanThatListens", BeanThatListens.class, new MutablePropertyValues());
212
213         sac.registerSingleton("aca", ACATest.class, new MutablePropertyValues());
214
215         sac.registerPrototype("aca-prototype", ACATest.class, new MutablePropertyValues());
216
217         PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(sac.getDefaultListableBeanFactory());
218         reader.loadBeanDefinitions(new ClassPathResource("testBeans.properties", getClass()));
219         sac.refresh();
220         sac.addListener(listener);
221
222         StaticMessageSource messageSource = sac.getStaticMessageSource();
223         messageSource.addMessage("message.format.example1", Locale.US, MSG_TXT1_US);
224         messageSource.addMessage("message.format.example2", Locale.US, MSG_TXT2_US);
225         messageSource.addMessage("message.format.example3", Locale.US, MSG_TXT3_US);
226         messageSource.addMessage("message.format.example1", Locale.UK, MSG_TXT1_UK);
227
228         return sac;
229     }
230
231 }
232
Popular Tags