View Javadoc

1   /*
2    * $Id$
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *  http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
20   */
21  
22  package org.apache.struts2;
23  
24  import java.io.UnsupportedEncodingException;
25  import java.text.SimpleDateFormat;
26  import java.util.Date;
27  import java.util.HashMap;
28  import java.util.Map;
29  import java.util.logging.ConsoleHandler;
30  import java.util.logging.Formatter;
31  import java.util.logging.Level;
32  import java.util.logging.LogRecord;
33  import java.util.logging.Logger;
34  
35  import javax.servlet.ServletException;
36  import javax.servlet.http.HttpServletRequest;
37  import javax.servlet.http.HttpServletResponse;
38  
39  import org.apache.struts2.dispatcher.Dispatcher;
40  import org.apache.struts2.dispatcher.mapper.ActionMapper;
41  import org.apache.struts2.dispatcher.mapper.ActionMapping;
42  import org.apache.struts2.util.StrutsTestCaseHelper;
43  import org.springframework.core.io.DefaultResourceLoader;
44  import org.springframework.mock.web.MockHttpServletRequest;
45  import org.springframework.mock.web.MockHttpServletResponse;
46  import org.springframework.mock.web.MockPageContext;
47  import org.springframework.mock.web.MockServletContext;
48  
49  import com.opensymphony.xwork2.ActionContext;
50  import com.opensymphony.xwork2.ActionProxy;
51  import com.opensymphony.xwork2.ActionProxyFactory;
52  import com.opensymphony.xwork2.XWorkTestCase;
53  import com.opensymphony.xwork2.config.Configuration;
54  import com.opensymphony.xwork2.util.logging.LoggerFactory;
55  import com.opensymphony.xwork2.util.logging.jdk.JdkLoggerFactory;
56  
57  /***
58   * Base test case for JUnit testing Struts.
59   */
60  public abstract class StrutsTestCase extends XWorkTestCase {
61      protected MockHttpServletResponse response;
62      protected MockHttpServletRequest request;
63      protected MockPageContext pageContext;
64      protected MockServletContext servletContext;
65      protected Map<String, String> dispatcherInitParams;
66      
67      protected DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
68  
69      static {
70          ConsoleHandler handler = new ConsoleHandler();
71          final SimpleDateFormat df = new SimpleDateFormat("mm:ss.SSS");
72          Formatter formatter = new Formatter() {
73              @Override
74              public String format(LogRecord record) {
75                  StringBuilder sb = new StringBuilder();
76                  sb.append(record.getLevel());
77                  sb.append(':');
78                  for (int x = 9 - record.getLevel().toString().length(); x > 0; x--) {
79                      sb.append(' ');
80                  }
81                  sb.append('[');
82                  sb.append(df.format(new Date(record.getMillis())));
83                  sb.append("] ");
84                  sb.append(formatMessage(record));
85                  sb.append('\n');
86                  return sb.toString();
87              }
88          };
89          handler.setFormatter(formatter);
90          Logger logger = Logger.getLogger("");
91          if (logger.getHandlers().length > 0)
92              logger.removeHandler(logger.getHandlers()[0]);
93          logger.addHandler(handler);
94          logger.setLevel(Level.WARNING);
95          LoggerFactory.setLoggerFactory(new JdkLoggerFactory());
96      }
97  
98      /***
99       * gets an object from the stack after an action is executed
100      */
101     protected Object findValueAfterExecute(String key) {
102         return ServletActionContext.getValueStack(request).findValue(key);
103     }
104 
105     /***
106      * Executes an action and returns it's output (not the result returned from
107      * execute()), but the actual output that would be written to the response.
108      * For this to work the configured result for the action needs to be
109      * FreeMarker, or Velocity (JSPs can be used with the Embedded JSP plugin)
110      */
111     protected String executeAction(String uri) throws ServletException, UnsupportedEncodingException {
112         request.setRequestURI(uri);
113         ActionMapping mapping = getActionMapping(request);
114 
115         assertNotNull(mapping);
116         Dispatcher.getInstance().serviceAction(request, response, servletContext, mapping);
117 
118         if (response.getStatus() != HttpServletResponse.SC_OK)
119             throw new ServletException("Error code [" + response.getStatus() + "], Error: ["
120                     + response.getErrorMessage() + "]");
121 
122         return response.getContentAsString();
123     }
124 
125     /***
126      * Creates an action proxy for a request, and sets parameters of the ActionInvocation to the passed
127      * parameters. Make sure to set the request parameters in the protected "request" object before calling this method.
128      */
129     protected ActionProxy getActionProxy(String uri) {
130         request.setRequestURI(uri);
131         ActionMapping mapping = getActionMapping(request);
132         String namespace = mapping.getNamespace();
133         String name = mapping.getName();
134         String method = mapping.getMethod();
135 
136         Configuration config = configurationManager.getConfiguration();
137         ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
138                 namespace, name, method, new HashMap<String, Object>(), true, false);
139 
140         ActionContext invocationContext = proxy.getInvocation().getInvocationContext();
141         invocationContext.setParameters(new HashMap(request.getParameterMap()));
142         // set the action context to the one used by the proxy
143         ActionContext.setContext(invocationContext);
144 
145         // this is normaly done in onSetUp(), but we are using Struts internal
146         // objects (proxy and action invocation)
147         // so we have to hack around so it works
148         ServletActionContext.setServletContext(servletContext);
149         ServletActionContext.setRequest(request);
150         ServletActionContext.setResponse(response);
151 
152         return proxy;
153     }
154 
155     /***
156      * Finds an ActionMapping for a given request
157      */
158     protected ActionMapping getActionMapping(HttpServletRequest request) {
159         return Dispatcher.getInstance().getContainer().getInstance(ActionMapper.class).getMapping(request,
160                 Dispatcher.getInstance().getConfigurationManager());
161     }
162 
163     /***
164      * Finds an ActionMapping for a given url
165      */
166     protected ActionMapping getActionMapping(String url) {
167         MockHttpServletRequest req = new MockHttpServletRequest();
168         req.setRequestURI(url);
169         return getActionMapping(req);
170     }
171 
172     /***
173      * Injects dependencies on an Object using Struts internal IoC container
174      */
175     protected void injectStrutsDependencies(Object object) {
176         Dispatcher.getInstance().getContainer().inject(object);
177     }
178 
179 
180     /***
181      * Sets up the configuration settings, XWork configuration, and
182      * message resources
183      */
184     protected void setUp() throws Exception {
185         super.setUp();
186         initServletMockObjects();
187         setupBeforeInitDispatcher();
188         initDispatcher(dispatcherInitParams);
189     }
190 
191     protected void setupBeforeInitDispatcher() throws Exception {
192     }
193 
194     protected void initServletMockObjects() {
195         servletContext = new MockServletContext(resourceLoader);
196         response = new MockHttpServletResponse();
197         request = new MockHttpServletRequest();
198         pageContext = new MockPageContext(servletContext, request, response);
199     }
200 
201     protected Dispatcher initDispatcher(Map<String, String> params) {
202         Dispatcher du = StrutsTestCaseHelper.initDispatcher(servletContext, params);
203         configurationManager = du.getConfigurationManager();
204         configuration = configurationManager.getConfiguration();
205         container = configuration.getContainer();
206         return du;
207     }
208 
209     protected void tearDown() throws Exception {
210         super.tearDown();
211         StrutsTestCaseHelper.tearDown();
212     }
213 
214 }