Merge pull request #595 from apache/WW-5220-move-junit

WW-5220 Moves JUnit related test into the JUnit plugin
This commit is contained in:
Lukasz Lenart
2022-09-14 16:37:34 +02:00
committed by GitHub
31 changed files with 601 additions and 594 deletions
@@ -25,7 +25,7 @@ import com.opensymphony.xwork2.util.ClassLoaderUtil;
import com.opensymphony.xwork2.util.ValueStack;
import net.sf.jasperreports.engine.JasperCompileManager;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.junit.StrutsTestCase;
import javax.servlet.ServletException;
import java.net.URL;
@@ -82,7 +82,7 @@ public class JasperReportsResultTest extends StrutsTestCase {
result.execute(this.invocation);
} catch (ServletException e) {
assertEquals("Error building dataSource for excluded or not accepted [getDatasource()]",
e.getMessage());
e.getMessage());
}
// verify that above test has really effect
@@ -242,14 +242,14 @@ public class JasperReportsResultTest extends StrutsTestCase {
private static final Map<String, String>[] JR_MAP_ARRAY_DATA_SOURCE = new Map[]{
new HashMap<String, String>() {{
put("firstName", "Foo");
put("lastName", "Bar");
}}
new HashMap<String, String>() {{
put("firstName", "Foo");
put("lastName", "Bar");
}}
};
private static final NotExcludedAcceptedPatternsChecker NO_EXCLUSION_ACCEPT_ALL_PATTERNS_CHECKER
= new NotExcludedAcceptedPatternsChecker() {
= new NotExcludedAcceptedPatternsChecker() {
@Override
public IsAllowed isAllowed(String value) {
return IsAllowed.yes("*");
@@ -23,7 +23,7 @@ import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.junit.StrutsTestCase;
import org.easymock.EasyMock;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
@@ -36,6 +36,7 @@ import java.io.IOException;
/**
*
*/
public class ChartResultTest extends StrutsTestCase {
@@ -50,7 +51,7 @@ public class ChartResultTest extends StrutsTestCase {
public void testChart() throws Exception {
EasyMock.expect(responseMock.getOutputStream()).andReturn(os);
EasyMock.replay(responseMock, mockActionProxy, actionInvocation);
ChartResult result = new ChartResult();
result.setChart(mockChart);
@@ -62,7 +63,7 @@ public class ChartResultTest extends StrutsTestCase {
EasyMock.verify(responseMock);
assertTrue(os.isWritten());
}
public void testContentTypePng() throws Exception {
EasyMock.expect(responseMock.getOutputStream()).andReturn(os);
responseMock.setContentType("image/png");
@@ -79,7 +80,7 @@ public class ChartResultTest extends StrutsTestCase {
EasyMock.verify(responseMock);
assertTrue(os.isWritten());
}
public void testContentTypeJpg() throws Exception {
EasyMock.expect(responseMock.getOutputStream()).andReturn(os);
responseMock.setContentType("image/jpg");
@@ -101,7 +102,7 @@ public class ChartResultTest extends StrutsTestCase {
public void testChartNotSet() {
ChartResult result = new ChartResult();
EasyMock.replay(responseMock, mockActionProxy, actionInvocation);
// expect exception if chart not set.
result.setChart(null);
@@ -141,7 +142,7 @@ public class ChartResultTest extends StrutsTestCase {
assertEquals("150", result.getWidth().toString());
assertTrue(os.isWritten());
}
protected void setUp() throws Exception {
super.setUp();
@@ -160,8 +161,8 @@ public class ChartResultTest extends StrutsTestCase {
actionInvocation = EasyMock.createMock(ActionInvocation.class);
EasyMock.expect(actionInvocation.getStack()).andReturn(stack).anyTimes();
os = new MockServletOutputStream();
responseMock = EasyMock.createNiceMock(HttpServletResponse.class);
@@ -18,10 +18,10 @@
*/
package org.apache.struts2.json;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.json.annotations.JSONFieldBridge;
import org.apache.struts2.json.bridge.StringBridge;
import org.apache.struts2.util.TestUtils;
import org.apache.struts2.junit.StrutsTestCase;
import org.apache.struts2.junit.util.TestUtils;
import org.junit.Test;
import java.net.URL;
@@ -32,10 +32,10 @@ import java.util.List;
import java.util.Map;
import java.util.TimeZone;
public class DefaultJSONWriterTest extends StrutsTestCase{
public class DefaultJSONWriterTest extends StrutsTestCase {
@Test
public void testWrite() throws Exception {
Bean bean1=new Bean();
Bean bean1 = new Bean();
bean1.setStringField("str");
bean1.setBooleanField(true);
bean1.setCharField('s');
@@ -54,7 +54,7 @@ public class DefaultJSONWriterTest extends StrutsTestCase{
@Test
public void testWriteExcludeNull() throws Exception {
BeanWithMap bean1=new BeanWithMap();
BeanWithMap bean1 = new BeanWithMap();
bean1.setStringField("str");
bean1.setBooleanField(true);
bean1.setCharField('s');
@@ -78,7 +78,7 @@ public class DefaultJSONWriterTest extends StrutsTestCase{
TestUtils.assertEquals(DefaultJSONWriter.class.getResource("jsonwriter-write-bean-03.txt"), json);
}
private class BeanWithMap extends Bean{
private class BeanWithMap extends Bean {
private Map map;
public Map getMap() {
@@ -92,7 +92,7 @@ public class DefaultJSONWriterTest extends StrutsTestCase{
@Test
public void testWriteAnnotatedBean() throws Exception {
AnnotatedBean bean1=new AnnotatedBean();
AnnotatedBean bean1 = new AnnotatedBean();
bean1.setStringField("str");
bean1.setBooleanField(true);
bean1.setCharField('s');
@@ -146,7 +146,7 @@ public class DefaultJSONWriterTest extends StrutsTestCase{
}
}
private class AnnotatedBean extends Bean{
private class AnnotatedBean extends Bean {
private URL url;
@JSONFieldBridge(impl = StringBridge.class)
@@ -18,19 +18,18 @@
*/
package org.apache.struts2.json;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.dispatcher.mapper.DefaultActionMapper;
import org.apache.struts2.views.util.DefaultUrlHelper;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import com.opensymphony.xwork2.mock.MockActionProxy;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.mapper.DefaultActionMapper;
import org.apache.struts2.junit.StrutsTestCase;
import org.apache.struts2.views.util.DefaultUrlHelper;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
public class JSONActionRedirectResultTest extends StrutsTestCase {
@@ -18,19 +18,18 @@
*/
package org.apache.struts2.json;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.util.TestUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.junit.StrutsTestCase;
import org.apache.struts2.junit.util.TestUtils;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
public class JSONInterceptorTest extends StrutsTestCase {
private MockActionInvocationEx invocation;
@@ -294,7 +293,7 @@ public class JSONInterceptorTest extends StrutsTestCase {
assertEquals("application/json;charset=UTF-8", response.getContentType());
}
@SuppressWarnings( { "unchecked", "unchecked" })
@SuppressWarnings({"unchecked", "unchecked"})
public void testReadEmpty() throws Exception {
// request
setRequestContent("json-6.txt");
@@ -309,7 +308,7 @@ public class JSONInterceptorTest extends StrutsTestCase {
interceptor.intercept(this.invocation);
}
@SuppressWarnings( { "unchecked", "unchecked" })
@SuppressWarnings({"unchecked", "unchecked"})
public void test() throws Exception {
// request
setRequestContent("json-1.txt");
@@ -457,7 +456,7 @@ public class JSONInterceptorTest extends StrutsTestCase {
assertEquals(bean2.getDoubleField(), 10.1);
assertEquals(bean2.getByteField(), 3);
}
public void testJSONArray() throws Exception {
setRequestContent("json-12.txt");
this.request.addHeader("Content-Type", "application/json");
@@ -509,7 +508,7 @@ public class JSONInterceptorTest extends StrutsTestCase {
assertEquals(beans.get(0).getDoubleField(), 10.1);
assertEquals(beans.get(0).getByteField(), 3);
}
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -27,7 +27,7 @@ import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.apache.struts2.util.TestUtils;
import org.apache.struts2.junit.util.TestUtils;
public class JSONPopulatorTest extends TestCase {
@@ -18,6 +18,19 @@
*/
package org.apache.struts2.json;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.junit.StrutsTestCase;
import org.apache.struts2.junit.util.TestUtils;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
@@ -33,21 +46,6 @@ import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.Result;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.util.TestUtils;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.mock.MockActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
/**
* JSONResultTest
*/
@@ -298,13 +296,13 @@ public class JSONResultTest extends StrutsTestCase {
stack.push(action);
// test scape characters
action.setArray(new String[] { "a", "a", "\"", "\\", "/", "\b", "\f", "\n", "\r", "\t" });
action.setArray(new String[]{"a", "a", "\"", "\\", "/", "\b", "\f", "\n", "\r", "\t"});
List list = new ArrayList();
list.add("b");
list.add(1);
list.add(new int[] { 10, 12 });
list.add(new int[]{10, 12});
action.setCollection(list);
// beans
@@ -343,7 +341,7 @@ public class JSONResultTest extends StrutsTestCase {
Map map = new LinkedHashMap();
map.put("a", 1);
map.put("c", new float[] { 1.0f, 2.0f });
map.put("c", new float[]{1.0f, 2.0f});
action.setMap(map);
action.setFoo("foo");
@@ -403,13 +401,13 @@ public class JSONResultTest extends StrutsTestCase {
stack.push(action);
// test scape characters
action.setArray(new String[] { "a", "a", "\"", "\\", "/", "\b", "\f", "\n", "\r", "\t" });
action.setArray(new String[]{"a", "a", "\"", "\\", "/", "\b", "\f", "\n", "\r", "\t"});
List list = new ArrayList();
list.add("b");
list.add(1);
list.add(new int[] { 10, 12 });
list.add(new int[]{10, 12});
action.setCollection(list);
// beans
@@ -446,7 +444,7 @@ public class JSONResultTest extends StrutsTestCase {
Map map = new LinkedHashMap();
map.put("a", 1);
map.put("c", new float[] { 1.0f, 2.0f });
map.put("c", new float[]{1.0f, 2.0f});
action.setMap(map);
action.setFoo("foo");
@@ -714,7 +712,7 @@ public class JSONResultTest extends StrutsTestCase {
assertEquals("UTF-8", encoding);
}
public void testPassingNullInvocation() throws Exception{
public void testPassingNullInvocation() throws Exception {
Result result = new JSONResult();
try {
result.execute(null);
@@ -26,13 +26,13 @@ import com.opensymphony.xwork2.mock.MockActionInvocation;
import com.opensymphony.xwork2.mock.MockActionProxy;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.IntRangeFieldValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.apache.struts2.util.TestUtils;
import org.apache.struts2.junit.StrutsTestCase;
import org.apache.struts2.junit.util.TestUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@@ -53,13 +53,13 @@ public class JSONValidationInterceptorTest extends StrutsTestCase {
private AnnotationValidationInterceptor validationInterceptor;
public void testValidationFails() throws Exception {
action.addActionError("General error");
Map parameters = new HashMap();
parameters.put("struts.enableJSONValidation", "true");
request.setParameterMap(parameters);
validationInterceptor.intercept(invocation);
interceptor.intercept(invocation);
@@ -69,11 +69,11 @@ public class JSONValidationInterceptorTest extends StrutsTestCase {
//json
assertThat(normalizedActual)
.contains("\"errors\":[\"Generalerror\"]")
.contains("\"fieldErrors\":{")
.contains("\"value\":[\"Minvalueis-1\"]")
.contains("\"text\":[\"Tooshort\",\"Thisisnoemail\"]")
.contains("\"password\":[\"Passwordisn'tcorrect\"]");
.contains("\"errors\":[\"Generalerror\"]")
.contains("\"fieldErrors\":{")
.contains("\"value\":[\"Minvalueis-1\"]")
.contains("\"text\":[\"Tooshort\",\"Thisisnoemail\"]")
.contains("\"password\":[\"Passwordisn'tcorrect\"]");
//execution
assertFalse(action.isExecuted());
@@ -89,7 +89,7 @@ public class JSONValidationInterceptorTest extends StrutsTestCase {
action.setText("abcd@ggg.com");
action.setPassword("apassword");
action.setValue(10);
Map parameters = new HashMap();
parameters.put("struts.enableJSONValidation", "true");
request.setParameterMap(parameters);
@@ -102,7 +102,7 @@ public class JSONValidationInterceptorTest extends StrutsTestCase {
String normalizedActual = TestUtils.normalize(json, true);
assertEquals("", normalizedActual);
}
public void testValidationSucceedsValidateOnly() throws Exception {
JSONValidationInterceptor interceptor = new JSONValidationInterceptor();
@@ -115,7 +115,7 @@ public class JSONValidationInterceptorTest extends StrutsTestCase {
parameters.put("struts.validateOnly", "true");
parameters.put("struts.enableJSONValidation", "true");
request.setParameterMap(parameters);
validationInterceptor.intercept(invocation);
interceptor.intercept(invocation);
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
@@ -1,252 +1,252 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.XWorkJUnit4TestCase;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.interceptor.ValidationAware;
import com.opensymphony.xwork2.interceptor.annotations.After;
import com.opensymphony.xwork2.interceptor.annotations.Before;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.util.StrutsTestCaseHelper;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
public abstract class StrutsJUnit4TestCase<T> extends XWorkJUnit4TestCase {
protected MockHttpServletResponse response;
protected MockHttpServletRequest request;
protected MockPageContext pageContext;
protected MockServletContext servletContext;
protected Map<String, String> dispatcherInitParams;
protected Dispatcher dispatcher;
protected DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
/**
* gets an object from the stack after an action is executed
*/
protected Object findValueAfterExecute(String key) {
return ServletActionContext.getValueStack(request).findValue(key);
}
/**
* gets an object from the stack after an action is executed
*
* @return The executed action
*/
@SuppressWarnings("unchecked")
protected T getAction() {
return (T) findValueAfterExecute("action");
}
protected boolean containsErrors() {
T action = this.getAction();
if (action instanceof ValidationAware) {
return ((ValidationAware) action).hasActionErrors();
}
throw new UnsupportedOperationException("Current action does not implement ValidationAware interface");
}
/**
* Executes an action and returns it's output (not the result returned from
* execute()), but the actual output that would be written to the response.
* For this to work the configured result for the action needs to be
* FreeMarker, or Velocity (JSPs can be used with the Embedded JSP plugin)
*/
protected String executeAction(String uri) throws ServletException, UnsupportedEncodingException {
request.setRequestURI(uri);
ActionMapping mapping = getActionMapping(request);
assertNotNull(mapping);
Dispatcher.getInstance().serviceAction(request, response, mapping);
if (response.getStatus() != HttpServletResponse.SC_OK)
throw new ServletException("Error code [" + response.getStatus() + "], Error: ["
+ response.getErrorMessage() + "]");
return response.getContentAsString();
}
/**
* Creates an action proxy for a request, and sets parameters of the ActionInvocation to the passed
* parameters. Make sure to set the request parameters in the protected "request" object before calling this method.
*/
protected ActionProxy getActionProxy(String uri) {
request.setRequestURI(uri);
ActionMapping mapping = getActionMapping(request);
String namespace = mapping.getNamespace();
String name = mapping.getName();
String method = mapping.getMethod();
Configuration config = configurationManager.getConfiguration();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, new HashMap<String, Object>(), true, false);
initActionContext(proxy.getInvocation().getInvocationContext());
// this is normally done in onSetUp(), but we are using Struts internal
// objects (proxy and action invocation)
// so we have to hack around so it works
ServletActionContext.setServletContext(servletContext);
ServletActionContext.setRequest(request);
ServletActionContext.setResponse(response);
ServletActionContext.getContext().put(ServletActionContext.ACTION_MAPPING, mapping);
return proxy;
}
protected void initActionContext(ActionContext actionContext) {
actionContext.setParameters(HttpParameters.create(request.getParameterMap()).build());
initSession(actionContext);
// set the action context to the one used by the proxy
ActionContext.bind(actionContext);
}
protected void initSession(ActionContext actionContext) {
if (actionContext.getSession() == null) {
actionContext.withSession(new HashMap<>());
request.setSession(new MockHttpSession(servletContext));
}
}
/**
* Finds an ActionMapping for a given request
*/
protected ActionMapping getActionMapping(HttpServletRequest request) {
return container.getInstance(ActionMapper.class).getMapping(request, configurationManager);
}
/**
* Finds an ActionMapping for a given url
*/
protected ActionMapping getActionMapping(String url) {
MockHttpServletRequest req = new MockHttpServletRequest();
req.setRequestURI(url);
return getActionMapping(req);
}
/**
* Injects dependencies on an Object using Struts internal IoC container
*/
protected void injectStrutsDependencies(Object object) {
container.inject(object);
}
protected void setupBeforeInitDispatcher() throws Exception {
}
protected void initServletMockObjects() {
servletContext = new MockServletContext(resourceLoader);
response = new MockHttpServletResponse();
request = new MockHttpServletRequest();
pageContext = new MockPageContext(servletContext, request, response);
}
public void finishExecution() {
HttpSession session = this.request.getSession();
Enumeration attributeNames = session.getAttributeNames();
MockHttpServletRequest nextRequest = new MockHttpServletRequest();
while (attributeNames.hasMoreElements()) {
String key = (String) attributeNames.nextElement();
Object attribute = session.getAttribute(key);
nextRequest.getSession().setAttribute(key, attribute);
}
this.response = new MockHttpServletResponse();
this.request = nextRequest;
this.pageContext = new MockPageContext(servletContext, request, response);
}
/**
* Sets up the configuration settings, XWork configuration, and
* message resources
*/
@Before
public void setUp() throws Exception {
super.setUp();
initServletMockObjects();
setupBeforeInitDispatcher();
initDispatcherParams();
initDispatcher(dispatcherInitParams);
}
protected void initDispatcherParams() {
if (StringUtils.isNotBlank(getConfigPath())) {
dispatcherInitParams = new HashMap<>();
dispatcherInitParams.put("config", "struts-default.xml," + getConfigPath());
}
}
protected Dispatcher initDispatcher(Map<String, String> params) {
dispatcher = StrutsTestCaseHelper.initDispatcher(servletContext, params);
configurationManager = dispatcher.getConfigurationManager();
configuration = configurationManager.getConfiguration();
container = configuration.getContainer();
container.inject(dispatcher);
return dispatcher;
}
/**
* Override this method to return a comma separated list of paths to a configuration
* file.
* <p>The default implementation simply returns <code>null</code>.
* @return a comma separated list of config locations
*/
protected String getConfigPath() {
return null;
}
@After
public void tearDown() throws Exception {
super.tearDown();
if (dispatcher != null && dispatcher.getConfigurationManager() != null) {
dispatcher.cleanup();
dispatcher = null;
}
StrutsTestCaseHelper.tearDown();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.junit;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.interceptor.ValidationAware;
import com.opensymphony.xwork2.interceptor.annotations.After;
import com.opensymphony.xwork2.interceptor.annotations.Before;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.util.StrutsTestCaseHelper;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
public abstract class StrutsJUnit4TestCase<T> extends XWorkJUnit4TestCase {
protected MockHttpServletResponse response;
protected MockHttpServletRequest request;
protected MockPageContext pageContext;
protected MockServletContext servletContext;
protected Map<String, String> dispatcherInitParams;
protected Dispatcher dispatcher;
protected DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
/**
* gets an object from the stack after an action is executed
*/
protected Object findValueAfterExecute(String key) {
return ServletActionContext.getValueStack(request).findValue(key);
}
/**
* gets an object from the stack after an action is executed
*
* @return The executed action
*/
@SuppressWarnings("unchecked")
protected T getAction() {
return (T) findValueAfterExecute("action");
}
protected boolean containsErrors() {
T action = this.getAction();
if (action instanceof ValidationAware) {
return ((ValidationAware) action).hasActionErrors();
}
throw new UnsupportedOperationException("Current action does not implement ValidationAware interface");
}
/**
* Executes an action and returns it's output (not the result returned from
* execute()), but the actual output that would be written to the response.
* For this to work the configured result for the action needs to be
* FreeMarker, or Velocity (JSPs can be used with the Embedded JSP plugin)
*/
protected String executeAction(String uri) throws ServletException, UnsupportedEncodingException {
request.setRequestURI(uri);
ActionMapping mapping = getActionMapping(request);
assertNotNull(mapping);
Dispatcher.getInstance().serviceAction(request, response, mapping);
if (response.getStatus() != HttpServletResponse.SC_OK)
throw new ServletException("Error code [" + response.getStatus() + "], Error: ["
+ response.getErrorMessage() + "]");
return response.getContentAsString();
}
/**
* Creates an action proxy for a request, and sets parameters of the ActionInvocation to the passed
* parameters. Make sure to set the request parameters in the protected "request" object before calling this method.
*/
protected ActionProxy getActionProxy(String uri) {
request.setRequestURI(uri);
ActionMapping mapping = getActionMapping(request);
String namespace = mapping.getNamespace();
String name = mapping.getName();
String method = mapping.getMethod();
Configuration config = configurationManager.getConfiguration();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, new HashMap<String, Object>(), true, false);
initActionContext(proxy.getInvocation().getInvocationContext());
// this is normally done in onSetUp(), but we are using Struts internal
// objects (proxy and action invocation)
// so we have to hack around so it works
ServletActionContext.setServletContext(servletContext);
ServletActionContext.setRequest(request);
ServletActionContext.setResponse(response);
ServletActionContext.getContext().put(ServletActionContext.ACTION_MAPPING, mapping);
return proxy;
}
protected void initActionContext(ActionContext actionContext) {
actionContext.setParameters(HttpParameters.create(request.getParameterMap()).build());
initSession(actionContext);
// set the action context to the one used by the proxy
ActionContext.bind(actionContext);
}
protected void initSession(ActionContext actionContext) {
if (actionContext.getSession() == null) {
actionContext.withSession(new HashMap<>());
request.setSession(new MockHttpSession(servletContext));
}
}
/**
* Finds an ActionMapping for a given request
*/
protected ActionMapping getActionMapping(HttpServletRequest request) {
return container.getInstance(ActionMapper.class).getMapping(request, configurationManager);
}
/**
* Finds an ActionMapping for a given url
*/
protected ActionMapping getActionMapping(String url) {
MockHttpServletRequest req = new MockHttpServletRequest();
req.setRequestURI(url);
return getActionMapping(req);
}
/**
* Injects dependencies on an Object using Struts internal IoC container
*/
protected void injectStrutsDependencies(Object object) {
container.inject(object);
}
protected void setupBeforeInitDispatcher() throws Exception {
}
protected void initServletMockObjects() {
servletContext = new MockServletContext(resourceLoader);
response = new MockHttpServletResponse();
request = new MockHttpServletRequest();
pageContext = new MockPageContext(servletContext, request, response);
}
public void finishExecution() {
HttpSession session = this.request.getSession();
Enumeration attributeNames = session.getAttributeNames();
MockHttpServletRequest nextRequest = new MockHttpServletRequest();
while (attributeNames.hasMoreElements()) {
String key = (String) attributeNames.nextElement();
Object attribute = session.getAttribute(key);
nextRequest.getSession().setAttribute(key, attribute);
}
this.response = new MockHttpServletResponse();
this.request = nextRequest;
this.pageContext = new MockPageContext(servletContext, request, response);
}
/**
* Sets up the configuration settings, XWork configuration, and
* message resources
*/
@Before
public void setUp() throws Exception {
super.setUp();
initServletMockObjects();
setupBeforeInitDispatcher();
initDispatcherParams();
initDispatcher(dispatcherInitParams);
}
protected void initDispatcherParams() {
if (StringUtils.isNotBlank(getConfigPath())) {
dispatcherInitParams = new HashMap<>();
dispatcherInitParams.put("config", "struts-default.xml," + getConfigPath());
}
}
protected Dispatcher initDispatcher(Map<String, String> params) {
dispatcher = StrutsTestCaseHelper.initDispatcher(servletContext, params);
configurationManager = dispatcher.getConfigurationManager();
configuration = configurationManager.getConfiguration();
container = configuration.getContainer();
container.inject(dispatcher);
return dispatcher;
}
/**
* Override this method to return a comma separated list of paths to a configuration
* file.
* <p>The default implementation simply returns <code>null</code>.
*
* @return a comma separated list of config locations
*/
protected String getConfigPath() {
return null;
}
@After
public void tearDown() throws Exception {
super.tearDown();
if (dispatcher != null && dispatcher.getConfigurationManager() != null) {
dispatcher.cleanup();
dispatcher = null;
}
StrutsTestCaseHelper.tearDown();
}
}
@@ -16,15 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
import com.opensymphony.xwork2.ActionContext;
import java.util.HashMap;
import java.util.Map;
import javax.portlet.PortletMode;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.mock.web.portlet.MockPortletContext;
import org.apache.struts2.mock.web.portlet.MockPortletRequest;
import org.apache.struts2.mock.web.portlet.MockPortletResponse;
@@ -33,6 +31,10 @@ import org.apache.struts2.mock.web.portlet.MockStateAwareResponse;
import org.apache.struts2.portlet.PortletConstants;
import org.apache.struts2.portlet.PortletPhase;
import javax.portlet.PortletMode;
import java.util.HashMap;
import java.util.Map;
/*
* Changes: This is a copy of org.apache.struts2.StrutsPortletTestCase from the Struts 2 portlet-plugin, moved
* into the junit-plugin (same package org.apache.struts2).
@@ -16,12 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.config.Configuration;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
@@ -1,47 +1,47 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.support.GenericXmlContextLoader;
import org.springframework.web.context.WebApplicationContext;
/**
* Base class for Spring JUnit actions
*/
public abstract class StrutsSpringTestCase extends StrutsTestCase {
private static final String DEFAULT_CONTEXT_LOCATION = "classpath*:applicationContext.xml";
protected static ApplicationContext applicationContext;
protected void setupBeforeInitDispatcher() throws Exception {
// only load beans from spring once
if (applicationContext == null) {
GenericXmlContextLoader xmlContextLoader = new GenericXmlContextLoader();
applicationContext = xmlContextLoader.loadContext(getContextLocations());
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
}
protected String[] getContextLocations() {
return new String[] {DEFAULT_CONTEXT_LOCATION};
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.junit;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.support.GenericXmlContextLoader;
import org.springframework.web.context.WebApplicationContext;
/**
* Base class for Spring JUnit actions
*/
public abstract class StrutsSpringTestCase extends StrutsTestCase {
private static final String DEFAULT_CONTEXT_LOCATION = "classpath*:applicationContext.xml";
protected static ApplicationContext applicationContext;
protected void setupBeforeInitDispatcher() throws Exception {
// only load beans from spring once
if (applicationContext == null) {
GenericXmlContextLoader xmlContextLoader = new GenericXmlContextLoader();
applicationContext = xmlContextLoader.loadContext(getContextLocations());
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
}
protected String[] getContextLocations() {
return new String[]{DEFAULT_CONTEXT_LOCATION};
}
}
@@ -16,13 +16,14 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.XWorkTestCase;
import com.opensymphony.xwork2.config.Configuration;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
@@ -94,7 +95,7 @@ public abstract class StrutsTestCase extends XWorkTestCase {
Configuration config = configurationManager.getConfiguration();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, new HashMap<String, Object>(), true, false);
namespace, name, method, new HashMap<String, Object>(), true, false);
initActionContext(proxy.getInvocation().getInvocationContext());
@@ -16,13 +16,18 @@
* specific language governing permissions and limitations
* under the License.
*/
package com.opensymphony.xwork2;
package org.apache.struts2.junit;
import com.opensymphony.xwork2.ActionProxyFactory;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.inject.*;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.inject.Context;
import com.opensymphony.xwork2.inject.Factory;
import com.opensymphony.xwork2.inject.Scope;
import com.opensymphony.xwork2.test.StubConfigurationProvider;
import com.opensymphony.xwork2.util.XWorkTestCaseHelper;
import com.opensymphony.xwork2.util.location.LocatableProperties;
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.util;
package org.apache.struts2.junit.util;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
@@ -1,39 +1,39 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
public class JUnitTestAction extends ActionSupport {
private static final long serialVersionUID = 1629266238339053546L;
private String name;
@Autowired
private MySessionBean mySessionBean;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.junit;
import com.opensymphony.xwork2.ActionSupport;
import org.springframework.beans.factory.annotation.Autowired;
public class JUnitTestAction extends ActionSupport {
private static final long serialVersionUID = 1629266238339053546L;
private String name;
@Autowired
private MySessionBean mySessionBean;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
public class MySessionBean {
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
import com.opensymphony.xwork2.ActionProxy;
import org.junit.Assert;
@@ -27,7 +27,7 @@ import org.junit.Test;
* Date: 8/15/11
* Time: 7:04 PM
*/
public class StrutsJUnit4TestCaseTest extends StrutsJUnit4TestCase<JUnitTestAction>{
public class StrutsJUnit4TestCaseTest extends StrutsJUnit4TestCase<JUnitTestAction> {
@Test
public void testExecuteActionAgainstCustomStrutsConfigFile() throws Exception {
String output = executeAction("/test/testAction-2.action");
@@ -38,7 +38,7 @@ public class StrutsJUnit4TestCaseTest extends StrutsJUnit4TestCase<JUnitTestActi
public void testSessionInitialized() throws Exception {
ActionProxy proxy = getActionProxy("/test/testAction-2.action");
Assert.assertNotNull("invocation session should being initialized",
proxy.getInvocation().getInvocationContext().getSession());
proxy.getInvocation().getInvocationContext().getSession());
}
@Override
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
package org.apache.struts2.junit;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionProxy;
@@ -30,11 +30,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.ServletException;
import java.io.UnsupportedEncodingException;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public class StrutsSpringJUnit4TestCaseTest extends StrutsSpringJUnit4TestCase<JUnitTestAction> {
@Test
@Test
public void getActionMapping() {
ActionMapping mapping = getActionMapping("/test/testAction.action");
Assert.assertNotNull(mapping);
@@ -42,11 +42,11 @@ public class StrutsSpringJUnit4TestCaseTest extends StrutsSpringJUnit4TestCase<J
Assert.assertEquals("testAction", mapping.getName());
}
@Test
@Test
public void getActionProxy() throws Exception {
//set parameters before calling getActionProxy
request.setParameter("name", "FD");
ActionProxy proxy = getActionProxy("/test/testAction.action");
Assert.assertNotNull(proxy);
@@ -58,13 +58,13 @@ public class StrutsSpringJUnit4TestCaseTest extends StrutsSpringJUnit4TestCase<J
Assert.assertEquals("FD", action.getName());
}
@Test
@Test
public void executeAction() throws ServletException, UnsupportedEncodingException {
String output = executeAction("/test/testAction.action");
Assert.assertEquals("Hello", output);
}
@Test
@Test
public void getValueFromStack() throws ServletException, UnsupportedEncodingException {
request.setParameter("name", "FD");
executeAction("/test/testAction.action");
@@ -1,27 +1,27 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
public class StrutsSpringTestCaseTest extends StrutsSpringTestCase {
public void testApplicationContext() {
assertNotNull(applicationContext);
JUnitTestAction action = (JUnitTestAction) applicationContext.getBean("testAction");
assertNotNull(action);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.junit;
public class StrutsSpringTestCaseTest extends StrutsSpringTestCase {
public void testApplicationContext() {
assertNotNull(applicationContext);
JUnitTestAction action = (JUnitTestAction) applicationContext.getBean("testAction");
assertNotNull(action);
}
}
@@ -1,100 +1,101 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.junit.Test;
import javax.portlet.PortletContext;
import javax.servlet.ServletException;
import java.io.UnsupportedEncodingException;
public class StrutsTestCaseTest extends StrutsSpringTestCase {
public void testGetActionMapping() {
ActionMapping mapping = getActionMapping("/test/testAction.action");
assertNotNull(mapping);
assertEquals("/test", mapping.getNamespace());
assertEquals("testAction", mapping.getName());
}
public void testGetActionProxy() throws Exception {
//set parameters before calling getActionProxy
request.setParameter("name", "FD");
ActionProxy proxy = getActionProxy("/test/testAction.action");
assertNotNull(proxy);
JUnitTestAction action = (JUnitTestAction) proxy.getAction();
assertNotNull(action);
String result = proxy.execute();
assertEquals(Action.SUCCESS, result);
assertEquals("FD", action.getName());
}
public void testExecuteAction() throws ServletException, UnsupportedEncodingException {
String output = executeAction("/test/testAction.action");
assertEquals("Hello", output);
}
public void testGetValueFromStack() throws ServletException, UnsupportedEncodingException {
request.setParameter("name", "FD");
executeAction("/test/testAction.action");
String name = (String) findValueAfterExecute("name");
assertEquals("FD", name);
}
@Test
public void shouldPortletContextBeAvailable() throws Exception {
// given
assertNull(ActionContext.getContext().get(StrutsStatics.STRUTS_PORTLET_CONTEXT));
// when
String output = executeAction("/test/testAction.action");
assertEquals("Hello", output);
// then
Object portletContext = ActionContext.getContext().get(StrutsStatics.STRUTS_PORTLET_CONTEXT);
assertNotNull(portletContext);
assertTrue(portletContext instanceof PortletContext);
}
@Test
public void shouldAdditionalContextParamsBeAvailable() throws Exception {
// given
String key = "my-param";
assertNull(ActionContext.getContext().get(key));
// when
String output = executeAction("/test/testAction.action");
assertEquals("Hello", output);
// then
assertNotNull(ActionContext.getContext().get(key));
}
@Override
protected void applyAdditionalParams(ActionContext context) {
context.put("my-param", new Object());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.junit;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionProxy;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.junit.Test;
import javax.portlet.PortletContext;
import javax.servlet.ServletException;
import java.io.UnsupportedEncodingException;
public class StrutsTestCaseTest extends StrutsSpringTestCase {
public void testGetActionMapping() {
ActionMapping mapping = getActionMapping("/test/testAction.action");
assertNotNull(mapping);
assertEquals("/test", mapping.getNamespace());
assertEquals("testAction", mapping.getName());
}
public void testGetActionProxy() throws Exception {
//set parameters before calling getActionProxy
request.setParameter("name", "FD");
ActionProxy proxy = getActionProxy("/test/testAction.action");
assertNotNull(proxy);
JUnitTestAction action = (JUnitTestAction) proxy.getAction();
assertNotNull(action);
String result = proxy.execute();
assertEquals(Action.SUCCESS, result);
assertEquals("FD", action.getName());
}
public void testExecuteAction() throws ServletException, UnsupportedEncodingException {
String output = executeAction("/test/testAction.action");
assertEquals("Hello", output);
}
public void testGetValueFromStack() throws ServletException, UnsupportedEncodingException {
request.setParameter("name", "FD");
executeAction("/test/testAction.action");
String name = (String) findValueAfterExecute("name");
assertEquals("FD", name);
}
@Test
public void shouldPortletContextBeAvailable() throws Exception {
// given
assertNull(ActionContext.getContext().get(StrutsStatics.STRUTS_PORTLET_CONTEXT));
// when
String output = executeAction("/test/testAction.action");
assertEquals("Hello", output);
// then
Object portletContext = ActionContext.getContext().get(StrutsStatics.STRUTS_PORTLET_CONTEXT);
assertNotNull(portletContext);
assertTrue(portletContext instanceof PortletContext);
}
@Test
public void shouldAdditionalContextParamsBeAvailable() throws Exception {
// given
String key = "my-param";
assertNull(ActionContext.getContext().get(key));
// when
String output = executeAction("/test/testAction.action");
assertEquals("Hello", output);
// then
assertNotNull(ActionContext.getContext().get(key));
}
@Override
protected void applyAdditionalParams(ActionContext context) {
context.put("my-param", new Object());
}
}
@@ -16,10 +16,10 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.convention;
package org.apache.struts2.junit.convention;
import actions.ViewAction;
import org.apache.struts2.StrutsJUnit4TestCase;
import org.apache.struts2.junit.StrutsJUnit4TestCase;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.session;
package org.apache.struts2.junit.session;
import com.opensymphony.xwork2.ActionSupport;
@@ -16,7 +16,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.session;
package org.apache.struts2.junit.session;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@@ -16,22 +16,22 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.struts2.session;
package org.apache.struts2.junit.session;
import org.apache.struts2.JUnitTestAction;
import org.apache.struts2.StrutsJUnit4TestCase;
import org.apache.struts2.junit.JUnitTestAction;
import org.apache.struts2.junit.StrutsJUnit4TestCase;
import org.junit.Assert;
import org.junit.Test;
/**
* Calls SessionSet which sets a value into the session and afterwards calls SessionGet, which
* should return this session value.
*
* <p>
* In prior versions only one executeAction() call could happen in a single test case, because
* either the session values were deleted or the wrong result would be returned (always the result of
* the first action execution).
*/
public class StrutsJUnit4SessionTestCaseTest extends StrutsJUnit4TestCase<JUnitTestAction>{
public class StrutsJUnit4SessionTestCaseTest extends StrutsJUnit4TestCase<JUnitTestAction> {
@Test
public void testPersistingSessionValues() throws Exception {
String output = executeAction("/sessiontest/sessionSet.action");
@@ -33,6 +33,6 @@
</property>
</bean>
<bean id="testAction" class="org.apache.struts2.JUnitTestAction"/>
<bean id="mySessionBean" class="org.apache.struts2.MySessionBean" scope="session" />
</beans>
<bean id="testAction" class="org.apache.struts2.junit.JUnitTestAction"/>
<bean id="mySessionBean" class="org.apache.struts2.junit.MySessionBean" scope="session"/>
</beans>
@@ -21,15 +21,15 @@
-->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="test" namespace="/sessiontest" extends="struts-default">
<action name="sessionSet" class="org.apache.struts2.session.SessionSetAction">
<action name="sessionSet" class="org.apache.struts2.junit.session.SessionSetAction">
<result type="freemarker">/template-session.ftl</result>
</action>
<action name="sessionGet" class="org.apache.struts2.session.SessionGetAction">
<action name="sessionGet" class="org.apache.struts2.junit.session.SessionGetAction">
<result type="freemarker">/template-session.ftl</result>
</action>
</package>
@@ -20,12 +20,12 @@
*/
-->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="test" namespace="/test" extends="struts-default">
<action name="testAction-2" class="org.apache.struts2.JUnitTestAction">
<action name="testAction-2" class="org.apache.struts2.junit.JUnitTestAction">
<result type="freemarker">/template-2.ftl</result>
</action>
</package>
+4 -4
View File
@@ -20,14 +20,14 @@
*/
-->
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.objectFactory" value="spring"/>
<package name="test" namespace="/test" extends="struts-default">
<action name="testAction" class="org.apache.struts2.JUnitTestAction">
<action name="testAction" class="org.apache.struts2.junit.JUnitTestAction">
<result type="freemarker">/template-1.ftl</result>
</action>
</package>
</struts>
</struts>