KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > servlet > view > velocity > VelocityViewTests


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.web.servlet.view.velocity;
18
19 import java.io.IOException JavaDoc;
20 import java.util.HashMap JavaDoc;
21 import java.util.Locale JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.Properties JavaDoc;
24
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.http.HttpServletResponse JavaDoc;
27
28 import junit.framework.TestCase;
29 import org.apache.velocity.Template;
30 import org.apache.velocity.app.VelocityEngine;
31 import org.apache.velocity.app.tools.VelocityFormatter;
32 import org.apache.velocity.context.Context;
33 import org.apache.velocity.exception.ParseErrorException;
34 import org.apache.velocity.exception.ResourceNotFoundException;
35 import org.apache.velocity.tools.generic.DateTool;
36 import org.apache.velocity.tools.generic.MathTool;
37 import org.apache.velocity.tools.generic.NumberTool;
38 import org.apache.velocity.tools.view.context.ChainedContext;
39 import org.apache.velocity.tools.view.tools.LinkTool;
40 import org.easymock.MockControl;
41
42 import org.springframework.context.ApplicationContextException;
43 import org.springframework.mock.web.MockHttpServletRequest;
44 import org.springframework.mock.web.MockHttpServletResponse;
45 import org.springframework.mock.web.MockServletContext;
46 import org.springframework.web.context.WebApplicationContext;
47 import org.springframework.web.context.support.StaticWebApplicationContext;
48 import org.springframework.web.servlet.DispatcherServlet;
49 import org.springframework.web.servlet.View;
50 import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
51 import org.springframework.web.servlet.view.InternalResourceView;
52 import org.springframework.web.servlet.view.RedirectView;
53
54 /**
55  * @author Rod Johnson
56  */

57 public class VelocityViewTests extends TestCase {
58
59     public void testNoVelocityConfig() throws Exception JavaDoc {
60         VelocityView vv = new VelocityView();
61         MockControl wmc = MockControl.createControl(WebApplicationContext.class);
62         WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
63         wac.getBeansOfType(VelocityConfig.class, true, false);
64         wmc.setReturnValue(new HashMap JavaDoc());
65         wac.getParentBeanFactory();
66         wmc.setReturnValue(null);
67         wmc.replay();
68
69         vv.setUrl("anythingButNull");
70         try {
71             vv.setApplicationContext(wac);
72             fail();
73         }
74         catch (ApplicationContextException ex) {
75             // Check there's a helpful error message
76
assertTrue(ex.getMessage().indexOf("VelocityConfig") != -1);
77         }
78
79         wmc.verify();
80     }
81
82     public void testNoTemplateName() throws Exception JavaDoc {
83         VelocityView vv = new VelocityView();
84         try {
85             vv.afterPropertiesSet();
86             fail("Should have thrown IllegalArgumentException");
87         }
88         catch (IllegalArgumentException JavaDoc ex) {
89             // Check there's a helpful error message
90
assertTrue(ex.getMessage().indexOf("url") != -1);
91         }
92     }
93
94     public void testCannotResolveTemplateNameResourceNotFoundException() throws Exception JavaDoc {
95         testCannotResolveTemplateName(new ResourceNotFoundException(""));
96     }
97
98     public void testCannotResolveTemplateNameParseErrorException() throws Exception JavaDoc {
99         testCannotResolveTemplateName(new ParseErrorException(""));
100     }
101
102     public void testCannotResolveTemplateNameNonspecificException() throws Exception JavaDoc {
103         testCannotResolveTemplateName(new Exception JavaDoc(""));
104     }
105
106     /**
107      * Check for failure to lookup a template for a range of reasons.
108      */

109     private void testCannotResolveTemplateName(final Exception JavaDoc templateLookupException) throws Exception JavaDoc {
110         final String JavaDoc templateName = "test.vm";
111
112         MockControl wmc = MockControl.createControl(WebApplicationContext.class);
113         WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
114         wac.getParentBeanFactory();
115         wmc.setReturnValue(null);
116         VelocityConfig vc = new VelocityConfig() {
117             public VelocityEngine getVelocityEngine() {
118                 return new VelocityEngine() {
119                     public Template getTemplate(String JavaDoc tn)
120                         throws ResourceNotFoundException, ParseErrorException, Exception JavaDoc {
121                         assertEquals(tn, templateName);
122                         throw templateLookupException;
123                     }
124                 };
125             }
126         };
127         wac.getBeansOfType(VelocityConfig.class, true, false);
128         Map JavaDoc configurers = new HashMap JavaDoc();
129         configurers.put("velocityConfigurer", vc);
130         wmc.setReturnValue(configurers);
131         wmc.replay();
132
133         VelocityView vv = new VelocityView();
134         //vv.setExposeDateFormatter(false);
135
//vv.setExposeCurrencyFormatter(false);
136
vv.setUrl(templateName);
137
138         try {
139             vv.setApplicationContext(wac);
140             fail();
141         }
142         catch (ApplicationContextException ex) {
143             assertEquals(ex.getCause(), templateLookupException);
144         }
145
146         wmc.verify();
147     }
148     
149     public void testMergeTemplateSucceeds() throws Exception JavaDoc {
150         testValidTemplateName(null);
151     }
152     
153     public void testMergeTemplateFailureWithIOException() throws Exception JavaDoc {
154         testValidTemplateName(new IOException JavaDoc());
155     }
156     
157     public void testMergeTemplateFailureWithParseErrorException() throws Exception JavaDoc {
158         testValidTemplateName(new ParseErrorException(""));
159     }
160         
161     public void testMergeTemplateFailureWithUnspecifiedException() throws Exception JavaDoc {
162         testValidTemplateName(new Exception JavaDoc(""));
163     }
164
165     /**
166      * @param mergeTemplateFailureException may be null in which case mergeTemplate override will succeed.
167      * If it's non null it will be checked
168      */

169     private void testValidTemplateName(final Exception JavaDoc mergeTemplateFailureException) throws Exception JavaDoc {
170         Map JavaDoc model = new HashMap JavaDoc();
171         model.put("foo", "bar");
172
173         final String JavaDoc templateName = "test.vm";
174
175         MockControl wmc = MockControl.createControl(WebApplicationContext.class);
176         WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
177         wac.getParentBeanFactory();
178         wmc.setReturnValue(null);
179         final Template expectedTemplate = new Template();
180         VelocityConfig vc = new VelocityConfig() {
181             public VelocityEngine getVelocityEngine() {
182                 return new TestVelocityEngine(templateName, expectedTemplate);
183             }
184         };
185         wac.getBeansOfType(VelocityConfig.class, true, false);
186         Map JavaDoc configurers = new HashMap JavaDoc();
187         configurers.put("velocityConfigurer", vc);
188         wmc.setReturnValue(configurers);
189         wmc.replay();
190
191         MockControl reqControl = MockControl.createControl(HttpServletRequest JavaDoc.class);
192         HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc) reqControl.getMock();
193         reqControl.replay();
194
195         final HttpServletResponse JavaDoc expectedResponse = new MockHttpServletResponse();
196
197         VelocityView vv = new VelocityView() {
198             protected void mergeTemplate(Template template, Context context, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
199                 assertTrue(template == expectedTemplate);
200                 assertTrue(context.getKeys().length >= 1);
201                 assertTrue(context.get("foo").equals("bar"));
202                 assertTrue(response == expectedResponse);
203                 if (mergeTemplateFailureException != null) {
204                     throw mergeTemplateFailureException;
205                 }
206             }
207         };
208         vv.setUrl(templateName);
209         vv.setApplicationContext(wac);
210
211         try {
212             vv.render(model, req, expectedResponse);
213             if (mergeTemplateFailureException != null) {
214                 fail();
215             }
216         }
217         catch (Exception JavaDoc ex) {
218             assertNotNull(mergeTemplateFailureException);
219             assertEquals(ex, mergeTemplateFailureException);
220         }
221
222         wmc.verify();
223         reqControl.verify();
224     }
225
226     public void testExposeHelpers() throws Exception JavaDoc {
227         final String JavaDoc templateName = "test.vm";
228
229         MockControl wmc = MockControl.createControl(WebApplicationContext.class);
230         WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
231         wac.getParentBeanFactory();
232         wmc.setReturnValue(null);
233         final Template expectedTemplate = new Template();
234         VelocityConfig vc = new VelocityConfig() {
235             public VelocityEngine getVelocityEngine() {
236                 return new TestVelocityEngine(templateName, expectedTemplate);
237             }
238         };
239         wac.getBeansOfType(VelocityConfig.class, true, false);
240         Map JavaDoc configurers = new HashMap JavaDoc();
241         configurers.put("velocityConfigurer", vc);
242         wmc.setReturnValue(configurers);
243         wmc.replay();
244
245         // let it ask for locale
246
MockControl reqControl = MockControl.createControl(HttpServletRequest JavaDoc.class);
247         HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc) reqControl.getMock();
248         req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
249         reqControl.setReturnValue(new AcceptHeaderLocaleResolver());
250         req.getLocale();
251         reqControl.setReturnValue(Locale.CANADA);
252         reqControl.replay();
253
254         final HttpServletResponse JavaDoc expectedResponse = new MockHttpServletResponse();
255
256         VelocityView vv = new VelocityView() {
257             protected void mergeTemplate(Template template, Context context, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
258                 assertTrue(template == expectedTemplate);
259                 assertTrue(response == expectedResponse);
260
261                 assertEquals("myValue", context.get("myHelper"));
262                 assertTrue(context.get("velocityFormatter") instanceof VelocityFormatter);
263                 assertTrue(context.get("math") instanceof MathTool);
264
265                 assertTrue(context.get("dateTool") instanceof DateTool);
266                 DateTool dateTool = (DateTool) context.get("dateTool");
267                 assertTrue(dateTool.getLocale().equals(Locale.CANADA));
268
269                 assertTrue(context.get("numberTool") instanceof NumberTool);
270                 NumberTool numberTool = (NumberTool) context.get("numberTool");
271                 assertTrue(numberTool.getLocale().equals(Locale.CANADA));
272             }
273
274             protected void exposeHelpers(Map JavaDoc model, HttpServletRequest JavaDoc request) throws Exception JavaDoc {
275                 model.put("myHelper", "myValue");
276             }
277         };
278         
279         vv.setUrl(templateName);
280         vv.setApplicationContext(wac);
281         Properties JavaDoc toolAttributes = new Properties JavaDoc();
282         toolAttributes.setProperty("math", MathTool.class.getName());
283         vv.setToolAttributes(toolAttributes);
284         vv.setVelocityFormatterAttribute("velocityFormatter");
285         vv.setDateToolAttribute("dateTool");
286         vv.setNumberToolAttribute("numberTool");
287         vv.render(new HashMap JavaDoc(), req, expectedResponse);
288
289         wmc.verify();
290         reqControl.verify();
291     }
292
293     public void testVelocityToolboxView() throws Exception JavaDoc {
294         final String JavaDoc templateName = "test.vm";
295
296         StaticWebApplicationContext wac = new StaticWebApplicationContext();
297         wac.setServletContext(new MockServletContext());
298         final Template expectedTemplate = new Template();
299         VelocityConfig vc = new VelocityConfig() {
300             public VelocityEngine getVelocityEngine() {
301                 return new TestVelocityEngine(templateName, expectedTemplate);
302             }
303         };
304         wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc);
305
306         final HttpServletRequest JavaDoc expectedRequest = new MockHttpServletRequest();
307         final HttpServletResponse JavaDoc expectedResponse = new MockHttpServletResponse();
308
309         VelocityToolboxView vv = new VelocityToolboxView() {
310             protected void mergeTemplate(Template template, Context context, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
311                 assertTrue(template == expectedTemplate);
312                 assertTrue(response == expectedResponse);
313                 assertTrue(context instanceof ChainedContext);
314
315                 assertEquals("this is foo.", context.get("foo"));
316                 assertTrue(context.get("map") instanceof HashMap JavaDoc);
317                 assertTrue(context.get("date") instanceof DateTool);
318                 assertTrue(context.get("math") instanceof MathTool);
319
320                 assertTrue(context.get("link") instanceof LinkTool);
321                 LinkTool linkTool = (LinkTool) context.get("link");
322                 assertNotNull(linkTool.getContextURL());
323
324                 assertTrue(context.get("link2") instanceof LinkTool);
325                 LinkTool linkTool2 = (LinkTool) context.get("link2");
326                 assertNotNull(linkTool2.getContextURL());
327             }
328         };
329
330         vv.setUrl(templateName);
331         vv.setApplicationContext(wac);
332         Properties JavaDoc toolAttributes = new Properties JavaDoc();
333         toolAttributes.setProperty("math", MathTool.class.getName());
334         toolAttributes.setProperty("link2", LinkTool.class.getName());
335         vv.setToolAttributes(toolAttributes);
336         vv.setToolboxConfigLocation("org/springframework/web/servlet/view/velocity/toolbox.xml");
337         vv.render(new HashMap JavaDoc(), expectedRequest, expectedResponse);
338     }
339
340     public void testVelocityViewResolver() throws Exception JavaDoc {
341         final Template expectedTemplate = new Template();
342         VelocityConfig vc = new VelocityConfig() {
343             public VelocityEngine getVelocityEngine() {
344                 return new TestVelocityEngine("prefix_test_suffix", expectedTemplate);
345             }
346         };
347
348         StaticWebApplicationContext wac = new StaticWebApplicationContext();
349         wac.getBeanFactory().registerSingleton("configurer",vc);
350
351         VelocityViewResolver vr = new VelocityViewResolver();
352         vr.setPrefix("prefix_");
353         vr.setSuffix("_suffix");
354         vr.setApplicationContext(wac);
355
356         View view = vr.resolveViewName("test", Locale.CANADA);
357         assertEquals("Correct view class", VelocityView.class, view.getClass());
358         assertEquals("Correct URL", "prefix_test_suffix", ((VelocityView) view).getUrl());
359
360         view = vr.resolveViewName("redirect:myUrl", Locale.getDefault());
361         assertEquals("Correct view class", RedirectView.class, view.getClass());
362         assertEquals("Correct URL", "myUrl", ((RedirectView) view).getUrl());
363
364         view = vr.resolveViewName("forward:myUrl", Locale.getDefault());
365         assertEquals("Correct view class", InternalResourceView.class, view.getClass());
366         assertEquals("Correct URL", "myUrl", ((InternalResourceView) view).getUrl());
367     }
368
369     public void testVelocityViewResolverWithToolbox() throws Exception JavaDoc {
370         final Template expectedTemplate = new Template();
371         VelocityConfig vc = new VelocityConfig() {
372             public VelocityEngine getVelocityEngine() {
373                 return new TestVelocityEngine("prefix_test_suffix", expectedTemplate);
374             }
375         };
376
377         StaticWebApplicationContext wac = new StaticWebApplicationContext();
378         wac.getBeanFactory().registerSingleton("configurer",vc);
379
380         String JavaDoc toolbox = "org/springframework/web/servlet/view/velocity/toolbox.xml";
381
382         VelocityViewResolver vr = new VelocityViewResolver();
383         vr.setPrefix("prefix_");
384         vr.setSuffix("_suffix");
385         vr.setToolboxConfigLocation(toolbox);
386         vr.setApplicationContext(wac);
387
388         View view = vr.resolveViewName("test", Locale.CANADA);
389         assertEquals("Correct view class", VelocityToolboxView.class, view.getClass());
390         assertEquals("Correct URL", "prefix_test_suffix", ((VelocityView) view).getUrl());
391         assertEquals("Correct toolbox", toolbox, ((VelocityToolboxView) view).getToolboxConfigLocation());
392     }
393
394 }
395
Popular Tags