Migrate JUnit 3 tests to JUnit 4

This commit migrates all remaining tests from JUnit 3 to JUnit 4, with
the exception of Spring's legacy JUnit 3.8 based testing framework that
is still in use in the spring-orm module.

Issue: SPR-13514
This commit is contained in:
Sam Brannen
2015-09-26 00:10:58 +02:00
parent 1580288815
commit d5ee787e1e
213 changed files with 4879 additions and 3939 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,19 +19,22 @@ package org.springframework.web.context;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.mock.web.test.MockServletConfig;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.support.ServletContextAwareProcessor;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Mark Fisher
*/
public class ServletContextAwareProcessorTests extends TestCase {
public class ServletContextAwareProcessorTests {
public void testServletContextAwareWithServletContext() {
@Test
public void servletContextAwareWithServletContext() {
ServletContext servletContext = new MockServletContext();
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
ServletContextAwareBean bean = new ServletContextAwareBean();
@@ -41,7 +44,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletContext, bean.getServletContext());
}
public void testServletContextAwareWithServletConfig() {
@Test
public void servletContextAwareWithServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletConfig servletConfig = new MockServletConfig(servletContext);
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletConfig);
@@ -52,7 +56,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletContext, bean.getServletContext());
}
public void testServletContextAwareWithServletContextAndServletConfig() {
@Test
public void servletContextAwareWithServletContextAndServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletConfig servletConfig = new MockServletConfig(servletContext);
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, servletConfig);
@@ -63,7 +68,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletContext, bean.getServletContext());
}
public void testServletContextAwareWithNullServletContextAndNonNullServletConfig() {
@Test
public void servletContextAwareWithNullServletContextAndNonNullServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletConfig servletConfig = new MockServletConfig(servletContext);
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig);
@@ -74,7 +80,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletContext, bean.getServletContext());
}
public void testServletContextAwareWithNonNullServletContextAndNullServletConfig() {
@Test
public void servletContextAwareWithNonNullServletContextAndNullServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, null);
ServletContextAwareBean bean = new ServletContextAwareBean();
@@ -84,7 +91,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletContext, bean.getServletContext());
}
public void testServletContextAwareWithNullServletContext() {
@Test
public void servletContextAwareWithNullServletContext() {
ServletContext servletContext = null;
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
ServletContextAwareBean bean = new ServletContextAwareBean();
@@ -93,7 +101,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertNull(bean.getServletContext());
}
public void testServletConfigAwareWithServletContextOnly() {
@Test
public void servletConfigAwareWithServletContextOnly() {
ServletContext servletContext = new MockServletContext();
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
ServletConfigAwareBean bean = new ServletConfigAwareBean();
@@ -102,7 +111,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertNull(bean.getServletConfig());
}
public void testServletConfigAwareWithServletConfig() {
@Test
public void servletConfigAwareWithServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletConfig servletConfig = new MockServletConfig(servletContext);
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletConfig);
@@ -113,7 +123,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletConfig, bean.getServletConfig());
}
public void testServletConfigAwareWithServletContextAndServletConfig() {
@Test
public void servletConfigAwareWithServletContextAndServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletConfig servletConfig = new MockServletConfig(servletContext);
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, servletConfig);
@@ -124,7 +135,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletConfig, bean.getServletConfig());
}
public void testServletConfigAwareWithNullServletContextAndNonNullServletConfig() {
@Test
public void servletConfigAwareWithNullServletContextAndNonNullServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletConfig servletConfig = new MockServletConfig(servletContext);
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig);
@@ -135,7 +147,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertEquals(servletConfig, bean.getServletConfig());
}
public void testServletConfigAwareWithNonNullServletContextAndNullServletConfig() {
@Test
public void servletConfigAwareWithNonNullServletContextAndNullServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext, null);
ServletConfigAwareBean bean = new ServletConfigAwareBean();
@@ -144,7 +157,8 @@ public class ServletContextAwareProcessorTests extends TestCase {
assertNull(bean.getServletConfig());
}
public void testServletConfigAwareWithNullServletContext() {
@Test
public void servletConfigAwareWithNullServletContext() {
ServletContext servletContext = null;
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(servletContext);
ServletConfigAwareBean bean = new ServletConfigAwareBean();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,8 +17,11 @@
package org.springframework.web.context;
import java.util.Locale;
import javax.servlet.ServletException;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
@@ -57,7 +60,6 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
@Override
@SuppressWarnings("unchecked")
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof TestBean) {
((TestBean) bean).getFriends().add("myFriend");
@@ -82,7 +84,8 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
return wac;
}
public void testEnvironmentMerge() {
@Test
public void environmentMerge() {
assertThat(this.root.getEnvironment().acceptsProfiles("rootProfile1"), is(true));
assertThat(this.root.getEnvironment().acceptsProfiles("wacProfile1"), is(false));
assertThat(this.applicationContext.getEnvironment().acceptsProfiles("rootProfile1"), is(true));
@@ -101,13 +104,16 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
super.doTestEvents(listenerBean, parentListenerBean, event);
}
@Test
@Override
public void testCount() {
public void count() {
assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(),
this.applicationContext.getBeanDefinitionCount() == 14);
}
public void testWithoutMessageSource() throws Exception {
@Test
@SuppressWarnings("resource")
public void withoutMessageSource() throws Exception {
MockServletContext sc = new MockServletContext("");
XmlWebApplicationContext wac = new XmlWebApplicationContext();
wac.setParent(root);
@@ -126,7 +132,8 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
assertTrue("Default message returned", "default".equals(msg));
}
public void testContextNesting() {
@Test
public void contextNesting() {
TestBean father = (TestBean) this.applicationContext.getBean("father");
assertTrue("Bean from root context", father != null);
assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend"));
@@ -141,7 +148,8 @@ public class XmlWebApplicationContextTests extends AbstractApplicationContextTes
assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend"));
}
public void testInitializingBeanAndInitMethod() throws Exception {
@Test
public void initializingBeanAndInitMethod() throws Exception {
assertFalse(InitAndIB.constructed);
InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib");
assertTrue(InitAndIB.constructed);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -89,7 +89,7 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
UserRoleAuthorizationInterceptor interceptor5 = new UserRoleAuthorizationInterceptor();
interceptor5.setAuthorizedRoles(new String[] {"role1", "role2"});
List interceptors = new ArrayList();
List<Object> interceptors = new ArrayList<>();
interceptors.add(interceptor5);
interceptors.add(interceptor1);
interceptors.add(interceptor2);
@@ -158,7 +158,7 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
pvs = new MutablePropertyValues();
pvs.add("order", "0");
pvs.add("exceptionMappings", "java.lang.Exception=failed1");
List mappedHandlers = new ManagedList();
List<RuntimeBeanReference> mappedHandlers = new ManagedList<RuntimeBeanReference>();
mappedHandlers.add(new RuntimeBeanReference("anotherLocaleHandler"));
pvs.add("mappedHandlers", mappedHandlers);
pvs.add("defaultStatusCode", "500");
@@ -397,6 +397,7 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
public static class ComplexLocaleChecker implements MyHandler {
@Override
@SuppressWarnings("deprecation")
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException {
WebApplicationContext wac = RequestContextUtils.getWebApplicationContext(request);
if (!(wac instanceof ComplexWebApplicationContext)) {
@@ -506,7 +507,7 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
}
public static class TestApplicationListener implements ApplicationListener {
public static class TestApplicationListener implements ApplicationListener<ApplicationEvent> {
public int counter = 0;

View File

@@ -26,7 +26,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
@@ -60,27 +61,29 @@ import org.springframework.web.util.WebUtils;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Rob Harrop
* @author Sam Brannen
*/
public class DispatcherServletTests extends TestCase {
public class DispatcherServletTests {
private static final String URL_KNOWN_ONLY_PARENT = "/knownOnlyToParent.do";
private MockServletConfig servletConfig;
private final MockServletConfig servletConfig = new MockServletConfig(new MockServletContext(), "simple");
private DispatcherServlet simpleDispatcherServlet;
private DispatcherServlet complexDispatcherServlet;
@Override
protected void setUp() throws ServletException {
servletConfig = new MockServletConfig(new MockServletContext(), "simple");
MockServletConfig complexConfig = new MockServletConfig(servletConfig.getServletContext(), "complex");
@Before
public void setUp() throws ServletException {
MockServletConfig complexConfig = new MockServletConfig(getServletContext(), "complex");
complexConfig.addInitParameter("publishContext", "false");
complexConfig.addInitParameter("class", "notWritable");
complexConfig.addInitParameter("unknownParam", "someValue");
@@ -100,14 +103,16 @@ public class DispatcherServletTests extends TestCase {
return servletConfig.getServletContext();
}
public void testDispatcherServletGetServletNameDoesNotFailWithoutConfig() {
@Test
public void dispatcherServletGetServletNameDoesNotFailWithoutConfig() {
DispatcherServlet ds = new DispatcherServlet();
assertNull(ds.getServletConfig());
assertNull(ds.getServletName());
assertNull(ds.getServletContext());
}
public void testConfiguredDispatcherServlets() {
@Test
public void configuredDispatcherServlets() {
assertTrue("Correct namespace",
("simple" + FrameworkServlet.DEFAULT_NAMESPACE_SUFFIX).equals(simpleDispatcherServlet.getNamespace()));
assertTrue("Correct attribute", (FrameworkServlet.SERVLET_CONTEXT_PREFIX + "simple").equals(
@@ -125,7 +130,8 @@ public class DispatcherServletTests extends TestCase {
complexDispatcherServlet.destroy();
}
public void testInvalidRequest() throws Exception {
@Test
public void invalidRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/invalid.do");
MockHttpServletResponse response = new MockHttpServletResponse();
simpleDispatcherServlet.service(request, response);
@@ -133,7 +139,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("correct error code", response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
}
public void testRequestHandledEvent() throws Exception {
@Test
public void requestHandledEvent() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
MockHttpServletResponse response = new MockHttpServletResponse();
complexDispatcherServlet.service(request, response);
@@ -143,7 +150,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals(1, listener.counter);
}
public void testPublishEventsOff() throws Exception {
@Test
public void publishEventsOff() throws Exception {
complexDispatcherServlet.setPublishEvents(false);
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -154,7 +162,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals(0, listener.counter);
}
public void testParameterizableViewController() throws Exception {
@Test
public void parameterizableViewController() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/view.do");
request.addUserRole("role1");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -162,7 +171,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("forwarded to form", "myform.jsp".equals(response.getForwardedUrl()));
}
public void testHandlerInterceptorSuppressesView() throws Exception {
@Test
public void handlerInterceptorSuppressesView() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/view.do");
request.addUserRole("role1");
request.addParameter("noView", "true");
@@ -171,7 +181,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Not forwarded", response.getForwardedUrl() == null);
}
public void testLocaleRequest() throws Exception {
@Test
public void localeRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -180,7 +191,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals("Wed, 01 Apr 2015 00:00:00 GMT", response.getHeader("Last-Modified"));
}
public void testUnknownRequest() throws Exception {
@Test
public void unknownRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/unknown.do");
MockHttpServletResponse response = new MockHttpServletResponse();
complexDispatcherServlet.service(request, response);
@@ -188,7 +200,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
}
public void testAnotherLocaleRequest() throws Exception {
@Test
public void anotherLocaleRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -208,7 +221,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals("Wed, 01 Apr 2015 00:00:01 GMT", response.getHeader("Last-Modified"));
}
public void testExistingMultipartRequest() throws Exception {
@Test
public void existingMultipartRequest() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -223,7 +237,8 @@ public class DispatcherServletTests extends TestCase {
assertNotNull(request.getAttribute("cleanedUp"));
}
public void testExistingMultipartRequestButWrapped() throws Exception {
@Test
public void existingMultipartRequestButWrapped() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -238,7 +253,8 @@ public class DispatcherServletTests extends TestCase {
assertNotNull(request.getAttribute("cleanedUp"));
}
public void testMultipartResolutionFailed() throws Exception {
@Test
public void multipartResolutionFailed() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do;abc=def");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -251,7 +267,8 @@ public class DispatcherServletTests extends TestCase {
SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE) instanceof MaxUploadSizeExceededException);
}
public void testHandlerInterceptorAbort() throws Exception {
@Test
public void handlerInterceptorAbort() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addParameter("abort", "true");
request.addPreferredLocale(Locale.CANADA);
@@ -267,7 +284,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue(request.getAttribute("test2y") == null);
}
public void testModelAndViewDefiningException() throws Exception {
@Test
public void modelAndViewDefiningException() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -283,7 +301,8 @@ public class DispatcherServletTests extends TestCase {
}
}
public void testSimpleMappingExceptionResolverWithSpecificHandler1() throws Exception {
@Test
public void simpleMappingExceptionResolverWithSpecificHandler1() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -295,7 +314,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception") instanceof IllegalAccessException);
}
public void testSimpleMappingExceptionResolverWithSpecificHandler2() throws Exception {
@Test
public void simpleMappingExceptionResolverWithSpecificHandler2() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -307,7 +327,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception") instanceof ServletException);
}
public void testSimpleMappingExceptionResolverWithAllHandlers1() throws Exception {
@Test
public void simpleMappingExceptionResolverWithAllHandlers1() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/loc.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -319,7 +340,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception") instanceof IllegalAccessException);
}
public void testSimpleMappingExceptionResolverWithAllHandlers2() throws Exception {
@Test
public void simpleMappingExceptionResolverWithAllHandlers2() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/loc.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -331,7 +353,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception") instanceof ServletException);
}
public void testSimpleMappingExceptionResolverWithDefaultErrorView() throws Exception {
@Test
public void simpleMappingExceptionResolverWithDefaultErrorView() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -343,7 +366,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(RuntimeException.class));
}
public void testLocaleChangeInterceptor1() throws Exception {
@Test
public void localeChangeInterceptor1() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.GERMAN);
request.addUserRole("role2");
@@ -355,7 +379,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
}
public void testLocaleChangeInterceptor2() throws Exception {
@Test
public void localeChangeInterceptor2() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.GERMAN);
request.addUserRole("role2");
@@ -366,7 +391,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Not forwarded", response.getForwardedUrl() == null);
}
public void testThemeChangeInterceptor1() throws Exception {
@Test
public void themeChangeInterceptor1() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -378,7 +404,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
}
public void testThemeChangeInterceptor2() throws Exception {
@Test
public void themeChangeInterceptor2() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
request.addUserRole("role1");
@@ -394,7 +421,8 @@ public class DispatcherServletTests extends TestCase {
}
}
public void testNotAuthorized() throws Exception {
@Test
public void notAuthorized() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/locale.do");
request.addPreferredLocale(Locale.CANADA);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -407,7 +435,8 @@ public class DispatcherServletTests extends TestCase {
}
}
public void testHeadMethodWithExplicitHandling() throws Exception {
@Test
public void headMethodWithExplicitHandling() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "HEAD", "/head.do");
MockHttpServletResponse response = new MockHttpServletResponse();
complexDispatcherServlet.service(request, response);
@@ -419,7 +448,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals("", response.getContentAsString());
}
public void testHeadMethodWithNoBodyResponse() throws Exception {
@Test
public void headMethodWithNoBodyResponse() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "HEAD", "/body.do");
MockHttpServletResponse response = new MockHttpServletResponse();
complexDispatcherServlet.service(request, response);
@@ -431,7 +461,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals("body", response.getContentAsString());
}
public void testNotDetectAllHandlerMappings() throws ServletException, IOException {
@Test
public void notDetectAllHandlerMappings() throws ServletException, IOException {
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
complexDispatcherServlet.setNamespace("test");
@@ -444,7 +475,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue(response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
}
public void testHandlerNotMappedWithAutodetect() throws ServletException, IOException {
@Test
public void handlerNotMappedWithAutodetect() throws ServletException, IOException {
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
// no parent
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
@@ -457,10 +489,11 @@ public class DispatcherServletTests extends TestCase {
assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
}
public void testDetectHandlerMappingFromParent() throws ServletException, IOException {
@Test
public void detectHandlerMappingFromParent() throws ServletException, IOException {
// create a parent context that includes a mapping
StaticWebApplicationContext parent = new StaticWebApplicationContext();
parent.setServletContext(servletConfig.getServletContext());
parent.setServletContext(getServletContext());
parent.registerSingleton("parentHandler", ControllerFromParent.class, new MutablePropertyValues());
MutablePropertyValues pvs = new MutablePropertyValues();
@@ -486,7 +519,8 @@ public class DispatcherServletTests extends TestCase {
response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
}
public void testDetectAllHandlerAdapters() throws ServletException, IOException {
@Test
public void detectAllHandlerAdapters() throws ServletException, IOException {
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
complexDispatcherServlet.setNamespace("test");
@@ -502,7 +536,8 @@ public class DispatcherServletTests extends TestCase {
complexDispatcherServlet.service(request, response);
}
public void testNotDetectAllHandlerAdapters() throws ServletException, IOException {
@Test
public void notDetectAllHandlerAdapters() throws ServletException, IOException {
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
complexDispatcherServlet.setNamespace("test");
@@ -523,7 +558,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue("Exception exposed", request.getAttribute("exception").getClass().equals(ServletException.class));
}
public void testNotDetectAllHandlerExceptionResolvers() throws ServletException, IOException {
@Test
public void notDetectAllHandlerExceptionResolvers() throws ServletException, IOException {
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
complexDispatcherServlet.setNamespace("test");
@@ -542,7 +578,8 @@ public class DispatcherServletTests extends TestCase {
}
}
public void testNotDetectAllViewResolvers() throws ServletException, IOException {
@Test
public void notDetectAllViewResolvers() throws ServletException, IOException {
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
complexDispatcherServlet.setNamespace("test");
@@ -561,7 +598,8 @@ public class DispatcherServletTests extends TestCase {
}
}
public void testThrowExceptionIfNoHandlerFound() throws ServletException, IOException {
@Test
public void throwExceptionIfNoHandlerFound() throws ServletException, IOException {
DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
complexDispatcherServlet.setContextClass(SimpleWebApplicationContext.class);
complexDispatcherServlet.setNamespace("test");
@@ -577,7 +615,8 @@ public class DispatcherServletTests extends TestCase {
// SPR-12984
public void testNoHandlerFoundExceptionMessage() {
@Test
public void noHandlerFoundExceptionMessage() {
HttpHeaders headers = new HttpHeaders();
headers.add("foo", "bar");
NoHandlerFoundException ex = new NoHandlerFoundException("GET", "/foo", headers);
@@ -585,7 +624,8 @@ public class DispatcherServletTests extends TestCase {
assertTrue(!ex.toString().contains("bar"));
}
public void testCleanupAfterIncludeWithRemove() throws ServletException, IOException {
@Test
public void cleanupAfterIncludeWithRemove() throws ServletException, IOException {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -604,7 +644,8 @@ public class DispatcherServletTests extends TestCase {
assertNull(request.getAttribute("command"));
}
public void testCleanupAfterIncludeWithRestore() throws ServletException, IOException {
@Test
public void cleanupAfterIncludeWithRestore() throws ServletException, IOException {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -623,7 +664,8 @@ public class DispatcherServletTests extends TestCase {
assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
public void testNoCleanupAfterInclude() throws ServletException, IOException {
@Test
public void noCleanupAfterInclude() throws ServletException, IOException {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -643,7 +685,8 @@ public class DispatcherServletTests extends TestCase {
assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
public void testServletHandlerAdapter() throws Exception {
@Test
public void servletHandlerAdapter() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/servlet.do");
MockHttpServletResponse response = new MockHttpServletResponse();
complexDispatcherServlet.service(request, response);
@@ -656,7 +699,9 @@ public class DispatcherServletTests extends TestCase {
assertNull(myServlet.getServletConfig());
}
public void testWebApplicationContextLookup() {
@Test
@SuppressWarnings("deprecation")
public void webApplicationContextLookup() {
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/invalid.do");
@@ -686,7 +731,8 @@ public class DispatcherServletTests extends TestCase {
}
}
public void testWithNoView() throws Exception {
@Test
public void withNoView() throws Exception {
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/noview.do");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -695,7 +741,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals("noview.jsp", response.getForwardedUrl());
}
public void testWithNoViewNested() throws Exception {
@Test
public void withNoViewNested() throws Exception {
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/noview/simple.do");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -704,7 +751,8 @@ public class DispatcherServletTests extends TestCase {
assertEquals("noview/simple.jsp", response.getForwardedUrl());
}
public void testWithNoViewAndSamePath() throws Exception {
@Test
public void withNoViewAndSamePath() throws Exception {
InternalResourceViewResolver vr = (InternalResourceViewResolver) complexDispatcherServlet
.getWebApplicationContext().getBean("viewResolver2");
vr.setSuffix("");
@@ -722,7 +770,8 @@ public class DispatcherServletTests extends TestCase {
}
}
public void testDispatcherServletRefresh() throws ServletException {
@Test
public void dispatcherServletRefresh() throws ServletException {
MockServletContext servletContext = new MockServletContext("org/springframework/web/context");
DispatcherServlet servlet = new DispatcherServlet();
@@ -752,7 +801,8 @@ public class DispatcherServletTests extends TestCase {
servlet.destroy();
}
public void testDispatcherServletContextRefresh() throws ServletException {
@Test
public void dispatcherServletContextRefresh() throws ServletException {
MockServletContext servletContext = new MockServletContext("org/springframework/web/context");
DispatcherServlet servlet = new DispatcherServlet();
@@ -782,7 +832,8 @@ public class DispatcherServletTests extends TestCase {
servlet.destroy();
}
public void testEnvironmentOperations() {
@Test
public void environmentOperations() {
DispatcherServlet servlet = new DispatcherServlet();
ConfigurableEnvironment defaultEnv = servlet.getEnvironment();
assertThat(defaultEnv, notNullValue());
@@ -806,7 +857,8 @@ public class DispatcherServletTests extends TestCase {
assertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.class));
}
public void testAllowedOptionsIncludesPatchMethod() throws Exception {
@Test
public void allowedOptionsIncludesPatchMethod() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "OPTIONS", "/foo");
MockHttpServletResponse response = spy(new MockHttpServletResponse());
DispatcherServlet servlet = new DispatcherServlet();
@@ -815,44 +867,48 @@ public class DispatcherServletTests extends TestCase {
assertThat(response.getHeader("Allow"), equalTo("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"));
}
public void testContextInitializers() throws Exception {
@Test
public void contextInitializers() throws Exception {
DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextClass(SimpleWebApplicationContext.class);
servlet.setContextInitializers(new TestWebContextInitializer(), new OtherWebContextInitializer());
servlet.init(servletConfig);
assertEquals("true", servletConfig.getServletContext().getAttribute("initialized"));
assertEquals("true", servletConfig.getServletContext().getAttribute("otherInitialized"));
assertEquals("true", getServletContext().getAttribute("initialized"));
assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
public void testContextInitializerClasses() throws Exception {
@Test
public void contextInitializerClasses() throws Exception {
DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextClass(SimpleWebApplicationContext.class);
servlet.setContextInitializerClasses(
TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName());
servlet.init(servletConfig);
assertEquals("true", servletConfig.getServletContext().getAttribute("initialized"));
assertEquals("true", servletConfig.getServletContext().getAttribute("otherInitialized"));
assertEquals("true", getServletContext().getAttribute("initialized"));
assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
public void testGlobalInitializerClasses() throws Exception {
@Test
public void globalInitializerClasses() throws Exception {
DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextClass(SimpleWebApplicationContext.class);
servletConfig.getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
TestWebContextInitializer.class.getName() + "," + OtherWebContextInitializer.class.getName());
servlet.init(servletConfig);
assertEquals("true", servletConfig.getServletContext().getAttribute("initialized"));
assertEquals("true", servletConfig.getServletContext().getAttribute("otherInitialized"));
assertEquals("true", getServletContext().getAttribute("initialized"));
assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}
public void testMixedInitializerClasses() throws Exception {
@Test
public void mixedInitializerClasses() throws Exception {
DispatcherServlet servlet = new DispatcherServlet();
servlet.setContextClass(SimpleWebApplicationContext.class);
servletConfig.getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
getServletContext().setInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM,
TestWebContextInitializer.class.getName());
servlet.setContextInitializerClasses(OtherWebContextInitializer.class.getName());
servlet.init(servletConfig);
assertEquals("true", servletConfig.getServletContext().getAttribute("initialized"));
assertEquals("true", servletConfig.getServletContext().getAttribute("otherInitialized"));
assertEquals("true", getServletContext().getAttribute("initialized"));
assertEquals("true", getServletContext().getAttribute("otherInitialized"));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -74,6 +74,7 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext {
public static class LocaleChecker implements Controller, LastModified {
@Override
@SuppressWarnings("deprecation")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!(RequestContextUtils.getWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,8 @@ package org.springframework.web.servlet.handler;
import javax.servlet.ServletException;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.mock.web.test.MockHttpServletRequest;
@@ -28,17 +29,20 @@ import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class BeanNameUrlHandlerMappingTests extends TestCase {
public class BeanNameUrlHandlerMappingTests {
public static final String CONF = "/org/springframework/web/servlet/handler/map1.xml";
private ConfigurableWebApplicationContext wac;
@Override
@Before
public void setUp() throws Exception {
MockServletContext sc = new MockServletContext("");
wac = new XmlWebApplicationContext();
@@ -47,7 +51,8 @@ public class BeanNameUrlHandlerMappingTests extends TestCase {
wac.refresh();
}
public void testRequestsWithoutHandlers() throws Exception {
@Test
public void requestsWithoutHandlers() throws Exception {
HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping");
MockHttpServletRequest req = new MockHttpServletRequest("GET", "/mypath/nonsense.html");
@@ -60,12 +65,14 @@ public class BeanNameUrlHandlerMappingTests extends TestCase {
assertTrue("Handler is null", h == null);
}
public void testRequestsWithSubPaths() throws Exception {
@Test
public void requestsWithSubPaths() throws Exception {
HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping");
doTestRequestsWithSubPaths(hm);
}
public void testRequestsWithSubPathsInParentContext() throws Exception {
@Test
public void requestsWithSubPathsInParentContext() throws Exception {
BeanNameUrlHandlerMapping hm = new BeanNameUrlHandlerMapping();
hm.setDetectHandlersInAncestorContexts(true);
hm.setApplicationContext(new StaticApplicationContext(wac));
@@ -111,7 +118,8 @@ public class BeanNameUrlHandlerMappingTests extends TestCase {
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
}
public void testRequestsWithFullPaths() throws Exception {
@Test
public void requestsWithFullPaths() throws Exception {
BeanNameUrlHandlerMapping hm = new BeanNameUrlHandlerMapping();
hm.setAlwaysUseFullPath(true);
hm.setApplicationContext(wac);
@@ -143,7 +151,8 @@ public class BeanNameUrlHandlerMappingTests extends TestCase {
assertTrue("Handler is correct bean", hec != null && hec.getHandler() == bean);
}
public void testAsteriskMatches() throws Exception {
@Test
public void asteriskMatches() throws Exception {
HandlerMapping hm = (HandlerMapping) wac.getBean("handlerMapping");
Object bean = wac.getBean("godCtrl");
@@ -160,7 +169,8 @@ public class BeanNameUrlHandlerMappingTests extends TestCase {
assertTrue("Handler is correct bean", hec == null);
}
public void testOverlappingMappings() throws Exception {
@Test
public void overlappingMappings() throws Exception {
BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping");
Object anotherHandler = new Object();
hm.registerHandler("/mypath/testaross*", anotherHandler);
@@ -179,7 +189,8 @@ public class BeanNameUrlHandlerMappingTests extends TestCase {
assertTrue("Handler is correct bean", hec == null);
}
public void testDoubleMappings() throws ServletException {
@Test
public void doubleMappings() throws ServletException {
BeanNameUrlHandlerMapping hm = (BeanNameUrlHandlerMapping) wac.getBean("handlerMapping");
try {
hm.registerHandler("/mypath/welcome.html", new Object());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,7 +26,7 @@ import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@@ -34,15 +34,17 @@ import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class ControllerTests extends TestCase {
public class ControllerTests {
public void testParameterizableViewController() throws Exception {
@Test
public void parameterizableViewController() throws Exception {
String viewName = "viewName";
ParameterizableViewController pvc = new ParameterizableViewController();
pvc.setViewName(viewName);
@@ -53,19 +55,22 @@ public class ControllerTests extends TestCase {
assertTrue("getViewName matches", pvc.getViewName().equals(viewName));
}
public void testServletForwardingController() throws Exception {
@Test
public void servletForwardingController() throws Exception {
ServletForwardingController sfc = new ServletForwardingController();
sfc.setServletName("action");
doTestServletForwardingController(sfc, false);
}
public void testServletForwardingControllerWithInclude() throws Exception {
@Test
public void servletForwardingControllerWithInclude() throws Exception {
ServletForwardingController sfc = new ServletForwardingController();
sfc.setServletName("action");
doTestServletForwardingController(sfc, true);
}
public void testServletForwardingControllerWithBeanName() throws Exception {
@Test
public void servletForwardingControllerWithBeanName() throws Exception {
ServletForwardingController sfc = new ServletForwardingController();
sfc.setBeanName("action");
doTestServletForwardingController(sfc, false);
@@ -101,7 +106,8 @@ public class ControllerTests extends TestCase {
}
}
public void testServletWrappingController() throws Exception {
@Test
public void servletWrappingController() throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/somePath");
HttpServletResponse response = new MockHttpServletResponse();
@@ -128,7 +134,8 @@ public class ControllerTests extends TestCase {
assertTrue(TestServlet.destroyed);
}
public void testServletWrappingControllerWithBeanName() throws Exception {
@Test
public void servletWrappingControllerWithBeanName() throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/somePath");
HttpServletResponse response = new MockHttpServletResponse();

View File

@@ -16,7 +16,9 @@
package org.springframework.web.servlet.mvc;
import junit.framework.TestCase;
import org.junit.Test;
import static org.junit.Assert.*;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@@ -32,12 +34,13 @@ import org.springframework.web.servlet.ModelAndView;
* @author Rick Evans
* @since 14.09.2005
*/
public class UrlFilenameViewControllerTests extends TestCase {
public class UrlFilenameViewControllerTests {
private PathMatcher pathMatcher = new AntPathMatcher();
public void testWithPlainFilename() throws Exception {
@Test
public void withPlainFilename() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -46,7 +49,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testWithFilenamePlusExtension() throws Exception {
@Test
public void withFilenamePlusExtension() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -55,7 +59,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testWithFilenameAndMatrixVariables() throws Exception {
@Test
public void withFilenameAndMatrixVariables() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index;a=A;b=B");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -64,7 +69,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testWithPrefixAndSuffix() throws Exception {
@Test
public void withPrefixAndSuffix() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
ctrl.setPrefix("mypre_");
ctrl.setSuffix("_mysuf");
@@ -75,7 +81,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testWithPrefix() throws Exception {
@Test
public void withPrefix() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
ctrl.setPrefix("mypre_");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
@@ -85,7 +92,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testWithSuffix() throws Exception {
@Test
public void withSuffix() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
ctrl.setSuffix("_mysuf");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
@@ -95,7 +103,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testMultiLevel() throws Exception {
@Test
public void multiLevel() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/docs/cvs/commit.html");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -104,7 +113,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testMultiLevelWithMapping() throws Exception {
@Test
public void multiLevelWithMapping() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/docs/cvs/commit.html");
exposePathInMapping(request, "/docs/**");
@@ -114,7 +124,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testMultiLevelMappingWithFallback() throws Exception {
@Test
public void multiLevelMappingWithFallback() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/docs/cvs/commit.html");
exposePathInMapping(request, "/docs/cvs/commit.html");
@@ -124,7 +135,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testWithContextMapping() throws Exception {
@Test
public void withContextMapping() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/docs/cvs/commit.html");
request.setContextPath("/myapp");
@@ -134,14 +146,16 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testSettingPrefixToNullCausesEmptyStringToBeUsed() throws Exception {
@Test
public void settingPrefixToNullCausesEmptyStringToBeUsed() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
ctrl.setPrefix(null);
assertNotNull("When setPrefix(..) is called with a null argument, the empty string value must be used instead.", ctrl.getPrefix());
assertEquals("When setPrefix(..) is called with a null argument, the empty string value must be used instead.", "", ctrl.getPrefix());
}
public void testSettingSuffixToNullCausesEmptyStringToBeUsed() throws Exception {
@Test
public void settingSuffixToNullCausesEmptyStringToBeUsed() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
ctrl.setSuffix(null);
assertNotNull("When setSuffix(..) is called with a null argument, the empty string value must be used instead.", ctrl.getSuffix());
@@ -152,7 +166,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
* This is the expected behavior, and it now has a test to prove it.
* http://opensource.atlassian.com/projects/spring/browse/SPR-2789
*/
public void testNestedPathisUsedAsViewName_InBreakingChangeFromSpring12Line() throws Exception {
@Test
public void nestedPathisUsedAsViewName_InBreakingChangeFromSpring12Line() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/products/view.html");
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -161,7 +176,8 @@ public class UrlFilenameViewControllerTests extends TestCase {
assertTrue(mv.getModel().isEmpty());
}
public void testWithFlashAttributes() throws Exception {
@Test
public void withFlashAttributes() throws Exception {
UrlFilenameViewController ctrl = new UrlFilenameViewController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new ModelMap("name", "value"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,9 @@
package org.springframework.web.servlet.mvc.annotation;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
@@ -24,29 +26,24 @@ import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class ControllerClassNameHandlerMappingTests extends TestCase {
public class ControllerClassNameHandlerMappingTests {
public static final String LOCATION = "/org/springframework/web/servlet/mvc/annotation/class-mapping.xml";
private static final String LOCATION = "/org/springframework/web/servlet/mvc/annotation/class-mapping.xml";
private XmlWebApplicationContext wac;
private final XmlWebApplicationContext wac = new XmlWebApplicationContext();
private HandlerMapping hm;
private HandlerMapping hm, hm2, hm3, hm4;
private HandlerMapping hm2;
private HandlerMapping hm3;
private HandlerMapping hm4;
@Override
@Before
public void setUp() throws Exception {
MockServletContext sc = new MockServletContext("");
this.wac = new XmlWebApplicationContext();
this.wac.setServletContext(sc);
this.wac.setConfigLocations(new String[] {LOCATION});
this.wac.setServletContext(new MockServletContext(""));
this.wac.setConfigLocations(LOCATION);
this.wac.refresh();
this.hm = (HandlerMapping) this.wac.getBean("mapping");
this.hm2 = (HandlerMapping) this.wac.getBean("mapping2");
@@ -54,7 +51,13 @@ public class ControllerClassNameHandlerMappingTests extends TestCase {
this.hm4 = (HandlerMapping) this.wac.getBean("mapping4");
}
public void testIndexUri() throws Exception {
@After
public void closeWac() {
this.wac.close();
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
@@ -64,7 +67,8 @@ public class ControllerClassNameHandlerMappingTests extends TestCase {
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
public void testMapSimpleUri() throws Exception {
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
@@ -74,15 +78,17 @@ public class ControllerClassNameHandlerMappingTests extends TestCase {
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithContextPath() throws Exception {
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buyform");
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buyform");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
@@ -91,28 +97,32 @@ public class ControllerClassNameHandlerMappingTests extends TestCase {
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
public void testWithBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/welcome");
@Test
public void withBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/welcome");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithBasePackageAndCaseSensitive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/buyForm");
@Test
public void withBasePackageAndCaseSensitive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/annotation/buyForm");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
public void testWithFullBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
@Test
public void withFullBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
HandlerExecutionChain chain = this.hm3.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithRootAsBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/org/springframework/web/servlet/mvc/annotation/welcome");
@Test
public void withRootAsBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/org/springframework/web/servlet/mvc/annotation/welcome");
HandlerExecutionChain chain = this.hm4.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,9 @@
package org.springframework.web.servlet.mvc.mapping;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
@@ -24,56 +26,67 @@ import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class ControllerBeanNameHandlerMappingTests extends TestCase {
public class ControllerBeanNameHandlerMappingTests {
public static final String LOCATION = "/org/springframework/web/servlet/mvc/mapping/name-mapping.xml";
private static final String LOCATION = "/org/springframework/web/servlet/mvc/mapping/name-mapping.xml";
private XmlWebApplicationContext wac;
private final XmlWebApplicationContext wac = new XmlWebApplicationContext();
private HandlerMapping hm;
@Override
@Before
public void setUp() throws Exception {
MockServletContext sc = new MockServletContext("");
this.wac = new XmlWebApplicationContext();
this.wac.setServletContext(sc);
this.wac.setConfigLocations(new String[] {LOCATION});
this.wac.setServletContext(new MockServletContext(""));
this.wac.setConfigLocations(LOCATION);
this.wac.refresh();
this.hm = (HandlerMapping) this.wac.getBean("mapping");
this.hm = this.wac.getBean(HandlerMapping.class);
}
public void testIndexUri() throws Exception {
@After
public void closeWac() {
this.wac.close();
}
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
public void testMapSimpleUri() throws Exception {
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithContextPath() throws Exception {
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithMultiActionControllerMapping() throws Exception {
@Test
public void withMultiActionControllerMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
}
public void testWithoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buy");
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buy");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,8 @@
package org.springframework.web.servlet.mvc.mapping;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
@@ -24,11 +25,13 @@ import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class ControllerClassNameHandlerMappingTests extends TestCase {
public class ControllerClassNameHandlerMappingTests {
public static final String LOCATION = "/org/springframework/web/servlet/mvc/mapping/class-mapping.xml";
@@ -42,7 +45,8 @@ public class ControllerClassNameHandlerMappingTests extends TestCase {
private HandlerMapping hm4;
@Override
@Before
public void setUp() throws Exception {
MockServletContext sc = new MockServletContext("");
this.wac = new XmlWebApplicationContext();
@@ -55,26 +59,30 @@ public class ControllerClassNameHandlerMappingTests extends TestCase {
this.hm4 = (HandlerMapping) this.wac.getBean("mapping4");
}
public void testIndexUri() throws Exception {
@Test
public void indexUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("index"), chain.getHandler());
}
public void testMapSimpleUri() throws Exception {
@Test
public void mapSimpleUri() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithContextPath() throws Exception {
@Test
public void withContextPath() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
request.setContextPath("/myapp");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithMultiActionControllerMapping() throws Exception {
@Test
public void withMultiActionControllerMapping() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/user");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("admin"), chain.getHandler());
@@ -84,31 +92,36 @@ public class ControllerClassNameHandlerMappingTests extends TestCase {
assertEquals(this.wac.getBean("admin"), chain.getHandler());
}
public void testWithoutControllerSuffix() throws Exception {
@Test
public void withoutControllerSuffix() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/buyform");
HandlerExecutionChain chain = this.hm.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
public void testWithBasePackage() throws Exception {
@Test
public void withBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/mapping/welcome");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithBasePackageAndCaseSensitive() throws Exception {
@Test
public void withBasePackageAndCaseSensitive() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/mvc/mapping/buyForm");
HandlerExecutionChain chain = this.hm2.getHandler(request);
assertEquals(this.wac.getBean("buy"), chain.getHandler());
}
public void testWithFullBasePackage() throws Exception {
@Test
public void withFullBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/welcome");
HandlerExecutionChain chain = this.hm3.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());
}
public void testWithRootAsBasePackage() throws Exception {
@Test
public void withRootAsBasePackage() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myapp/org/springframework/web/servlet/mvc/mapping/welcome");
HandlerExecutionChain chain = this.hm4.getHandler(request);
assertEquals(this.wac.getBean("welcome"), chain.getHandler());

View File

@@ -29,6 +29,7 @@ import org.eclipse.jetty.server.NetworkConnector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
@@ -66,8 +67,8 @@ import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import static org.junit.Assert.assertEquals;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
import static org.junit.Assert.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;
/**
* Test access to parts of a multipart request with {@link RequestPart}.

View File

@@ -16,6 +16,8 @@
package org.springframework.web.servlet.mvc.multiaction;
import org.junit.Test;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
@@ -26,7 +28,7 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import junit.framework.TestCase;
import static org.junit.Assert.*;
import org.springframework.beans.FatalBeanException;
import org.springframework.context.ApplicationContextException;
@@ -45,9 +47,10 @@ import org.springframework.web.servlet.ModelAndView;
* @author Rob Harrop
* @author Sam Brannen
*/
public class MultiActionControllerTests extends TestCase {
public class MultiActionControllerTests {
public void testDefaultInternalPathMethodNameResolver() throws Exception {
@Test
public void defaultInternalPathMethodNameResolver() throws Exception {
doDefaultTestInternalPathMethodNameResolver("/foo.html", "foo");
doDefaultTestInternalPathMethodNameResolver("/foo/bar.html", "bar");
doDefaultTestInternalPathMethodNameResolver("/bugal.xyz", "bugal");
@@ -62,7 +65,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals("Wrong method name resolved", expected, actual);
}
public void testCustomizedInternalPathMethodNameResolver() throws Exception {
@Test
public void customizedInternalPathMethodNameResolver() throws Exception {
doTestCustomizedInternalPathMethodNameResolver("/foo.html", "my", null, "myfoo");
doTestCustomizedInternalPathMethodNameResolver("/foo/bar.html", null, "Handler", "barHandler");
doTestCustomizedInternalPathMethodNameResolver("/Bugal.xyz", "your", "Method", "yourBugalMethod");
@@ -85,7 +89,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals("Wrong method name resolved", expected, actual);
}
public void testParameterMethodNameResolver() throws NoSuchRequestHandlingMethodException {
@Test
public void parameterMethodNameResolver() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver mnr = new ParameterMethodNameResolver();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.html");
@@ -119,7 +124,8 @@ public class MultiActionControllerTests extends TestCase {
}
}
public void testParameterMethodNameResolverWithCustomParamName() throws NoSuchRequestHandlingMethodException {
@Test
public void parameterMethodNameResolverWithCustomParamName() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver mnr = new ParameterMethodNameResolver();
mnr.setParamName("myparam");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.html");
@@ -127,7 +133,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals("bar", mnr.getHandlerMethodName(request));
}
public void testParameterMethodNameResolverWithParamNames() throws NoSuchRequestHandlingMethodException {
@Test
public void parameterMethodNameResolverWithParamNames() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver resolver = new ParameterMethodNameResolver();
resolver.setDefaultMethodName("default");
resolver.setMethodParamNames(new String[] { "hello", "spring", "colin" });
@@ -181,7 +188,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals("goodbye", resolver.getHandlerMethodName(request));
}
public void testParameterMethodNameResolverWithDefaultMethodName() throws NoSuchRequestHandlingMethodException {
@Test
public void parameterMethodNameResolverWithDefaultMethodName() throws NoSuchRequestHandlingMethodException {
ParameterMethodNameResolver mnr = new ParameterMethodNameResolver();
mnr.setDefaultMethodName("foo");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.html");
@@ -191,7 +199,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals("foo", mnr.getHandlerMethodName(request));
}
public void testInvokesCorrectMethod() throws Exception {
@Test
public void invokesCorrectMethod() throws Exception {
TestMaController mc = new TestMaController();
HttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
HttpServletResponse response = new MockHttpServletResponse();
@@ -215,7 +224,8 @@ public class MultiActionControllerTests extends TestCase {
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
}
public void testPathMatching() throws Exception {
@Test
public void pathMatching() throws Exception {
TestMaController mc = new TestMaController();
HttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
HttpServletResponse response = new MockHttpServletResponse();
@@ -243,7 +253,8 @@ public class MultiActionControllerTests extends TestCase {
assertTrue("No method invoked", mc.getInvokedMethods() == 0);
}
public void testInvokesCorrectMethodOnDelegate() throws Exception {
@Test
public void invokesCorrectMethodOnDelegate() throws Exception {
MultiActionController mac = new MultiActionController();
TestDelegate d = new TestDelegate();
mac.setDelegate(d);
@@ -254,7 +265,8 @@ public class MultiActionControllerTests extends TestCase {
assertTrue("Delegate was invoked", d.invoked);
}
public void testInvokesCorrectMethodWithSession() throws Exception {
@Test
public void invokesCorrectMethodWithSession() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/inSession.html");
request.setSession(new MockHttpSession(null));
@@ -275,7 +287,8 @@ public class MultiActionControllerTests extends TestCase {
}
}
public void testInvokesCommandMethodNoSession() throws Exception {
@Test
public void invokesCommandMethodNoSession() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/commandNoSession.html");
request.addParameter("name", "rod");
@@ -287,7 +300,8 @@ public class MultiActionControllerTests extends TestCase {
assertTrue("Only one method invoked", mc.getInvokedMethods() == 1);
}
public void testInvokesCommandMethodWithSession() throws Exception {
@Test
public void invokesCommandMethodWithSession() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/commandInSession.html");
request.addParameter("name", "rod");
@@ -311,7 +325,8 @@ public class MultiActionControllerTests extends TestCase {
}
}
public void testSessionRequiredCatchable() throws Exception {
@Test
public void sessionRequiredCatchable() throws Exception {
HttpServletRequest request = new MockHttpServletRequest("GET", "/testSession.html");
HttpServletResponse response = new MockHttpServletResponse();
TestMaController contr = new TestSessionRequiredController();
@@ -346,7 +361,8 @@ public class MultiActionControllerTests extends TestCase {
testExceptionNoHandler(new TestMaController(), t);
}
public void testExceptionNoHandler() throws Exception {
@Test
public void exceptionNoHandler() throws Exception {
testExceptionNoHandler(new Exception());
// must go straight through
@@ -358,14 +374,16 @@ public class MultiActionControllerTests extends TestCase {
testExceptionNoHandler(new Error());
}
public void testLastModifiedDefault() throws Exception {
@Test
public void lastModifiedDefault() throws Exception {
TestMaController mc = new TestMaController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
long lastMod = mc.getLastModified(request);
assertTrue("default last modified is -1", lastMod == -1L);
}
public void testLastModifiedWithMethod() throws Exception {
@Test
public void lastModifiedWithMethod() throws Exception {
LastModController mc = new LastModController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
long lastMod = mc.getLastModified(request);
@@ -379,7 +397,8 @@ public class MultiActionControllerTests extends TestCase {
return mc.handleRequest(request, response);
}
public void testHandlerCaughtException() throws Exception {
@Test
public void handlerCaughtException() throws Exception {
TestMaController mc = new TestExceptionHandler();
ModelAndView mv = testHandlerCaughtException(mc, new Exception());
assertNotNull("ModelAndView must not be null", mv);
@@ -416,7 +435,8 @@ public class MultiActionControllerTests extends TestCase {
testExceptionNoHandler(mc, new Exception());
}
public void testHandlerReturnsMap() throws Exception {
@Test
public void handlerReturnsMap() throws Exception {
Map model = new HashMap();
model.put("message", "Hello World!");
@@ -431,7 +451,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals(model, mav.getModel());
}
public void testExceptionHandlerReturnsMap() throws Exception {
@Test
public void exceptionHandlerReturnsMap() throws Exception {
Map model = new HashMap();
MultiActionController mac = new ModelOnlyMultiActionController(model);
@@ -445,7 +466,8 @@ public class MultiActionControllerTests extends TestCase {
assertTrue(model.containsKey("exception"));
}
public void testCannotCallExceptionHandlerDirectly() throws Exception {
@Test
public void cannotCallExceptionHandlerDirectly() throws Exception {
Map model = new HashMap();
MultiActionController mac = new ModelOnlyMultiActionController(model);
@@ -456,7 +478,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
}
public void testHandlerReturnsVoid() throws Exception {
@Test
public void handlerReturnsVoid() throws Exception {
MultiActionController mac = new VoidMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
@@ -466,7 +489,8 @@ public class MultiActionControllerTests extends TestCase {
assertNull("ModelAndView must be null", mav);
}
public void testExceptionHandlerReturnsVoid() throws Exception {
@Test
public void exceptionHandlerReturnsVoid() throws Exception {
MultiActionController mac = new VoidMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
@@ -477,7 +501,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals("exception", response.getContentAsString());
}
public void testHandlerReturnsString() throws Exception {
@Test
public void handlerReturnsString() throws Exception {
MultiActionController mac = new StringMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/welcome.html");
@@ -489,7 +514,8 @@ public class MultiActionControllerTests extends TestCase {
assertEquals("Verifying view name", "welcomeString", mav.getViewName());
}
public void testExceptionHandlerReturnsString() throws Exception {
@Test
public void exceptionHandlerReturnsString() throws Exception {
MultiActionController mac = new StringMultiActionController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.springframework.web.servlet.tags;
import junit.framework.TestCase;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockPageContext;
@@ -37,7 +35,7 @@ import org.springframework.web.servlet.theme.FixedThemeResolver;
* @author Juergen Hoeller
* @author Sam Brannen
*/
public abstract class AbstractTagTests extends TestCase {
public abstract class AbstractTagTests {
protected MockPageContext createPageContext() {
MockServletContext sc = new MockServletContext();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,11 +21,16 @@ import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockBodyContent;
import org.springframework.mock.web.test.MockHttpServletResponse;
import static org.junit.Assert.*;
/**
* Unit tests for ArgumentTag
* Unit tests for {@link ArgumentTag}
*
* @author Nicholas Williams
*/
@@ -35,8 +40,8 @@ public class ArgumentTagTests extends AbstractTagTests {
private MockArgumentSupportTag parent;
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
PageContext context = createPageContext();
parent = new MockArgumentSupportTag();
tag = new ArgumentTag();
@@ -44,7 +49,8 @@ public class ArgumentTagTests extends AbstractTagTests {
tag.setParent(parent);
}
public void testArgumentWithStringValue() throws JspException {
@Test
public void argumentWithStringValue() throws JspException {
tag.setValue("value1");
int action = tag.doEndTag();
@@ -53,14 +59,16 @@ public class ArgumentTagTests extends AbstractTagTests {
assertEquals("value1", parent.getArgument());
}
public void testArgumentWithImplicitNullValue() throws JspException {
@Test
public void argumentWithImplicitNullValue() throws JspException {
int action = tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, action);
assertNull(parent.getArgument());
}
public void testArgumentWithExplicitNullValue() throws JspException {
@Test
public void argumentWithExplicitNullValue() throws JspException {
tag.setValue(null);
int action = tag.doEndTag();
@@ -69,7 +77,8 @@ public class ArgumentTagTests extends AbstractTagTests {
assertNull(parent.getArgument());
}
public void testArgumentWithBodyValue() throws JspException {
@Test
public void argumentWithBodyValue() throws JspException {
tag.setBodyContent(new MockBodyContent("value2",
new MockHttpServletResponse()));
@@ -79,7 +88,8 @@ public class ArgumentTagTests extends AbstractTagTests {
assertEquals("value2", parent.getArgument());
}
public void testArgumentWithValueThenReleaseThenBodyValue() throws JspException {
@Test
public void argumentWithValueThenReleaseThenBodyValue() throws JspException {
tag.setValue("value3");
int action = tag.doEndTag();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,8 @@ import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.tests.sample.beans.IndexedTestBean;
import org.springframework.tests.sample.beans.NestedTestBean;
@@ -39,6 +41,8 @@ import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.form.FormTag;
import org.springframework.web.servlet.tags.form.TagWriter;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Alef Arendsen
@@ -46,7 +50,8 @@ import org.springframework.web.servlet.tags.form.TagWriter;
*/
public class BindTagTests extends AbstractTagTests {
public void testBindTagWithoutErrors() throws JspException {
@Test
public void bindTagWithoutErrors() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);
@@ -67,7 +72,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessagesAsString", "".equals(status.getErrorMessagesAsString(",")));
}
public void testBindTagWithGlobalErrors() throws JspException {
@Test
public void bindTagWithGlobalErrors() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
errors.reject("code1", "message1");
@@ -106,7 +112,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(",")));
}
public void testBindTagWithGlobalErrorsAndNoDefaultMessage() throws JspException {
@Test
public void bindTagWithGlobalErrorsAndNoDefaultMessage() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
errors.reject("code1");
@@ -139,7 +146,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorCode", "code1".equals(status.getErrorCode()));
}
public void testBindTagWithGlobalErrorsAndDefaultMessageOnly() throws JspException {
@Test
public void bindTagWithGlobalErrorsAndDefaultMessageOnly() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
errors.reject(null, "message1");
@@ -174,7 +182,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(",")));
}
public void testBindStatusGetErrorMessagesAsString() throws JspException {
@Test
public void bindStatusGetErrorMessagesAsString() throws JspException {
// one error (should not include delimiter)
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
@@ -214,7 +223,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("Error messages String should be ''", status.getErrorMessagesAsString(","), "");
}
public void testBindTagWithFieldErrors() throws JspException {
@Test
public void bindTagWithFieldErrors() throws JspException {
PageContext pc = createPageContext();
TestBean tb = new TestBean();
tb.setName("name1");
@@ -284,7 +294,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[2]));
}
public void testBindTagWithFieldErrorsAndNoDefaultMessage() throws JspException {
@Test
public void bindTagWithFieldErrorsAndNoDefaultMessage() throws JspException {
PageContext pc = createPageContext();
TestBean tb = new TestBean();
tb.setName("name1");
@@ -340,7 +351,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorCode", "code2".equals(status.getErrorCodes()[2]));
}
public void testBindTagWithFieldErrorsAndDefaultMessageOnly() throws JspException {
@Test
public void bindTagWithFieldErrorsAndDefaultMessageOnly() throws JspException {
PageContext pc = createPageContext();
TestBean tb = new TestBean();
tb.setName("name1");
@@ -399,7 +411,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[2]));
}
public void testBindTagWithNestedFieldErrors() throws JspException {
@Test
public void bindTagWithNestedFieldErrors() throws JspException {
PageContext pc = createPageContext();
TestBean tb = new TestBean();
tb.setName("name1");
@@ -426,7 +439,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessagesAsString", "message1".equals(status.getErrorMessagesAsString(" - ")));
}
public void testPropertyExposing() throws JspException {
@Test
public void propertyExposing() throws JspException {
PageContext pc = createPageContext();
TestBean tb = new TestBean();
tb.setName("name1");
@@ -450,7 +464,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("name", tag.getProperty());
}
public void testBindTagWithIndexedProperties() throws JspException {
@Test
public void bindTagWithIndexedProperties() throws JspException {
PageContext pc = createPageContext();
IndexedTestBean tb = new IndexedTestBean();
Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult();
@@ -476,7 +491,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1]));
}
public void testBindTagWithMappedProperties() throws JspException {
@Test
public void bindTagWithMappedProperties() throws JspException {
PageContext pc = createPageContext();
IndexedTestBean tb = new IndexedTestBean();
Errors errors = new ServletRequestDataBinder(tb, "tb").getBindingResult();
@@ -502,7 +518,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct errorMessage", "message2".equals(status.getErrorMessages()[1]));
}
public void testBindTagWithIndexedPropertiesAndCustomEditor() throws JspException {
@Test
public void bindTagWithIndexedPropertiesAndCustomEditor() throws JspException {
PageContext pc = createPageContext();
IndexedTestBean tb = new IndexedTestBean();
DataBinder binder = new ServletRequestDataBinder(tb, "tb");
@@ -529,7 +546,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Correct value", "something".equals(status.getValue()));
}
public void testBindTagWithToStringAndHtmlEscaping() throws JspException {
@Test
public void bindTagWithToStringAndHtmlEscaping() throws JspException {
PageContext pc = createPageContext();
BindTag tag = new BindTag();
tag.setPageContext(pc);
@@ -546,7 +564,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue(status.getDisplayValue().indexOf("juergen&amp;eva") != -1);
}
public void testBindTagWithSetValueAndHtmlEscaping() throws JspException {
@Test
public void bindTagWithSetValueAndHtmlEscaping() throws JspException {
PageContext pc = createPageContext();
BindTag tag = new BindTag();
tag.setPageContext(pc);
@@ -559,7 +578,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue(status.getValue() instanceof Set);
}
public void testBindTagWithFieldButWithoutErrorsInstance() throws JspException {
@Test
public void bindTagWithFieldButWithoutErrorsInstance() throws JspException {
PageContext pc = createPageContext();
BindTag tag = new BindTag();
tag.setPageContext(pc);
@@ -571,7 +591,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("juergen&eva", status.getValue());
}
public void testBindTagWithFieldButWithoutErrorsInstanceAndHtmlEscaping() throws JspException {
@Test
public void bindTagWithFieldButWithoutErrorsInstanceAndHtmlEscaping() throws JspException {
PageContext pc = createPageContext();
BindTag tag = new BindTag();
tag.setPageContext(pc);
@@ -584,7 +605,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("juergen&amp;eva", status.getValue());
}
public void testBindTagWithBeanButWithoutErrorsInstance() throws JspException {
@Test
public void bindTagWithBeanButWithoutErrorsInstance() throws JspException {
PageContext pc = createPageContext();
BindTag tag = new BindTag();
tag.setPageContext(pc);
@@ -596,7 +618,8 @@ public class BindTagTests extends AbstractTagTests {
assertNull(status.getValue());
}
public void testBindTagWithoutBean() throws JspException {
@Test
public void bindTagWithoutBean() throws JspException {
PageContext pc = createPageContext();
BindTag tag = new BindTag();
tag.setPageContext(pc);
@@ -611,7 +634,8 @@ public class BindTagTests extends AbstractTagTests {
}
public void testBindErrorsTagWithoutErrors() throws JspException {
@Test
public void bindErrorsTagWithoutErrors() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);
@@ -622,7 +646,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Doesn't have errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME) == null);
}
public void testBindErrorsTagWithErrors() throws JspException {
@Test
public void bindErrorsTagWithErrors() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
errors.reject("test", null, "test");
@@ -634,7 +659,8 @@ public class BindTagTests extends AbstractTagTests {
assertTrue("Has errors variable", pc.getAttribute(BindErrorsTag.ERRORS_VARIABLE_NAME, PageContext.REQUEST_SCOPE) == errors);
}
public void testBindErrorsTagWithoutBean() throws JspException {
@Test
public void bindErrorsTagWithoutBean() throws JspException {
PageContext pc = createPageContext();
BindErrorsTag tag = new BindErrorsTag();
tag.setPageContext(pc);
@@ -643,7 +669,8 @@ public class BindTagTests extends AbstractTagTests {
}
public void testNestedPathDoEndTag() throws JspException {
@Test
public void nestedPathDoEndTag() throws JspException {
PageContext pc = createPageContext();
NestedPathTag tag = new NestedPathTag();
tag.setPath("foo");
@@ -654,7 +681,8 @@ public class BindTagTests extends AbstractTagTests {
assertNull(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
}
public void testNestedPathDoEndTagWithNesting() throws JspException {
@Test
public void nestedPathDoEndTagWithNesting() throws JspException {
PageContext pc = createPageContext();
NestedPathTag tag = new NestedPathTag();
tag.setPath("foo");
@@ -673,7 +701,8 @@ public class BindTagTests extends AbstractTagTests {
assertNull(pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
}
public void testNestedPathDoStartTagInternal() throws JspException {
@Test
public void nestedPathDoStartTagInternal() throws JspException {
PageContext pc = createPageContext();
NestedPathTag tag = new NestedPathTag();
tag.setPath("foo");
@@ -684,7 +713,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("foo.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
}
public void testNestedPathDoStartTagInternalWithNesting() throws JspException {
@Test
public void nestedPathDoStartTagInternalWithNesting() throws JspException {
PageContext pc = createPageContext();
NestedPathTag tag = new NestedPathTag();
tag.setPath("foo");
@@ -716,7 +746,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("foo.bar.boo2.", pc.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
}
public void testNestedPathWithBindTag() throws JspException {
@Test
public void nestedPathWithBindTag() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb").getBindingResult();
pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb", errors);
@@ -757,7 +788,8 @@ public class BindTagTests extends AbstractTagTests {
nestedPathTag.doEndTag();
}
public void testNestedPathWithBindTagWithIgnoreNestedPath() throws JspException {
@Test
public void nestedPathWithBindTagWithIgnoreNestedPath() throws JspException {
PageContext pc = createPageContext();
Errors errors = new ServletRequestDataBinder(new TestBean(), "tb2").getBindingResult();
pc.getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "tb2", errors);
@@ -778,7 +810,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("tb2.name", status.getPath());
}
public void testTransformTagCorrectBehavior() throws JspException {
@Test
public void transformTagCorrectBehavior() throws JspException {
// first set up the pagecontext and the bean
PageContext pc = createPageContext();
TestBean tb = new TestBean();
@@ -822,7 +855,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("name", pc.getAttribute("theString"));
}
public void testTransformTagWithHtmlEscape() throws JspException {
@Test
public void transformTagWithHtmlEscape() throws JspException {
// first set up the PageContext and the bean
PageContext pc = createPageContext();
TestBean tb = new TestBean();
@@ -850,7 +884,8 @@ public class BindTagTests extends AbstractTagTests {
assertEquals("na&lt;me", pc.getAttribute("theString"));
}
public void testTransformTagOutsideBindTag() throws JspException {
@Test
public void transformTagOutsideBindTag() throws JspException {
// first set up the pagecontext and the bean
PageContext pc = createPageContext();
TestBean tb = new TestBean();
@@ -890,7 +925,8 @@ public class BindTagTests extends AbstractTagTests {
}
}
public void testTransformTagNonExistingValue() throws JspException {
@Test
public void transformTagNonExistingValue() throws JspException {
// first set up the pagecontext and the bean
PageContext pc = createPageContext();
TestBean tb = new TestBean();
@@ -916,7 +952,8 @@ public class BindTagTests extends AbstractTagTests {
assertNull(pc.getAttribute("theString2"));
}
public void testTransformTagWithSettingOfScope() throws JspException {
@Test
public void transformTagWithSettingOfScope() throws JspException {
// first set up the pagecontext and the bean
PageContext pc = createPageContext();
TestBean tb = new TestBean();
@@ -970,7 +1007,8 @@ public class BindTagTests extends AbstractTagTests {
* SPR-4022
*/
@SuppressWarnings("serial")
public void testNestingInFormTag() throws JspException {
@Test
public void nestingInFormTag() throws JspException {
PageContext pc = createPageContext();
TestBean tb = new TestBean();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

View File

@@ -22,6 +22,9 @@ import java.util.Locale;
import java.util.Map;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.env.MapPropertySource;
import org.springframework.format.annotation.NumberFormat;
@@ -32,6 +35,8 @@ import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockPageContext;
import org.springframework.web.servlet.DispatcherServlet;
import static org.junit.Assert.*;
/**
* @author Keith Donald
*/
@@ -41,8 +46,8 @@ public class EvalTagTests extends AbstractTagTests {
private MockPageContext context;
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
context = createPageContext();
FormattingConversionServiceFactoryBean factory = new FormattingConversionServiceFactoryBean();
factory.afterPropertiesSet();
@@ -52,7 +57,8 @@ public class EvalTagTests extends AbstractTagTests {
tag.setPageContext(context);
}
public void testPrintScopedAttributeResult() throws Exception {
@Test
public void printScopedAttributeResult() throws Exception {
tag.setExpression("bean.method()");
int action = tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, action);
@@ -61,7 +67,8 @@ public class EvalTagTests extends AbstractTagTests {
assertEquals("foo", ((MockHttpServletResponse) context.getResponse()).getContentAsString());
}
public void testPrintNullAsEmptyString() throws Exception {
@Test
public void printNullAsEmptyString() throws Exception {
tag.setExpression("bean.null");
int action = tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, action);
@@ -70,7 +77,8 @@ public class EvalTagTests extends AbstractTagTests {
assertEquals("", ((MockHttpServletResponse) context.getResponse()).getContentAsString());
}
public void testPrintFormattedScopedAttributeResult() throws Exception {
@Test
public void printFormattedScopedAttributeResult() throws Exception {
PercentStyleFormatter formatter = new PercentStyleFormatter();
tag.setExpression("bean.formattable");
int action = tag.doStartTag();
@@ -81,7 +89,8 @@ public class EvalTagTests extends AbstractTagTests {
((MockHttpServletResponse) context.getResponse()).getContentAsString());
}
public void testPrintHtmlEscapedAttributeResult() throws Exception {
@Test
public void printHtmlEscapedAttributeResult() throws Exception {
tag.setExpression("bean.html()");
tag.setHtmlEscape(true);
int action = tag.doStartTag();
@@ -91,7 +100,8 @@ public class EvalTagTests extends AbstractTagTests {
assertEquals("&lt;p&gt;", ((MockHttpServletResponse) context.getResponse()).getContentAsString());
}
public void testPrintJavaScriptEscapedAttributeResult() throws Exception {
@Test
public void printJavaScriptEscapedAttributeResult() throws Exception {
tag.setExpression("bean.js()");
tag.setJavaScriptEscape(true);
int action = tag.doStartTag();
@@ -102,7 +112,8 @@ public class EvalTagTests extends AbstractTagTests {
((MockHttpServletResponse)context.getResponse()).getContentAsString());
}
public void testSetFormattedScopedAttributeResult() throws Exception {
@Test
public void setFormattedScopedAttributeResult() throws Exception {
tag.setExpression("bean.formattable");
tag.setVar("foo");
int action = tag.doStartTag();
@@ -113,7 +124,8 @@ public class EvalTagTests extends AbstractTagTests {
}
// SPR-6923
public void testNestedPropertyWithAttributeName() throws Exception {
@Test
public void nestedPropertyWithAttributeName() throws Exception {
tag.setExpression("bean.bean");
tag.setVar("foo");
int action = tag.doStartTag();
@@ -123,7 +135,8 @@ public class EvalTagTests extends AbstractTagTests {
assertEquals("not the bean object", context.getAttribute("foo"));
}
public void testAccessUsingBeanSyntax() throws Exception {
@Test
public void accessUsingBeanSyntax() throws Exception {
GenericApplicationContext wac = (GenericApplicationContext)
context.getRequest().getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
wac.getDefaultListableBeanFactory().registerSingleton("bean2", context.getRequest().getAttribute("bean"));
@@ -136,7 +149,8 @@ public class EvalTagTests extends AbstractTagTests {
assertEquals("not the bean object", context.getAttribute("foo"));
}
public void testEnvironmentAccess() throws Exception {
@Test
public void environmentAccess() throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("key.foo", "value.foo");
GenericApplicationContext wac = (GenericApplicationContext)
@@ -151,7 +165,8 @@ public class EvalTagTests extends AbstractTagTests {
assertEquals("value.foo", ((MockHttpServletResponse) context.getResponse()).getContentAsString());
}
public void testMapAccess() throws Exception {
@Test
public void mapAccess() throws Exception {
tag.setExpression("bean.map.key");
int action = tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, action);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,17 +21,22 @@ import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.util.WebUtils;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Alef Arendsen
*/
@SuppressWarnings("serial")
public class HtmlEscapeTagTests extends AbstractTagTests {
@SuppressWarnings("serial")
public void testHtmlEscapeTag() throws JspException {
@Test
public void htmlEscapeTag() throws JspException {
PageContext pc = createPageContext();
HtmlEscapeTag tag = new HtmlEscapeTag();
tag.setPageContext(pc);
@@ -74,7 +79,8 @@ public class HtmlEscapeTagTests extends AbstractTagTests {
assertTrue("Correctly applied", !testTag.isHtmlEscape());
}
public void testHtmlEscapeTagWithContextParamTrue() throws JspException {
@Test
public void htmlEscapeTagWithContextParamTrue() throws JspException {
PageContext pc = createPageContext();
MockServletContext sc = (MockServletContext) pc.getServletContext();
sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "true");
@@ -92,7 +98,8 @@ public class HtmlEscapeTagTests extends AbstractTagTests {
assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
public void testHtmlEscapeTagWithContextParamFalse() throws JspException {
@Test
public void htmlEscapeTagWithContextParamFalse() throws JspException {
PageContext pc = createPageContext();
MockServletContext sc = (MockServletContext) pc.getServletContext();
HtmlEscapeTag tag = new HtmlEscapeTag();
@@ -109,8 +116,8 @@ public class HtmlEscapeTagTests extends AbstractTagTests {
assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
@SuppressWarnings("serial")
public void testEscapeBody() throws JspException {
@Test
public void escapeBody() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
@@ -129,8 +136,8 @@ public class HtmlEscapeTagTests extends AbstractTagTests {
assertEquals("test text", result.toString());
}
@SuppressWarnings("serial")
public void testEscapeBodyWithHtmlEscape() throws JspException {
@Test
public void escapeBodyWithHtmlEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
@@ -150,8 +157,8 @@ public class HtmlEscapeTagTests extends AbstractTagTests {
assertEquals("test &amp; text", result.toString());
}
@SuppressWarnings("serial")
public void testEscapeBodyWithJavaScriptEscape() throws JspException {
@Test
public void escapeBodyWithJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {
@@ -171,8 +178,8 @@ public class HtmlEscapeTagTests extends AbstractTagTests {
assertEquals("Correct content", "\\' test & text \\\\", result.toString());
}
@SuppressWarnings("serial")
public void testEscapeBodyWithHtmlEscapeAndJavaScriptEscape() throws JspException {
@Test
public void escapeBodyWithHtmlEscapeAndJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer result = new StringBuffer();
EscapeBodyTag tag = new EscapeBodyTag() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,8 @@ import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.context.ConfigurableWebApplicationContext;
@@ -31,6 +33,8 @@ import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.WebUtils;
import static org.junit.Assert.*;
/**
* Tests for {@link MessageTag}.
*
@@ -38,10 +42,11 @@ import org.springframework.web.util.WebUtils;
* @author Alef Arendsen
* @author Nicholas Williams
*/
@SuppressWarnings("serial")
public class MessageTagTests extends AbstractTagTests {
@SuppressWarnings("serial")
public void testMessageTagWithMessageSourceResolvable() throws JspException {
@Test
public void messageTagWithMessageSourceResolvable() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -57,8 +62,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test message", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCode() throws JspException {
@Test
public void messageTagWithCode() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -74,8 +79,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test message", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithNullCode() throws JspException {
@Test
public void messageTagWithNullCode() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -91,8 +96,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "null", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndArgument() throws JspException {
@Test
public void messageTagWithCodeAndArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -109,8 +114,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test arg1 message {1}", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndArguments() throws JspException {
@Test
public void messageTagWithCodeAndArguments() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -127,8 +132,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test arg1 message arg2", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndStringArgumentWithCustomSeparator() throws JspException {
@Test
public void messageTagWithCodeAndStringArgumentWithCustomSeparator() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -146,8 +151,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test arg1,1 message arg2,2", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndArrayArgument() throws JspException {
@Test
public void messageTagWithCodeAndArrayArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -164,8 +169,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test arg1 message 5", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndObjectArgument() throws JspException {
@Test
public void messageTagWithCodeAndObjectArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -182,8 +187,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test 5 message {1}", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndArgumentAndNestedArgument() throws JspException {
@Test
public void messageTagWithCodeAndArgumentAndNestedArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -201,8 +206,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test 5 message 7", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndNestedArgument() throws JspException {
@Test
public void messageTagWithCodeAndNestedArgument() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -219,8 +224,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test 7 message {1}", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndNestedArguments() throws JspException {
@Test
public void messageTagWithCodeAndNestedArguments() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -238,8 +243,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test arg1 message 6", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithCodeAndText() throws JspException {
@Test
public void messageTagWithCodeAndText() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -256,8 +261,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test message", (message.toString()));
}
@SuppressWarnings("serial")
public void testMessageTagWithText() throws JspException {
@Test
public void messageTagWithText() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -274,8 +279,8 @@ public class MessageTagTests extends AbstractTagTests {
assertTrue("Correct message", message.toString().startsWith("test &amp; text &"));
}
@SuppressWarnings("serial")
public void testMessageTagWithTextEncodingEscaped() throws JspException {
@Test
public void messageTagWithTextEncodingEscaped() throws JspException {
PageContext pc = createPageContext();
pc.getServletContext().setInitParameter(WebUtils.RESPONSE_ENCODED_HTML_ESCAPE_CONTEXT_PARAM, "true");
pc.getResponse().setCharacterEncoding("UTF-8");
@@ -294,8 +299,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test &lt;&amp;&gt; é", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithTextAndJavaScriptEscape() throws JspException {
@Test
public void messageTagWithTextAndJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -312,8 +317,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "\\' test & text \\\\", message.toString());
}
@SuppressWarnings("serial")
public void testMessageTagWithTextAndHtmlEscapeAndJavaScriptEscape() throws JspException {
@Test
public void messageTagWithTextAndHtmlEscapeAndJavaScriptEscape() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
MessageTag tag = new MessageTag() {
@@ -331,7 +336,8 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "&#39; test &amp; text \\\\", message.toString());
}
public void testMessageWithVarAndScope() throws JspException {
@Test
public void messageWithVarAndScope() throws JspException {
PageContext pc = createPageContext();
MessageTag tag = new MessageTag();
tag.setPageContext(pc);
@@ -353,7 +359,8 @@ public class MessageTagTests extends AbstractTagTests {
tag.release();
}
public void testMessageWithVar() throws JspException {
@Test
public void messageWithVar() throws JspException {
PageContext pc = createPageContext();
MessageTag tag = new MessageTag();
tag.setPageContext(pc);
@@ -374,7 +381,9 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct message", "test message", pc.getAttribute("testvar"));
}
public void testNullMessageSource() throws JspException {
@Test
@SuppressWarnings("deprecation")
public void nullMessageSource() throws JspException {
PageContext pc = createPageContext();
ConfigurableWebApplicationContext ctx = (ConfigurableWebApplicationContext)
RequestContextUtils.getWebApplicationContext(pc.getRequest(), pc.getServletContext());
@@ -388,7 +397,9 @@ public class MessageTagTests extends AbstractTagTests {
assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
}
public void testRequestContext() throws ServletException {
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
PageContext pc = createPageContext();
RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
assertEquals("test message", rc.getMessage("test"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,31 +21,35 @@ import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockBodyContent;
import org.springframework.mock.web.test.MockHttpServletResponse;
import static org.junit.Assert.*;
/**
* Unit tests for {@link ParamTag}
* Unit tests for {@link ParamTag}.
*
* @author Scott Andrews
* @author Nicholas Williams
*/
public class ParamTagTests extends AbstractTagTests {
private ParamTag tag;
private final ParamTag tag = new ParamTag();
private MockParamSupportTag parent;
private MockParamSupportTag parent = new MockParamSupportTag();
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
PageContext context = createPageContext();
parent = new MockParamSupportTag();
tag = new ParamTag();
tag.setPageContext(context);
tag.setParent(parent);
}
public void testParamWithNameAndValue() throws JspException {
@Test
public void paramWithNameAndValue() throws JspException {
tag.setName("name");
tag.setValue("value");
@@ -56,10 +60,10 @@ public class ParamTagTests extends AbstractTagTests {
assertEquals("value", parent.getParam().getValue());
}
public void testParamWithBodyValue() throws JspException {
@Test
public void paramWithBodyValue() throws JspException {
tag.setName("name");
tag.setBodyContent(new MockBodyContent("value",
new MockHttpServletResponse()));
tag.setBodyContent(new MockBodyContent("value", new MockHttpServletResponse()));
int action = tag.doEndTag();
@@ -68,7 +72,8 @@ public class ParamTagTests extends AbstractTagTests {
assertEquals("value", parent.getParam().getValue());
}
public void testParamWithImplicitNullValue() throws JspException {
@Test
public void paramWithImplicitNullValue() throws JspException {
tag.setName("name");
int action = tag.doEndTag();
@@ -78,7 +83,8 @@ public class ParamTagTests extends AbstractTagTests {
assertNull(parent.getParam().getValue());
}
public void testParamWithExplicitNullValue() throws JspException {
@Test
public void paramWithExplicitNullValue() throws JspException {
tag.setName("name");
tag.setValue(null);
@@ -89,7 +95,8 @@ public class ParamTagTests extends AbstractTagTests {
assertNull(parent.getParam().getValue());
}
public void testParamWithValueThenReleaseThenBodyValue() throws JspException {
@Test
public void paramWithValueThenReleaseThenBodyValue() throws JspException {
tag.setName("name1");
tag.setValue("value1");
@@ -105,8 +112,7 @@ public class ParamTagTests extends AbstractTagTests {
tag.setPageContext(createPageContext());
tag.setParent(parent);
tag.setName("name2");
tag.setBodyContent(new MockBodyContent("value2",
new MockHttpServletResponse()));
tag.setBodyContent(new MockBodyContent("value2", new MockHttpServletResponse()));
action = tag.doEndTag();
@@ -115,19 +121,12 @@ public class ParamTagTests extends AbstractTagTests {
assertEquals("value2", parent.getParam().getValue());
}
public void testParamWithNoParent() {
@Test(expected = JspException.class)
public void paramWithNoParent() throws Exception {
tag.setName("name");
tag.setValue("value");
tag.setParent(null);
try {
tag.doEndTag();
fail("expected JspException");
}
catch (JspException e) {
// we want this
}
tag.doEndTag();
}
@SuppressWarnings("serial")

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,34 +16,35 @@
package org.springframework.web.servlet.tags;
import junit.framework.TestCase;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for Param
* Unit tests for {@link Param}.
*
* @author Scott Andrews
*/
public class ParamTests extends TestCase {
public class ParamTests {
private Param param;
private final Param param = new Param();
@Override
protected void setUp() throws Exception {
param = new Param();
}
public void testName() {
@Test
public void name() {
param.setName("name");
assertEquals("name", param.getName());
}
public void testValue() {
@Test
public void value() {
param.setValue("value");
assertEquals("value", param.getValue());
}
public void testNullDefaults() {
@Test
public void nullDefaults() {
assertNull(param.getName());
assertNull(param.getValue());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,18 +24,23 @@ import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.servlet.support.RequestContext;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
* @author Alef Arendsen
*/
public class ThemeTagTests extends AbstractTagTests {
@Test
@SuppressWarnings("serial")
public void testThemeTag() throws JspException {
public void themeTag() throws JspException {
PageContext pc = createPageContext();
final StringBuffer message = new StringBuffer();
ThemeTag tag = new ThemeTag() {
@@ -51,7 +56,9 @@ public class ThemeTagTests extends AbstractTagTests {
assertEquals("theme test message", message.toString());
}
public void testRequestContext() throws ServletException {
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
PageContext pc = createPageContext();
RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
assertEquals("theme test message", rc.getThemeMessage("themetest"));

View File

@@ -25,6 +25,9 @@ import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockPageContext;
import org.springframework.util.ReflectionUtils;
@@ -41,24 +44,27 @@ public class UrlTagTests extends AbstractTagTests {
private MockPageContext context;
@Override
protected void setUp() throws Exception {
@Before
public void setUp() throws Exception {
context = createPageContext();
tag = new UrlTag();
tag.setPageContext(context);
}
public void testParamSupport() {
@Test
public void paramSupport() {
assertThat(tag, instanceOf(ParamAware.class));
}
public void testDoStartTag() throws JspException {
@Test
public void doStartTag() throws JspException {
int action = tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, action);
}
public void testDoEndTag() throws JspException {
@Test
public void doEndTag() throws JspException {
tag.setValue("url/path");
tag.doStartTag();
@@ -67,7 +73,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals(Tag.EVAL_PAGE, action);
}
public void testVarDefaultScope() throws JspException {
@Test
public void varDefaultScope() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
@@ -78,7 +85,8 @@ public class UrlTagTests extends AbstractTagTests {
PageContext.PAGE_SCOPE));
}
public void testVarExplicitScope() throws JspException {
@Test
public void varExplicitScope() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
tag.setScope("request");
@@ -90,7 +98,8 @@ public class UrlTagTests extends AbstractTagTests {
PageContext.REQUEST_SCOPE));
}
public void testSetHtmlEscapeDefault() throws JspException {
@Test
public void setHtmlEscapeDefault() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
@@ -112,7 +121,8 @@ public class UrlTagTests extends AbstractTagTests {
.getAttribute("var"));
}
public void testSetHtmlEscapeFalse() throws JspException {
@Test
public void setHtmlEscapeFalse() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
tag.setHtmlEscape(false);
@@ -135,7 +145,8 @@ public class UrlTagTests extends AbstractTagTests {
.getAttribute("var"));
}
public void testSetHtmlEscapeTrue() throws JspException {
@Test
public void setHtmlEscapeTrue() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
tag.setHtmlEscape(true);
@@ -158,7 +169,8 @@ public class UrlTagTests extends AbstractTagTests {
.getAttribute("var"));
}
public void testSetJavaScriptEscapeTrue() throws JspException {
@Test
public void setJavaScriptEscapeTrue() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
tag.setJavaScriptEscape(true);
@@ -181,7 +193,8 @@ public class UrlTagTests extends AbstractTagTests {
.getAttribute("var"));
}
public void testSetHtmlAndJavaScriptEscapeTrue() throws JspException {
@Test
public void setHtmlAndJavaScriptEscapeTrue() throws JspException {
tag.setValue("url/path");
tag.setVar("var");
tag.setHtmlEscape(true);
@@ -205,7 +218,8 @@ public class UrlTagTests extends AbstractTagTests {
.getAttribute("var"));
}
public void testCreateQueryStringNoParams() throws JspException {
@Test
public void createQueryStringNoParams() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -214,7 +228,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("", queryString);
}
public void testCreateQueryStringOneParam() throws JspException {
@Test
public void createQueryStringOneParam() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -228,7 +243,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("?name=value", queryString);
}
public void testCreateQueryStringOneParamForExsistingQueryString()
@Test
public void createQueryStringOneParamForExsistingQueryString()
throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -243,7 +259,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("&name=value", queryString);
}
public void testCreateQueryStringOneParamEmptyValue() throws JspException {
@Test
public void createQueryStringOneParamEmptyValue() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -257,7 +274,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("?name=", queryString);
}
public void testCreateQueryStringOneParamNullValue() throws JspException {
@Test
public void createQueryStringOneParamNullValue() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -271,7 +289,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("?name", queryString);
}
public void testCreateQueryStringOneParamAlreadyUsed() throws JspException {
@Test
public void createQueryStringOneParamAlreadyUsed() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -287,7 +306,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("", queryString);
}
public void testCreateQueryStringTwoParams() throws JspException {
@Test
public void createQueryStringTwoParams() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -306,7 +326,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("?name=value&name=value2", queryString);
}
public void testCreateQueryStringUrlEncoding() throws JspException {
@Test
public void createQueryStringUrlEncoding() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -325,7 +346,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("?n%20me=v%26l%3De&name=value2", queryString);
}
public void testCreateQueryStringParamNullName() throws JspException {
@Test
public void createQueryStringParamNullName() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -339,7 +361,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("", queryString);
}
public void testCreateQueryStringParamEmptyName() throws JspException {
@Test
public void createQueryStringParamEmptyName() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -353,7 +376,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("", queryString);
}
public void testReplaceUriTemplateParamsNoParams() throws JspException {
@Test
public void replaceUriTemplateParamsNoParams() throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -364,7 +388,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals(0, usedParams.size());
}
public void testReplaceUriTemplateParamsTemplateWithoutParamMatch()
@Test
public void replaceUriTemplateParamsTemplateWithoutParamMatch()
throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -376,7 +401,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals(0, usedParams.size());
}
public void testReplaceUriTemplateParamsTemplateWithParamMatch()
@Test
public void replaceUriTemplateParamsTemplateWithParamMatch()
throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -394,7 +420,8 @@ public class UrlTagTests extends AbstractTagTests {
assertTrue(usedParams.contains("name"));
}
public void testReplaceUriTemplateParamsTemplateWithParamMatchNamePreEncoding()
@Test
public void replaceUriTemplateParamsTemplateWithParamMatchNamePreEncoding()
throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -412,7 +439,8 @@ public class UrlTagTests extends AbstractTagTests {
assertTrue(usedParams.contains("n me"));
}
public void testReplaceUriTemplateParamsTemplateWithParamMatchValueEncoded()
@Test
public void replaceUriTemplateParamsTemplateWithParamMatchValueEncoded()
throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -432,7 +460,8 @@ public class UrlTagTests extends AbstractTagTests {
// SPR-11401
public void testReplaceUriTemplateParamsTemplateWithPathSegment()
@Test
public void replaceUriTemplateParamsTemplateWithPathSegment()
throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -449,7 +478,8 @@ public class UrlTagTests extends AbstractTagTests {
assertTrue(usedParams.contains("name"));
}
public void testReplaceUriTemplateParamsTemplateWithPath()
@Test
public void replaceUriTemplateParamsTemplateWithPath()
throws JspException {
List<Param> params = new LinkedList<Param>();
Set<String> usedParams = new HashSet<String>();
@@ -466,7 +496,8 @@ public class UrlTagTests extends AbstractTagTests {
assertTrue(usedParams.contains("name"));
}
public void testCreateUrlRemoteServer() throws JspException {
@Test
public void createUrlRemoteServer() throws JspException {
tag.setValue("http://www.springframework.org/");
tag.doStartTag();
@@ -477,7 +508,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("http://www.springframework.org/", uri);
}
public void testCreateUrlRelative() throws JspException {
@Test
public void createUrlRelative() throws JspException {
tag.setValue("url/path");
tag.doStartTag();
@@ -487,7 +519,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("url/path", uri);
}
public void testCreateUrlLocalContext() throws JspException {
@Test
public void createUrlLocalContext() throws JspException {
((MockHttpServletRequest) context.getRequest())
.setContextPath("/app-context");
@@ -500,7 +533,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("/app-context/url/path", uri);
}
public void testCreateUrlRemoteContext() throws JspException {
@Test
public void createUrlRemoteContext() throws JspException {
((MockHttpServletRequest) context.getRequest())
.setContextPath("/app-context");
@@ -514,7 +548,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("/some-other-context/url/path", uri);
}
public void testCreateUrlRemoteContextWithSlash() throws JspException {
@Test
public void createUrlRemoteContextWithSlash() throws JspException {
((MockHttpServletRequest) context.getRequest())
.setContextPath("/app-context");
@@ -528,7 +563,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("/some-other-context/url/path", uri);
}
public void testCreateUrlRemoteContextSingleSlash() throws JspException {
@Test
public void createUrlRemoteContextSingleSlash() throws JspException {
((MockHttpServletRequest) context.getRequest())
.setContextPath("/app-context");
@@ -542,7 +578,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("/url/path", uri);
}
public void testCreateUrlWithParams() throws JspException {
@Test
public void createUrlWithParams() throws JspException {
tag.setValue("url/path");
tag.doStartTag();
@@ -562,7 +599,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("url/path?name=value&n%20me=v%20lue", uri);
}
public void testCreateUrlWithTemplateParams() throws JspException {
@Test
public void createUrlWithTemplateParams() throws JspException {
tag.setValue("url/{name}");
tag.doStartTag();
@@ -582,7 +620,8 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("url/value?n%20me=v%20lue", uri);
}
public void testCreateUrlWithParamAndExsistingQueryString()
@Test
public void createUrlWithParamAndExsistingQueryString()
throws JspException {
tag.setValue("url/path?foo=bar");
@@ -598,11 +637,13 @@ public class UrlTagTests extends AbstractTagTests {
assertEquals("url/path?foo=bar&name=value", uri);
}
public void testJspWriterOutput() {
@Test
public void jspWriterOutput() {
// TODO assert that the output to the JspWriter is the expected output
}
public void testServletRepsonseEncodeUrl() {
@Test
public void servletRepsonseEncodeUrl() {
// TODO assert that HttpServletResponse.encodeURL(String) is invoked for
// non absolute urls
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,14 @@ package org.springframework.web.servlet.tags.form;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Collections;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import org.junit.Before;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockPageContext;
import org.springframework.validation.BindingResult;
@@ -37,7 +39,8 @@ import org.springframework.web.servlet.support.RequestDataValueProcessorWrapper;
import org.springframework.web.servlet.tags.AbstractTagTests;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
import static org.mockito.BDDMockito.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
/**
* @author Rob Harrop
@@ -52,8 +55,8 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
private MockPageContext pageContext;
@Override
protected final void setUp() throws Exception {
@Before
public final void setUp() throws Exception {
// set up a writer for the tag content to be written to
this.writer = new StringWriter();
@@ -66,7 +69,7 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
protected MockPageContext createAndPopulatePageContext() throws JspException {
MockPageContext pageContext = createPageContext();
MockHttpServletRequest request = (MockHttpServletRequest) pageContext.getRequest();
StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.getWebApplicationContext(request);
StaticWebApplicationContext wac = (StaticWebApplicationContext) RequestContextUtils.findWebApplicationContext(request);
wac.registerSingleton("requestDataValueProcessor", RequestDataValueProcessorWrapper.class);
extendRequest(request);
extendPageContext(pageContext);
@@ -100,6 +103,7 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
return (RequestContext) getPageContext().getAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE);
}
@SuppressWarnings("deprecation")
protected RequestDataValueProcessor getMockRequestDataValueProcessor() {
RequestDataValueProcessor mockProcessor = mock(RequestDataValueProcessor.class);
ServletRequest request = getPageContext().getRequest();
@@ -110,8 +114,8 @@ public abstract class AbstractHtmlElementTagTests extends AbstractTagTests {
protected void exposeBindingResult(Errors errors) {
// wrap errors in a Model
Map model = new HashMap();
model.put(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors);
Map<String, Object> model = Collections.singletonMap(
BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors);
// replace the request context with one containing the errors
MockPageContext pageContext = getPageContext();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,10 +17,15 @@
package org.springframework.web.servlet.tags.form;
import java.io.Writer;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean;
import static org.junit.Assert.*;
/**
* @author Rossen Stoyanchev
*/
@@ -38,7 +43,8 @@ public class ButtonTagTests extends AbstractFormTagTests {
this.tag.setValue("My Button");
}
public void testButtonTag() throws Exception {
@Test
public void buttonTag() throws Exception {
assertEquals(Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag());
assertEquals(Tag.EVAL_PAGE, this.tag.doEndTag());
@@ -53,7 +59,8 @@ public class ButtonTagTests extends AbstractFormTagTests {
assertAttributeNotPresent(output, "disabled");
}
public void testDisabled() throws Exception {
@Test
public void disabled() throws Exception {
this.tag.setDisabled(true);
this.tag.doStartTag();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,8 @@ import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.tests.sample.beans.Colour;
import org.springframework.tests.sample.beans.Pet;
@@ -38,11 +40,14 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Jeremy Grelle
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class CheckboxTagTests extends AbstractFormTagTests {
private CheckboxTag tag;
@@ -61,7 +66,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
this.tag.setPageContext(getPageContext());
}
public void testWithSingleValueBooleanObjectChecked() throws Exception {
@Test
public void withSingleValueBooleanObjectChecked() throws Exception {
this.tag.setPath("someBoolean");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
@@ -83,7 +89,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithIndexedBooleanObjectNotChecked() throws Exception {
@Test
public void withIndexedBooleanObjectNotChecked() throws Exception {
this.tag.setPath("someMap[key]");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
@@ -105,7 +112,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueBooleanObjectCheckedAndDynamicAttributes() throws Exception {
@Test
public void withSingleValueBooleanObjectCheckedAndDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -134,7 +142,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals(dynamicAttribute2, checkboxElement.attribute(dynamicAttribute2).getValue());
}
public void testWithSingleValueBooleanChecked() throws Exception {
@Test
public void withSingleValueBooleanChecked() throws Exception {
this.tag.setPath("jedi");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
@@ -153,7 +162,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueBooleanObjectUnchecked() throws Exception {
@Test
public void withSingleValueBooleanObjectUnchecked() throws Exception {
this.bean.setSomeBoolean(new Boolean(false));
this.tag.setPath("someBoolean");
int result = this.tag.doStartTag();
@@ -174,7 +184,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueBooleanUnchecked() throws Exception {
@Test
public void withSingleValueBooleanUnchecked() throws Exception {
this.bean.setJedi(false);
this.tag.setPath("jedi");
int result = this.tag.doStartTag();
@@ -195,7 +206,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueNull() throws Exception {
@Test
public void withSingleValueNull() throws Exception {
this.bean.setName(null);
this.tag.setPath("name");
this.tag.setValue("Rob Harrop");
@@ -217,7 +229,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("Rob Harrop", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueNotNull() throws Exception {
@Test
public void withSingleValueNotNull() throws Exception {
this.bean.setName("Rob Harrop");
this.tag.setPath("name");
this.tag.setValue("Rob Harrop");
@@ -239,7 +252,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("Rob Harrop", checkboxElement.attribute("value").getValue());
}
public void testWithSingleValueAndEditor() throws Exception {
@Test
public void withSingleValueAndEditor() throws Exception {
this.bean.setName("Rob Harrop");
this.tag.setPath("name");
this.tag.setValue(" Rob Harrop");
@@ -265,7 +279,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals(" Rob Harrop", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueChecked() throws Exception {
@Test
public void withMultiValueChecked() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue("foo");
int result = this.tag.doStartTag();
@@ -286,7 +301,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("foo", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueUnchecked() throws Exception {
@Test
public void withMultiValueUnchecked() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue("abc");
int result = this.tag.doStartTag();
@@ -307,7 +323,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("abc", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueWithEditor() throws Exception {
@Test
public void withMultiValueWithEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setValue(" foo");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -334,7 +351,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals(" foo", checkboxElement.attribute("value").getValue());
}
public void testWithMultiValueIntegerWithEditor() throws Exception {
@Test
public void withMultiValueIntegerWithEditor() throws Exception {
this.tag.setPath("someIntegerArray");
this.tag.setValue(" 1");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -361,7 +379,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals(" 1", checkboxElement.attribute("value").getValue());
}
public void testWithCollection() throws Exception {
@Test
public void withCollection() throws Exception {
this.tag.setPath("someList");
this.tag.setValue("foo");
int result = this.tag.doStartTag();
@@ -382,7 +401,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("foo", checkboxElement.attribute("value").getValue());
}
public void testWithObjectChecked() throws Exception {
@Test
public void withObjectChecked() throws Exception {
this.tag.setPath("date");
this.tag.setValue(getDate());
@@ -404,7 +424,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals(getDate().toString(), checkboxElement.attribute("value").getValue());
}
public void testWithObjectUnchecked() throws Exception {
@Test
public void withObjectUnchecked() throws Exception {
this.tag.setPath("date");
Date date = new Date();
this.tag.setValue(date);
@@ -427,7 +448,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals(date.toString(), checkboxElement.attribute("value").getValue());
}
public void testCollectionOfColoursSelected() throws Exception {
@Test
public void collectionOfColoursSelected() throws Exception {
this.tag.setPath("otherColours");
this.tag.setValue("RED");
@@ -448,7 +470,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfColoursNotSelected() throws Exception {
@Test
public void collectionOfColoursNotSelected() throws Exception {
this.tag.setPath("otherColours");
this.tag.setValue("PURPLE");
@@ -469,7 +492,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPetsAsString() throws Exception {
@Test
public void collectionOfPetsAsString() throws Exception {
this.tag.setPath("pets");
this.tag.setValue("Spot");
@@ -490,7 +514,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfPetsAsStringNotSelected() throws Exception {
@Test
public void collectionOfPetsAsStringNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue("Santa's Little Helper");
@@ -511,7 +536,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPets() throws Exception {
@Test
public void collectionOfPets() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Rudiger"));
@@ -533,7 +559,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfPetsNotSelected() throws Exception {
@Test
public void collectionOfPetsNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Santa's Little Helper"));
@@ -555,7 +582,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPetsWithEditor() throws Exception {
@Test
public void collectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new ItemPet("Rudiger"));
@@ -582,7 +610,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testWithNullValue() throws Exception {
@Test
public void withNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
@@ -593,7 +622,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
}
}
public void testHiddenElementOmittedOnDisabled() throws Exception {
@Test
public void hiddenElementOmittedOnDisabled() throws Exception {
this.tag.setPath("someBoolean");
this.tag.setDisabled(true);
int result = this.tag.doStartTag();
@@ -615,7 +645,8 @@ public class CheckboxTagTests extends AbstractFormTagTests {
assertEquals("true", checkboxElement.attribute("value").getValue());
}
public void testDynamicTypeAttribute() throws JspException {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -35,6 +35,8 @@ import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.format.Formatter;
import org.springframework.format.support.FormattingConversionService;
@@ -45,6 +47,8 @@ import org.springframework.util.ObjectUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.junit.Assert.*;
/**
* @author Thomas Risberg
* @author Mark Fisher
@@ -52,6 +56,7 @@ import org.springframework.validation.BindingResult;
* @author Benjamin Hoffmann
* @author Jeremy Grelle
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class CheckboxesTagTests extends AbstractFormTagTests {
private CheckboxesTag tag;
@@ -70,7 +75,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
this.tag.setPageContext(getPageContext());
}
public void testWithMultiValueArray() throws Exception {
@Test
public void withMultiValueArray() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
int result = this.tag.doStartTag();
@@ -108,7 +114,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueArrayAndDynamicAttributes() throws Exception {
@Test
public void withMultiValueArrayAndDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -161,7 +168,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
}
public void testWithMultiValueArrayWithDelimiter() throws Exception {
@Test
public void withMultiValueArrayWithDelimiter() throws Exception {
this.tag.setDelimiter("<br/>");
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
@@ -206,7 +214,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueMap() throws Exception {
@Test
public void withMultiValueMap() throws Exception {
this.tag.setPath("stringArray");
Map m = new LinkedHashMap();
m.put("foo", "FOO");
@@ -249,7 +258,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("BAZ", spanElement3.getStringValue());
}
public void testWithPetItemsMap() throws Exception {
@Test
public void withPetItemsMap() throws Exception {
this.tag.setPath("someSet");
Map m = new LinkedHashMap();
m.put(new ItemPet("PET1"), "PET1Label");
@@ -293,7 +303,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("PET3Label", spanElement3.getStringValue());
}
public void testWithMultiValueMapWithDelimiter() throws Exception {
@Test
public void withMultiValueMapWithDelimiter() throws Exception {
String delimiter = " | ";
this.tag.setDelimiter(delimiter);
this.tag.setPath("stringArray");
@@ -338,7 +349,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals(delimiter + "BAZ", spanElement3.getStringValue());
}
public void testWithMultiValueWithEditor() throws Exception {
@Test
public void withMultiValueWithEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {" foo", " bar", " baz"});
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -380,7 +392,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals(" baz", checkboxElement3.attribute("value").getValue());
}
public void testWithMultiValueWithReverseEditor() throws Exception {
@Test
public void withMultiValueWithReverseEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"FOO", "BAR", "BAZ"});
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -421,7 +434,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("BAZ", checkboxElement3.attribute("value").getValue());
}
public void testWithMultiValueWithFormatter() throws Exception {
@Test
public void withMultiValueWithFormatter() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {" foo", " bar", " baz"});
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -472,7 +486,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals(" baz", checkboxElement3.attribute("value").getValue());
}
public void testCollectionOfPets() throws Exception {
@Test
public void collectionOfPets() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
@@ -539,7 +554,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
/**
* Test case where items toString() doesn't fit the item ID
*/
public void testCollectionOfItemPets() throws Exception {
@Test
public void collectionOfItemPets() throws Exception {
this.tag.setPath("someSet");
List allPets = new ArrayList();
allPets.add(new ItemPet("PET1"));
@@ -587,7 +603,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("PET3", spanElement3.getStringValue());
}
public void testCollectionOfPetsWithEditor() throws Exception {
@Test
public void collectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
@@ -656,7 +673,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("MUFTY", spanElement5.getStringValue());
}
public void testWithNullValue() throws Exception {
@Test
public void withNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
@@ -667,7 +685,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
}
}
public void testHiddenElementOmittedOnDisabled() throws Exception {
@Test
public void hiddenElementOmittedOnDisabled() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setDisabled(true);
@@ -692,7 +711,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("foo", checkboxElement.attribute("value").getValue());
}
public void testSpanElementCustomizable() throws Exception {
@Test
public void spanElementCustomizable() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setElement("element");
@@ -709,7 +729,8 @@ public class CheckboxesTagTests extends AbstractFormTagTests {
assertEquals("element", spanElement.getName());
}
public void testDynamicTypeAttribute() throws JspException {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@ import java.util.List;
* @author Rob Harrop
* @author Sam Brannen
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class Country {
public static final Country COUNTRY_AT = new Country("AT", "Austria");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,8 @@ import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.mock.web.test.MockBodyContent;
import org.springframework.mock.web.test.MockPageContext;
import org.springframework.tests.sample.beans.TestBean;
@@ -34,6 +36,8 @@ import org.springframework.validation.Errors;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Rick Evans
@@ -41,6 +45,7 @@ import org.springframework.web.servlet.tags.RequestContextAwareTag;
* @author Mark Fisher
* @author Jeremy Grelle
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ErrorsTagTests extends AbstractFormTagTests {
private static final String COMMAND_NAME = "testBean";
@@ -68,7 +73,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
}
public void testWithExplicitNonWhitespaceBodyContent() throws Exception {
@Test
public void withExplicitNonWhitespaceBodyContent() throws Exception {
String mockContent = "This is some explicit body content";
this.tag.setBodyContent(new MockBodyContent(mockContent, getWriter()));
@@ -88,7 +94,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertEquals(mockContent, getOutput());
}
public void testWithExplicitWhitespaceBodyContent() throws Exception {
@Test
public void withExplicitWhitespaceBodyContent() throws Exception {
this.tag.setBodyContent(new MockBodyContent("\t\n ", getWriter()));
// construct an errors instance of the tag
@@ -113,7 +120,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Default Message");
}
public void testWithExplicitEmptyWhitespaceBodyContent() throws Exception {
@Test
public void withExplicitEmptyWhitespaceBodyContent() throws Exception {
this.tag.setBodyContent(new MockBodyContent("", getWriter()));
// construct an errors instance of the tag
@@ -138,7 +146,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Default Message");
}
public void testWithErrors() throws Exception {
@Test
public void withErrors() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
@@ -164,7 +173,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Too Short");
}
public void testWithErrorsAndDynamicAttributes() throws Exception {
@Test
public void withErrorsAndDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -198,7 +208,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Too Short");
}
public void testWithEscapedErrors() throws Exception {
@Test
public void withEscapedErrors() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
@@ -224,7 +235,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Too &amp; Short");
}
public void testWithNonEscapedErrors() throws Exception {
@Test
public void withNonEscapedErrors() throws Exception {
this.tag.setHtmlEscape(false);
// construct an errors instance of the tag
@@ -252,7 +264,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Too & Short");
}
public void testWithErrorsAndCustomElement() throws Exception {
@Test
public void withErrorsAndCustomElement() throws Exception {
// construct an errors instance of the tag
TestBean target = new TestBean();
target.setName("Rob Harrop");
@@ -279,7 +292,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Too Short");
}
public void testWithoutErrors() throws Exception {
@Test
public void withoutErrors() throws Exception {
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
exposeBindingResult(errors);
int result = this.tag.doStartTag();
@@ -292,7 +306,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertEquals(0, output.length());
}
public void testWithoutErrorsInstance() throws Exception {
@Test
public void withoutErrorsInstance() throws Exception {
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
@@ -303,7 +318,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertEquals(0, output.length());
}
public void testAsBodyTag() throws Exception {
@Test
public void asBodyTag() throws Exception {
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.rejectValue("name", "some.code", "Default Message");
errors.rejectValue("name", "too.short", "Too Short");
@@ -319,7 +335,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertNull(getPageContext().getAttribute(ErrorsTag.MESSAGES_ATTRIBUTE));
}
public void testAsBodyTagWithExistingMessagesAttribute() throws Exception {
@Test
public void asBodyTagWithExistingMessagesAttribute() throws Exception {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
@@ -339,9 +356,10 @@ public class ErrorsTagTests extends AbstractFormTagTests {
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
* https://jira.spring.io/browse/SPR-2788
*/
public void testAsBodyTagWithErrorsAndExistingMessagesAttributeInNonPageScopeAreNotClobbered() throws Exception {
@Test
public void asBodyTagWithErrorsAndExistingMessagesAttributeInNonPageScopeAreNotClobbered() throws Exception {
String existingAttribute = "something";
getPageContext().setAttribute(ErrorsTag.MESSAGES_ATTRIBUTE, existingAttribute, PageContext.APPLICATION_SCOPE);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
@@ -362,37 +380,42 @@ public class ErrorsTagTests extends AbstractFormTagTests {
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
* https://jira.spring.io/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInApplicationScopeAreNotClobbered() throws Exception {
@Test
public void asBodyTagWithNoErrorsAndExistingMessagesAttributeInApplicationScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.APPLICATION_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
* https://jira.spring.io/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInSessionScopeAreNotClobbered() throws Exception {
@Test
public void asBodyTagWithNoErrorsAndExistingMessagesAttributeInSessionScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.SESSION_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
* https://jira.spring.io/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInPageScopeAreNotClobbered() throws Exception {
@Test
public void asBodyTagWithNoErrorsAndExistingMessagesAttributeInPageScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.PAGE_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-2788
* https://jira.spring.io/browse/SPR-2788
*/
public void testAsBodyTagWithNoErrorsAndExistingMessagesAttributeInRequestScopeAreNotClobbered() throws Exception {
@Test
public void asBodyTagWithNoErrorsAndExistingMessagesAttributeInRequestScopeAreNotClobbered() throws Exception {
assertWhenNoErrorsExistingMessagesInScopeAreNotClobbered(PageContext.REQUEST_SCOPE);
}
/**
* http://opensource.atlassian.com/projects/spring/browse/SPR-4005
* https://jira.spring.io/browse/SPR-4005
*/
public void testOmittedPathMatchesObjectErrorsOnly() throws Exception {
@Test
public void omittedPathMatchesObjectErrorsOnly() throws Exception {
this.tag.setPath(null);
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.reject("some.code", "object error");
@@ -407,7 +430,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertFalse(output.contains("field error"));
}
public void testSpecificPathMatchesSpecificFieldOnly() throws Exception {
@Test
public void specificPathMatchesSpecificFieldOnly() throws Exception {
this.tag.setPath("name");
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.reject("some.code", "object error");
@@ -422,7 +446,8 @@ public class ErrorsTagTests extends AbstractFormTagTests {
assertTrue(output.contains("field error"));
}
public void testStarMatchesAllErrors() throws Exception {
@Test
public void starMatchesAllErrors() throws Exception {
this.tag.setPath("*");
Errors errors = new BeanPropertyBindingResult(new TestBean(), "COMMAND_NAME");
errors.reject("some.code", "object error");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,9 +20,12 @@ import java.util.Collections;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/**
@@ -39,7 +42,6 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
private static final String QUERY_STRING = "foo=bar";
private FormTag tag;
private MockHttpServletRequest request;
@@ -64,7 +66,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
this.request = request;
}
public void testWriteForm() throws Exception {
@Test
public void writeForm() throws Exception {
String commandName = "myCommand";
String name = "formName";
String action = "/form.html";
@@ -127,7 +130,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
}
public void testWithActionFromRequest() throws Exception {
@Test
public void withActionFromRequest() throws Exception {
String commandName = "myCommand";
String enctype = "my/enctype";
String method = "POST";
@@ -164,7 +168,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertAttributeNotPresent(output, "name");
}
public void testPrependServletPath() throws Exception {
@Test
public void prependServletPath() throws Exception {
this.request.setContextPath("/myApp");
this.request.setServletPath("/main");
@@ -208,7 +213,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertAttributeNotPresent(output, "name");
}
public void testWithNullResolvedCommand() throws Exception {
@Test
public void withNullResolvedCommand() throws Exception {
try {
tag.setCommandName(null);
tag.doStartTag();
@@ -219,10 +225,11 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
}
}
/*
* See http://opensource.atlassian.com/projects/spring/browse/SPR-2645
/**
* https://jira.spring.io/browse/SPR-2645
*/
public void testXSSScriptingExploitWhenActionIsResolvedFromQueryString() throws Exception {
@Test
public void xssExploitWhenActionIsResolvedFromQueryString() throws Exception {
String xssQueryString = QUERY_STRING + "&stuff=\"><script>alert('XSS!')</script>";
request.setQueryString(xssQueryString);
tag.doStartTag();
@@ -230,7 +237,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
getOutput());
}
public void testGet() throws Exception {
@Test
public void get() throws Exception {
this.tag.setMethod("get");
this.tag.doStartTag();
@@ -245,7 +253,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertEquals("", inputOutput);
}
public void testPost() throws Exception {
@Test
public void post() throws Exception {
this.tag.setMethod("post");
this.tag.doStartTag();
@@ -260,7 +269,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertEquals("", inputOutput);
}
public void testPut() throws Exception {
@Test
public void put() throws Exception {
this.tag.setMethod("put");
this.tag.doStartTag();
@@ -277,7 +287,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testDelete() throws Exception {
@Test
public void delete() throws Exception {
this.tag.setMethod("delete");
this.tag.doStartTag();
@@ -294,7 +305,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testCustomMethodParameter() throws Exception {
@Test
public void customMethodParameter() throws Exception {
this.tag.setMethod("put");
this.tag.setMethodParam("methodParameter");
@@ -312,7 +324,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertContainsAttribute(inputOutput, "type", "hidden");
}
public void testClearAttributesOnFinally() throws Exception {
@Test
public void clearAttributesOnFinally() throws Exception {
this.tag.setModelAttribute("model");
getPageContext().setAttribute("model", "foo bar");
assertNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
@@ -322,7 +335,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertNull(getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE));
}
public void testRequestDataValueProcessorHooks() throws Exception {
@Test
public void requestDataValueProcessorHooks() throws Exception {
String action = "/my/form?foo=bar";
RequestDataValueProcessor processor = getMockRequestDataValueProcessor();
given(processor.processAction(this.request, action, "post")).willReturn(action);
@@ -339,7 +353,8 @@ public class FormTagTests extends AbstractHtmlElementTagTests {
assertFormTagClosed(output);
}
public void testDefaultActionEncoded() throws Exception {
@Test
public void defaultActionEncoded() throws Exception {
this.request.setRequestURI("/a b c");
request.setQueryString("");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,9 +19,13 @@ package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
*/
@@ -43,7 +47,8 @@ public class HiddenInputTagTests extends AbstractFormTagTests {
this.tag.setPageContext(getPageContext());
}
public void testRender() throws Exception {
@Test
public void render() throws Exception {
this.tag.setPath("name");
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
@@ -58,7 +63,8 @@ public class HiddenInputTagTests extends AbstractFormTagTests {
assertAttributeNotPresent(output, "disabled");
}
public void testWithCustomBinder() throws Exception {
@Test
public void withCustomBinder() throws Exception {
this.tag.setPath("myFloat");
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -76,7 +82,8 @@ public class HiddenInputTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, "value", "12.34f");
}
public void testDynamicTypeAttribute() throws JspException {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");
@@ -86,7 +93,8 @@ public class HiddenInputTagTests extends AbstractFormTagTests {
}
}
public void testDisabledTrue() throws Exception {
@Test
public void disabledTrue() throws Exception {
this.tag.setDisabled(true);
this.tag.doStartTag();
@@ -101,7 +109,8 @@ public class HiddenInputTagTests extends AbstractFormTagTests {
// SPR-8661
public void testDisabledFalse() throws Exception {
@Test
public void disabledFalse() throws Exception {
this.tag.setDisabled(false);
this.tag.doStartTag();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,12 +20,16 @@ import java.io.Writer;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.BindTag;
import org.springframework.web.servlet.tags.NestedPathTag;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Rick Evans
@@ -64,7 +68,8 @@ public class InputTagTests extends AbstractFormTagTests {
}
public void testSimpleBind() throws Exception {
@Test
public void simpleBind() throws Exception {
this.tag.setPath("name");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
@@ -77,7 +82,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertValueAttribute(output, "Rob");
}
public void testSimpleBindTagWithinForm() throws Exception {
@Test
public void simpleBindTagWithinForm() throws Exception {
BindTag bindTag = new BindTag();
bindTag.setPath("name");
bindTag.setPageContext(getPageContext());
@@ -87,7 +93,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertEquals("Rob", bindStatus.getValue());
}
public void testSimpleBindWithHtmlEscaping() throws Exception {
@Test
public void simpleBindWithHtmlEscaping() throws Exception {
final String NAME = "Rob \"I Love Mangos\" Harrop";
final String HTML_ESCAPED_NAME = "Rob &quot;I Love Mangos&quot; Harrop";
@@ -108,7 +115,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, "value", expectedValue);
}
public void testComplexBind() throws Exception {
@Test
public void complexBind() throws Exception {
this.tag.setPath("spouse.name");
assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());
@@ -123,7 +131,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertValueAttribute(output, "Sally");
}
public void testWithAllAttributes() throws Exception {
@Test
public void withAllAttributes() throws Exception {
String title = "aTitle";
String id = "123";
String size = "12";
@@ -228,7 +237,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
}
public void testWithNestedBind() throws Exception {
@Test
public void withNestedBind() throws Exception {
NestedPathTag nestedPathTag = new NestedPathTag();
nestedPathTag.setPath("spouse.");
nestedPathTag.setPageContext(getPageContext());
@@ -246,7 +256,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertValueAttribute(output, "Sally");
}
public void testWithNestedBindTagWithinForm() throws Exception {
@Test
public void withNestedBindTagWithinForm() throws Exception {
NestedPathTag nestedPathTag = new NestedPathTag();
nestedPathTag.setPath("spouse.");
nestedPathTag.setPageContext(getPageContext());
@@ -261,7 +272,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertEquals("Sally", bindStatus.getValue());
}
public void testWithErrors() throws Exception {
@Test
public void withErrors() throws Exception {
this.tag.setPath("name");
this.tag.setCssClass("good");
this.tag.setCssErrorClass("bad");
@@ -282,7 +294,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, "class", "bad");
}
public void testDisabledFalse() throws Exception {
@Test
public void disabledFalse() throws Exception {
this.tag.setPath("name");
this.tag.setDisabled(false);
this.tag.doStartTag();
@@ -291,7 +304,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertAttributeNotPresent(output, "disabled");
}
public void testWithCustomBinder() throws Exception {
@Test
public void withCustomBinder() throws Exception {
this.tag.setPath("myFloat");
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
@@ -311,7 +325,8 @@ public class InputTagTests extends AbstractFormTagTests {
/**
* See SPR-3127 (http://opensource.atlassian.com/projects/spring/browse/SPR-3127)
*/
public void testReadOnlyAttributeRenderingWhenReadonlyIsTrue() throws Exception {
@Test
public void readOnlyAttributeRenderingWhenReadonlyIsTrue() throws Exception {
this.tag.setPath("name");
this.tag.setReadonly(true);
@@ -326,7 +341,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertValueAttribute(output, "Rob");
}
public void testDynamicTypeAttribute() throws JspException {
@Test
public void dynamicTypeAttribute() throws JspException {
this.tag.setPath("myFloat");
this.tag.setDynamicAttribute(null, "type", "number");
@@ -340,7 +356,8 @@ public class InputTagTests extends AbstractFormTagTests {
assertValueAttribute(output, "12.34");
}
public void testDynamicTypeRadioAttribute() throws JspException {
@Test
public void dynamicTypeRadioAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "radio");
fail("Expected exception");
@@ -350,7 +367,8 @@ public class InputTagTests extends AbstractFormTagTests {
}
}
public void testDynamicTypeCheckboxAttribute() throws JspException {
@Test
public void dynamicTypeCheckboxAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "checkbox");
fail("Expected exception");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,10 +19,14 @@ package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.mock.web.test.MockPageContext;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.web.servlet.tags.NestedPathTag;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Rick Evans
@@ -57,7 +61,8 @@ public class LabelTagTests extends AbstractFormTagTests {
}
public void testSimpleRender() throws Exception {
@Test
public void simpleRender() throws Exception {
this.tag.setPath("name");
int startResult = this.tag.doStartTag();
int endResult = this.tag.doEndTag();
@@ -66,7 +71,7 @@ public class LabelTagTests extends AbstractFormTagTests {
assertEquals(Tag.EVAL_PAGE, endResult);
String output = getOutput();
// we are using a nexted path (see extendPageContext(..)), so...
// we are using a nested path (see extendPageContext(..)), so...
assertContainsAttribute(output, "for", "spouse.name");
// name attribute is not supported by <label/>
assertAttributeNotPresent(output, "name");
@@ -76,7 +81,8 @@ public class LabelTagTests extends AbstractFormTagTests {
assertTrue(output.endsWith("</label>"));
}
public void testSimpleRenderWithDynamicAttributes() throws Exception {
@Test
public void simpleRenderWithDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -91,7 +97,7 @@ public class LabelTagTests extends AbstractFormTagTests {
assertEquals(Tag.EVAL_PAGE, endResult);
String output = getOutput();
// we are using a nexted path (see extendPageContext(..)), so...
// we are using a nested path (see extendPageContext(..)), so...
assertContainsAttribute(output, "for", "spouse.name");
assertContainsAttribute(output, dynamicAttribute1, dynamicAttribute1);
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
@@ -103,7 +109,8 @@ public class LabelTagTests extends AbstractFormTagTests {
assertTrue(output.endsWith("</label>"));
}
public void testSimpleRenderWithMapElement() throws Exception {
@Test
public void simpleRenderWithMapElement() throws Exception {
this.tag.setPath("someMap[1]");
int startResult = this.tag.doStartTag();
int endResult = this.tag.doEndTag();
@@ -112,7 +119,7 @@ public class LabelTagTests extends AbstractFormTagTests {
assertEquals(Tag.EVAL_PAGE, endResult);
String output = getOutput();
// we are using a nexted path (see extendPageContext(..)), so...
// we are using a nested path (see extendPageContext(..)), so...
assertContainsAttribute(output, "for", "spouse.someMap1");
// name attribute is not supported by <label/>
assertAttributeNotPresent(output, "name");
@@ -122,7 +129,8 @@ public class LabelTagTests extends AbstractFormTagTests {
assertTrue(output.endsWith("</label>"));
}
public void testOverrideFor() throws Exception {
@Test
public void overrideFor() throws Exception {
this.tag.setPath("name");
this.tag.setFor("myElement");
int startResult = this.tag.doStartTag();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,10 +19,13 @@ package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.tests.sample.beans.CustomEnum;
import org.springframework.tests.sample.beans.GenericBean;
import org.springframework.web.servlet.support.BindStatus;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
@@ -53,7 +56,9 @@ public class OptionTagEnumTests extends AbstractHtmlElementTagTests {
this.tag.setPageContext(getPageContext());
}
public void testWithJavaEnum() throws Exception {
@Test
@SuppressWarnings("rawtypes")
public void withJavaEnum() throws Exception {
GenericBean testBean = new GenericBean();
testBean.setCustomEnum(CustomEnum.VALUE_1);
getPageContext().getRequest().setAttribute("testBean", testBean);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,8 @@ import java.util.List;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.mock.web.test.MockBodyContent;
import org.springframework.mock.web.test.MockHttpServletRequest;
@@ -33,19 +35,21 @@ import org.springframework.util.StringUtils;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.web.servlet.support.BindStatus;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Rick Evans
* @author Jeremy Grelle
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class OptionTagTests extends AbstractHtmlElementTagTests {
private static final String ARRAY_SOURCE = "abc,123,def";
private static final String[] ARRAY = StringUtils.commaDelimitedListToStringArray(ARRAY_SOURCE);
private OptionTag tag;
private SelectTag parentTag;
@@ -72,7 +76,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
}
public void testCanBeDisabledEvenWhenSelected() throws Exception {
@Test
public void canBeDisabledEvenWhenSelected() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
this.tag.setValue("bar");
@@ -92,7 +97,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "Bar");
}
public void testRenderNotSelected() throws Exception {
@Test
public void renderNotSelected() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
this.tag.setValue("bar");
@@ -110,7 +116,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "Bar");
}
public void testRenderWithDynamicAttributes() throws Exception {
@Test
public void renderWithDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -136,7 +143,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "Bar");
}
public void testRenderSelected() throws Exception {
@Test
public void renderSelected() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
this.tag.setId("myOption");
@@ -157,7 +165,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "Foo");
}
public void testWithNoLabel() throws Exception {
@Test
public void withNoLabel() throws Exception {
String selectName = "testBean.name";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
this.tag.setValue("bar");
@@ -178,7 +187,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "bar");
}
public void testWithoutContext() throws Exception {
@Test
public void withoutContext() throws Exception {
this.tag.setParent(null);
this.tag.setValue("foo");
this.tag.setLabel("Foo");
@@ -191,7 +201,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
}
}
public void testWithPropertyEditor() throws Exception {
@Test
public void withPropertyEditor() throws Exception {
String selectName = "testBean.stringArray";
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) {
@Override
@@ -219,7 +230,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
}
public void testWithPropertyEditorStringComparison() throws Exception {
@Test
public void withPropertyEditorStringComparison() throws Exception {
final PropertyEditor testBeanEditor = new TestBeanPropertyEditor();
testBeanEditor.setValue(new TestBean("Sally"));
String selectName = "testBean.spouse";
@@ -246,7 +258,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "Sally");
}
public void testWithCustomObjectSelected() throws Exception {
@Test
public void withCustomObjectSelected() throws Exception {
String selectName = "testBean.someNumber";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
this.tag.setValue(new Float(12.34));
@@ -265,7 +278,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "GBP 12.34");
}
public void testWithCustomObjectNotSelected() throws Exception {
@Test
public void withCustomObjectNotSelected() throws Exception {
String selectName = "testBean.someNumber";
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), selectName, false));
this.tag.setValue(new Float(12.35));
@@ -284,7 +298,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "GBP 12.35");
}
public void testWithCustomObjectAndEditorSelected() throws Exception {
@Test
public void withCustomObjectAndEditorSelected() throws Exception {
final PropertyEditor floatEditor = new SimpleFloatEditor();
floatEditor.setValue(new Float("12.34"));
String selectName = "testBean.someNumber";
@@ -311,7 +326,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "12.34f");
}
public void testWithCustomObjectAndEditorNotSelected() throws Exception {
@Test
public void withCustomObjectAndEditorNotSelected() throws Exception {
final PropertyEditor floatEditor = new SimpleFloatEditor();
String selectName = "testBean.someNumber";
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) {
@@ -337,7 +353,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, "12.35f");
}
public void testAsBodyTag() throws Exception {
@Test
public void asBodyTag() throws Exception {
String selectName = "testBean.name";
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
@@ -358,7 +375,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, bodyContent);
}
public void testAsBodyTagSelected() throws Exception {
@Test
public void asBodyTagSelected() throws Exception {
String selectName = "testBean.name";
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
@@ -378,7 +396,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, bodyContent);
}
public void testAsBodyTagCollapsed() throws Exception {
@Test
public void asBodyTagCollapsed() throws Exception {
String selectName = "testBean.name";
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false);
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
@@ -399,7 +418,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertBlockTagContains(output, bodyContent);
}
public void testAsBodyTagWithEditor() throws Exception {
@Test
public void asBodyTagWithEditor() throws Exception {
String selectName = "testBean.stringArray";
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) {
@Override
@@ -422,7 +442,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertEquals(Tag.EVAL_PAGE, result);
}
public void testMultiBind() throws Exception {
@Test
public void multiBind() throws Exception {
BeanPropertyBindingResult result = new BeanPropertyBindingResult(new TestBean(), "testBean");
result.getPropertyAccessor().registerCustomEditor(TestBean.class, "friends", new FriendEditor());
exposeBindingResult(result);
@@ -437,7 +458,8 @@ public class OptionTagTests extends AbstractHtmlElementTagTests {
assertEquals("<option value=\"foo\">foo</option>", getOutput());
}
public void testOptionTagNotNestedWithinSelectTag() throws Exception {
@Test
public void optionTagNotNestedWithinSelectTag() throws Exception {
try {
tag.setParent(null);
tag.setValue("foo");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,8 @@ import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockPageContext;
import org.springframework.tests.sample.beans.TestBean;
@@ -42,12 +44,15 @@ import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Scott Andrews
* @author Jeremy Grelle
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public final class OptionsTagTests extends AbstractHtmlElementTagTests {
private static final String COMMAND_NAME = "testBean";
@@ -81,7 +86,8 @@ public final class OptionsTagTests extends AbstractHtmlElementTagTests {
this.tag.setPageContext(getPageContext());
}
public void testWithCollection() throws Exception {
@Test
public void withCollection() throws Exception {
getPageContext().setAttribute(
SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.country", false));
@@ -110,7 +116,8 @@ public final class OptionsTagTests extends AbstractHtmlElementTagTests {
assertEquals("CLICK", element.attribute("onclick").getValue());
}
public void testWithCollectionAndDynamicAttributes() throws Exception {
@Test
public void withCollectionAndDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -147,7 +154,8 @@ public final class OptionsTagTests extends AbstractHtmlElementTagTests {
assertEquals(dynamicAttribute2, element.attribute(dynamicAttribute2).getValue());
}
public void testWithCollectionAndCustomEditor() throws Exception {
@Test
public void withCollectionAndCustomEditor() throws Exception {
PropertyEditor propertyEditor = new SimpleFloatEditor();
TestBean target = new TestBean();
@@ -192,7 +200,8 @@ public final class OptionsTagTests extends AbstractHtmlElementTagTests {
assertNull("No id rendered", element.attribute("id"));
}
public void testWithItemsNullReference() throws Exception {
@Test
public void withItemsNullReference() throws Exception {
getPageContext().setAttribute(
SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, new BindStatus(getRequestContext(), "testBean.country", false));
@@ -212,7 +221,8 @@ public final class OptionsTagTests extends AbstractHtmlElementTagTests {
assertEquals("Incorrect number of children", 0, children.size());
}
public void testWithoutItems() throws Exception {
@Test
public void withoutItems() throws Exception {
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
this.selectTag.setPath("testBean");
@@ -232,7 +242,8 @@ public final class OptionsTagTests extends AbstractHtmlElementTagTests {
assertEquals("Incorrect number of children", 0, children.size());
}
public void testWithoutItemsEnumParent() throws Exception {
@Test
public void withoutItemsEnumParent() throws Exception {
BeanWithEnum testBean = new BeanWithEnum();
testBean.setTestEnum(TestEnum.VALUE_2);
getPageContext().getRequest().setAttribute("testBean", testBean);
@@ -259,7 +270,8 @@ public final class OptionsTagTests extends AbstractHtmlElementTagTests {
assertEquals(value2, rootElement.selectSingleNode("option[@selected]"));
}
public void testWithoutItemsEnumParentWithExplicitLabelsAndValues() throws Exception {
@Test
public void withoutItemsEnumParentWithExplicitLabelsAndValues() throws Exception {
BeanWithEnum testBean = new BeanWithEnum();
testBean.setTestEnum(TestEnum.VALUE_2);
getPageContext().getRequest().setAttribute("testBean", testBean);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,10 @@ import java.io.Writer;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Rick Evans
@@ -27,10 +31,11 @@ import javax.servlet.jsp.tagext.Tag;
*/
public class PasswordInputTagTests extends InputTagTests {
/*
* http://opensource.atlassian.com/projects/spring/browse/SPR-2866
/**
* https://jira.spring.io/browse/SPR-2866
*/
public void testPasswordValueIsNotRenderedByDefault() throws Exception {
@Test
public void passwordValueIsNotRenderedByDefault() throws Exception {
this.getTag().setPath("name");
assertEquals(Tag.SKIP_BODY, this.getTag().doStartTag());
@@ -43,10 +48,11 @@ public class PasswordInputTagTests extends InputTagTests {
assertValueAttribute(output, "");
}
/*
* http://opensource.atlassian.com/projects/spring/browse/SPR-2866
/**
* https://jira.spring.io/browse/SPR-2866
*/
public void testPasswordValueIsRenderedIfShowPasswordAttributeIsSetToTrue() throws Exception {
@Test
public void passwordValueIsRenderedIfShowPasswordAttributeIsSetToTrue() throws Exception {
this.getTag().setPath("name");
this.getPasswordTag().setShowPassword(true);
@@ -60,10 +66,11 @@ public class PasswordInputTagTests extends InputTagTests {
assertValueAttribute(output, "Rob");
}
/*
* http://opensource.atlassian.com/projects/spring/browse/SPR-2866
/**
* https://jira.spring.io/browse/SPR-2866
*/
public void testPasswordValueIsNotRenderedIfShowPasswordAttributeIsSetToFalse() throws Exception {
@Test
public void passwordValueIsNotRenderedIfShowPasswordAttributeIsSetToFalse() throws Exception {
this.getTag().setPath("name");
this.getPasswordTag().setShowPassword(false);
@@ -77,8 +84,9 @@ public class PasswordInputTagTests extends InputTagTests {
assertValueAttribute(output, "");
}
@Test
@Override
public void testDynamicTypeAttribute() throws JspException {
public void dynamicTypeAttribute() throws JspException {
try {
this.getTag().setDynamicAttribute(null, "type", "email");
fail("Expected exception");
@@ -116,4 +124,5 @@ public class PasswordInputTagTests extends InputTagTests {
private PasswordInputTag getPasswordTag() {
return (PasswordInputTag) this.getTag();
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,11 +26,15 @@ import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.springframework.tests.sample.beans.Pet;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
@@ -54,7 +58,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
this.tag.setPageContext(getPageContext());
}
public void testWithCheckedValue() throws Exception {
@Test
public void withCheckedValue() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -77,7 +82,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
}
public void testWithCheckedValueAndDynamicAttributes() throws Exception {
@Test
public void withCheckedValueAndDynamicAttributes() throws Exception {
this.tag.setPath("sex");
this.tag.setValue("M");
int result = this.tag.doStartTag();
@@ -92,7 +98,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, "checked", "checked");
}
public void testWithCheckedObjectValue() throws Exception {
@Test
public void withCheckedObjectValue() throws Exception {
this.tag.setPath("myFloat");
this.tag.setValue(getFloat());
int result = this.tag.doStartTag();
@@ -107,7 +114,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, "checked", "checked");
}
public void testWithCheckedObjectValueAndEditor() throws Exception {
@Test
public void withCheckedObjectValueAndEditor() throws Exception {
this.tag.setPath("myFloat");
this.tag.setValue("F12.99");
@@ -128,7 +136,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, "checked", "checked");
}
public void testWithUncheckedObjectValue() throws Exception {
@Test
public void withUncheckedObjectValue() throws Exception {
Float value = new Float("99.45");
this.tag.setPath("myFloat");
this.tag.setValue(value);
@@ -144,7 +153,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertAttributeNotPresent(output, "checked");
}
public void testWithUncheckedValue() throws Exception {
@Test
public void withUncheckedValue() throws Exception {
this.tag.setPath("sex");
this.tag.setValue("F");
int result = this.tag.doStartTag();
@@ -159,7 +169,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertAttributeNotPresent(output, "checked");
}
public void testCollectionOfPets() throws Exception {
@Test
public void collectionOfPets() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Rudiger"));
@@ -181,7 +192,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testCollectionOfPetsNotSelected() throws Exception {
@Test
public void collectionOfPetsNotSelected() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new Pet("Santa's Little Helper"));
@@ -203,7 +215,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertNull(checkboxElement.attribute("checked"));
}
public void testCollectionOfPetsWithEditor() throws Exception {
@Test
public void collectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
this.tag.setValue(new ItemPet("Rudiger"));
@@ -230,7 +243,8 @@ public class RadioButtonTagTests extends AbstractFormTagTests {
assertEquals("checked", checkboxElement.attribute("checked").getValue());
}
public void testDynamicTypeAttribute() throws JspException {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,6 +34,8 @@ import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.tests.sample.beans.Colour;
import org.springframework.tests.sample.beans.Pet;
@@ -41,12 +43,15 @@ import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindingResult;
import static org.junit.Assert.*;
/**
* @author Thomas Risberg
* @author Juergen Hoeller
* @author Scott Andrews
* @author Jeremy Grelle
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public final class RadioButtonsTagTests extends AbstractFormTagTests {
private RadioButtonsTag tag;
@@ -65,7 +70,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
this.tag.setPageContext(getPageContext());
}
public void testWithMultiValueArray() throws Exception {
@Test
public void withMultiValueArray() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
int result = this.tag.doStartTag();
@@ -103,7 +109,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueArrayAndDynamicAttributes() throws Exception {
@Test
public void withMultiValueArrayAndDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -156,7 +163,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
}
public void testWithMultiValueArrayWithDelimiter() throws Exception {
@Test
public void withMultiValueArrayWithDelimiter() throws Exception {
this.tag.setDelimiter("<br/>");
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
@@ -201,7 +209,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals("baz", spanElement3.getStringValue());
}
public void testWithMultiValueMap() throws Exception {
@Test
public void withMultiValueMap() throws Exception {
this.tag.setPath("stringArray");
Map m = new LinkedHashMap();
m.put("foo", "FOO");
@@ -244,7 +253,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals("BAZ", spanElement3.getStringValue());
}
public void testWithMultiValueMapWithDelimiter() throws Exception {
@Test
public void withMultiValueMapWithDelimiter() throws Exception {
String delimiter = " | ";
this.tag.setDelimiter(delimiter);
this.tag.setPath("stringArray");
@@ -289,7 +299,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals(delimiter + "BAZ", spanElement3.getStringValue());
}
public void testWithMultiValueWithEditor() throws Exception {
@Test
public void withMultiValueWithEditor() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {" foo", " bar", " baz"});
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -331,7 +342,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals(" baz", radioButtonElement3.attribute("value").getValue());
}
public void testCollectionOfPets() throws Exception {
@Test
public void collectionOfPets() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
@@ -395,7 +407,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals("MUFTY", spanElement5.getStringValue());
}
public void testCollectionOfPetsWithEditor() throws Exception {
@Test
public void collectionOfPetsWithEditor() throws Exception {
this.tag.setPath("pets");
List allPets = new ArrayList();
allPets.add(new ItemPet("Rudiger"));
@@ -464,7 +477,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals("MUFTY", spanElement5.getStringValue());
}
public void testWithoutItemsEnumBindTarget() throws Exception {
@Test
public void withoutItemsEnumBindTarget() throws Exception {
BeanWithEnum testBean = new BeanWithEnum();
testBean.setTestEnum(TestEnum.VALUE_2);
getPageContext().getRequest().setAttribute("testBean", testBean);
@@ -486,7 +500,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals(value2, rootElement.selectSingleNode("//input[@checked]"));
}
public void testWithoutItemsEnumBindTargetWithExplicitLabelsAndValues() throws Exception {
@Test
public void withoutItemsEnumBindTargetWithExplicitLabelsAndValues() throws Exception {
BeanWithEnum testBean = new BeanWithEnum();
testBean.setTestEnum(TestEnum.VALUE_2);
getPageContext().getRequest().setAttribute("testBean", testBean);
@@ -510,7 +525,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals(value2, rootElement.selectSingleNode("//input[@checked]"));
}
public void testWithNullValue() throws Exception {
@Test
public void withNullValue() throws Exception {
try {
this.tag.setPath("name");
this.tag.doStartTag();
@@ -521,7 +537,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
}
}
public void testHiddenElementOmittedOnDisabled() throws Exception {
@Test
public void hiddenElementOmittedOnDisabled() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setDisabled(true);
@@ -546,7 +563,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals("foo", radioButtonElement.attribute("value").getValue());
}
public void testSpanElementCustomizable() throws Exception {
@Test
public void spanElementCustomizable() throws Exception {
this.tag.setPath("stringArray");
this.tag.setItems(new Object[] {"foo", "bar", "baz"});
this.tag.setElement("element");
@@ -563,7 +581,8 @@ public final class RadioButtonsTagTests extends AbstractFormTagTests {
assertEquals("element", spanElement.getName());
}
public void testDynamicTypeAttribute() throws JspException {
@Test
public void dynamicTypeAttribute() throws JspException {
try {
this.tag.setDynamicAttribute(null, "type", "email");
fail("Expected exception");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,6 +38,8 @@ import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.format.Formatter;
import org.springframework.format.support.FormattingConversionService;
@@ -47,12 +49,15 @@ import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.tags.TransformTag;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Jeremy Grelle
* @author Dave Syer
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class SelectTagTests extends AbstractFormTagTests {
private static final Locale LOCALE_AT = new Locale("de", "AT");
@@ -75,7 +80,8 @@ public class SelectTagTests extends AbstractFormTagTests {
this.tag.setPageContext(getPageContext());
}
public void testDynamicAttributes() throws JspException {
@Test
public void dynamicAttributes() throws JspException {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -94,7 +100,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, dynamicAttribute2, dynamicAttribute2);
}
public void testEmptyItems() throws Exception {
@Test
public void emptyItems() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Collections.EMPTY_LIST);
@@ -107,7 +114,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("<select id=\"country\" name=\"country\"></select>", output);
}
public void testNullItems() throws Exception {
@Test
public void nullItems() throws Exception {
this.tag.setPath("country");
this.tag.setItems(null);
@@ -120,19 +128,22 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("<select id=\"country\" name=\"country\"></select>", output);
}
public void testWithList() throws Exception {
@Test
public void withList() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
assertList(true);
}
public void testWithResolvedList() throws Exception {
@Test
public void withResolvedList() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
assertList(true);
}
public void testWithOtherValue() throws Exception {
@Test
public void withOtherValue() throws Exception {
TestBean tb = getTestBean();
tb.setCountry("AT");
this.tag.setPath("country");
@@ -140,7 +151,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertList(false);
}
public void testWithNullValue() throws Exception {
@Test
public void withNullValue() throws Exception {
TestBean tb = getTestBean();
tb.setCountry(null);
this.tag.setPath("country");
@@ -148,7 +160,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertList(false);
}
public void testWithListAndNoLabel() throws Exception {
@Test
public void withListAndNoLabel() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -157,7 +170,8 @@ public class SelectTagTests extends AbstractFormTagTests {
validateOutput(getOutput(), true);
}
public void testWithListAndTransformTag() throws Exception {
@Test
public void withListAndTransformTag() throws Exception {
this.tag.setPath("country");
this.tag.setItems(Country.getCountries());
assertList(true);
@@ -171,7 +185,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("Austria(AT)", getPageContext().findAttribute("key"));
}
public void testWithListAndTransformTagAndEditor() throws Exception {
@Test
public void withListAndTransformTagAndEditor() throws Exception {
this.tag.setPath("realCountry");
this.tag.setItems(Country.getCountries());
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean");
@@ -197,7 +212,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("Austria", getPageContext().findAttribute("key"));
}
public void testWithListAndEditor() throws Exception {
@Test
public void withListAndEditor() throws Exception {
this.tag.setPath("realCountry");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -221,7 +237,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertTrue(output.contains("option value=\"AT\" selected=\"selected\">Austria"));
}
public void testNestedPathWithListAndEditorAndNullValue() throws Exception {
@Test
public void nestedPathWithListAndEditorAndNullValue() throws Exception {
this.tag.setPath("bean.realCountry");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -259,7 +276,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertFalse(output.contains("multiple=\"multiple\""));
}
public void testNestedPathWithListAndEditor() throws Exception {
@Test
public void nestedPathWithListAndEditor() throws Exception {
this.tag.setPath("bean.realCountry");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -285,7 +303,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertTrue(output.contains("option value=\"AT\" selected=\"selected\">Austria"));
}
public void testWithListAndEditorAndNullValue() throws Exception {
@Test
public void withListAndEditorAndNullValue() throws Exception {
this.tag.setPath("realCountry");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -315,14 +334,16 @@ public class SelectTagTests extends AbstractFormTagTests {
assertFalse(output.contains("selected=\"selected\""));
}
public void testWithMap() throws Exception {
@Test
public void withMap() throws Exception {
this.tag.setPath("sex");
this.tag.setItems(getSexes());
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
}
public void testWithInvalidList() throws Exception {
@Test
public void withInvalidList() throws Exception {
this.tag.setPath("country");
this.tag.setItems(new TestBean());
this.tag.setItemValue("isoCode");
@@ -337,7 +358,8 @@ public class SelectTagTests extends AbstractFormTagTests {
}
}
public void testWithNestedOptions() throws Exception {
@Test
public void withNestedOptions() throws Exception {
this.tag.setPath("country");
int result = this.tag.doStartTag();
assertEquals(Tag.EVAL_BODY_INCLUDE, result);
@@ -355,19 +377,22 @@ public class SelectTagTests extends AbstractFormTagTests {
assertContainsAttribute(output, "name", "country");
}
public void testWithStringArray() throws Exception {
@Test
public void withStringArray() throws Exception {
this.tag.setPath("name");
this.tag.setItems(getNames());
assertStringArray();
}
public void testWithResolvedStringArray() throws Exception {
@Test
public void withResolvedStringArray() throws Exception {
this.tag.setPath("name");
this.tag.setItems(getNames());
assertStringArray();
}
public void testWithIntegerArray() throws Exception {
@Test
public void withIntegerArray() throws Exception {
this.tag.setPath("someIntegerArray");
Integer[] array = new Integer[50];
for (int i = 0; i < array.length; i++) {
@@ -399,7 +424,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("'34' node not selected", "selected", e.attribute("selected").getValue());
}
public void testWithFloatCustom() throws Exception {
@Test
public void withFloatCustom() throws Exception {
PropertyEditor propertyEditor = new SimpleFloatEditor();
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(getTestBean(), COMMAND_NAME);
errors.getPropertyAccessor().registerCustomEditor(Float.class, propertyEditor);
@@ -436,7 +462,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertNull("'12.32' node incorrectly selected", e.attribute("selected"));
}
public void testWithMultiList() throws Exception {
@Test
public void withMultiList() throws Exception {
List list = new ArrayList();
list.add(Country.COUNTRY_UK);
list.add(Country.COUNTRY_AT);
@@ -472,7 +499,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("Austria(AT)", e.getText());
}
public void testWithElementFormatter() throws Exception {
@Test
public void withElementFormatter() throws Exception {
this.bean.setRealCountry(Country.COUNTRY_UK);
BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
@@ -516,7 +544,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("United Kingdom", e.getText());
}
public void testWithMultiListAndElementFormatter() throws Exception {
@Test
public void withMultiListAndElementFormatter() throws Exception {
List list = new ArrayList();
list.add(Country.COUNTRY_UK);
list.add(Country.COUNTRY_AT);
@@ -567,7 +596,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("Austria", e.getText());
}
public void testWithMultiListAndCustomEditor() throws Exception {
@Test
public void withMultiListAndCustomEditor() throws Exception {
List list = new ArrayList();
list.add(Country.COUNTRY_UK);
list.add(Country.COUNTRY_AT);
@@ -610,7 +640,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("AT node not selected", "selected", e.attribute("selected").getValue());
}
public void testWithMultiMap() throws Exception {
@Test
public void withMultiMap() throws Exception {
Map someMap = new HashMap();
someMap.put("M", "Male");
someMap.put("F", "Female");
@@ -660,7 +691,8 @@ public class SelectTagTests extends AbstractFormTagTests {
* map's <em>value</em>.</li>
* </ul>
*/
public void testWithMultiMapWithItemValueAndItemLabel() throws Exception {
@Test
public void withMultiMapWithItemValueAndItemLabel() throws Exception {
// Save original default locale.
final Locale defaultLocale = Locale.getDefault();
// Use a locale that doesn't result in the generation of HTML entities
@@ -732,7 +764,8 @@ public class SelectTagTests extends AbstractFormTagTests {
}
}
public void testMultipleForCollection() throws Exception {
@Test
public void multipleForCollection() throws Exception {
this.bean.setSomeList(new ArrayList());
this.tag.setPath("someList");
@@ -761,7 +794,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertNotNull(inputElement);
}
public void testMultipleWithStringValue() throws Exception {
@Test
public void multipleWithStringValue() throws Exception {
this.tag.setPath("name");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -789,7 +823,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertNotNull(inputElement);
}
public void testMultipleExplicitlyTrue() throws Exception {
@Test
public void multipleExplicitlyTrue() throws Exception {
this.tag.setPath("name");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -817,7 +852,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertNotNull(inputElement);
}
public void testMultipleExplicitlyFalse() throws Exception {
@Test
public void multipleExplicitlyFalse() throws Exception {
this.tag.setPath("name");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -842,7 +878,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertEquals("Incorrect number of children", 4, children.size());
}
public void testMultipleWithBooleanTrue() throws Exception {
@Test
public void multipleWithBooleanTrue() throws Exception {
this.tag.setPath("name");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
@@ -870,7 +907,8 @@ public class SelectTagTests extends AbstractFormTagTests {
assertNotNull(inputElement);
}
public void testMultipleWithBooleanFalse() throws Exception {
@Test
public void multipleWithBooleanFalse() throws Exception {
this.tag.setPath("name");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,31 +16,35 @@
package org.springframework.web.servlet.tags.form;
import java.util.stream.IntStream;
import javax.servlet.jsp.PageContext;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.mock.web.test.MockPageContext;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Sam Brannen
* @since 2.0
*/
public class TagIdGeneratorTests extends TestCase {
public class TagIdGeneratorTests {
public void testNextId() throws Exception {
String name = "foo";
@Test
public void nextId() {
// Repeat a few times just to be sure...
IntStream.rangeClosed(1, 5).forEach(i -> assertNextId());
}
private void assertNextId() {
PageContext pageContext = new MockPageContext();
assertEquals("foo1", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo2", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo3", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo4", TagIdGenerator.nextId(name, pageContext));
assertEquals("bar1", TagIdGenerator.nextId("bar", pageContext));
pageContext = new MockPageContext();
assertEquals("foo1", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo2", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo3", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo4", TagIdGenerator.nextId(name, pageContext));
assertEquals("foo1", TagIdGenerator.nextId("foo", pageContext));
assertEquals("foo2", TagIdGenerator.nextId("foo", pageContext));
assertEquals("foo3", TagIdGenerator.nextId("foo", pageContext));
assertEquals("foo4", TagIdGenerator.nextId("foo", pageContext));
assertEquals("bar1", TagIdGenerator.nextId("bar", pageContext));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,34 +18,31 @@ package org.springframework.web.servlet.tags.form;
import java.io.StringWriter;
import junit.framework.TestCase;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Rick Evans
*/
public class TagWriterTests extends TestCase {
public class TagWriterTests {
private TagWriter writer;
private final StringWriter data = new StringWriter();
private StringWriter data;
private final TagWriter writer = new TagWriter(this.data);
@Override
protected void setUp() throws Exception {
this.data = new StringWriter();
this.writer = new TagWriter(this.data);
}
public void testSimpleTag() throws Exception {
@Test
public void simpleTag() throws Exception {
this.writer.startTag("br");
this.writer.endTag();
assertEquals("<br/>", this.data.toString());
}
public void testEmptyTag() throws Exception {
@Test
public void emptyTag() throws Exception {
this.writer.startTag("input");
this.writer.writeAttribute("type", "text");
this.writer.endTag();
@@ -53,7 +50,8 @@ public class TagWriterTests extends TestCase {
assertEquals("<input type=\"text\"/>", this.data.toString());
}
public void testSimpleBlockTag() throws Exception {
@Test
public void simpleBlockTag() throws Exception {
this.writer.startTag("textarea");
this.writer.appendValue("foobar");
this.writer.endTag();
@@ -61,7 +59,8 @@ public class TagWriterTests extends TestCase {
assertEquals("<textarea>foobar</textarea>", this.data.toString());
}
public void testBlockTagWithAttributes() throws Exception {
@Test
public void blockTagWithAttributes() throws Exception {
this.writer.startTag("textarea");
this.writer.writeAttribute("width", "10");
this.writer.writeAttribute("height", "20");
@@ -71,7 +70,8 @@ public class TagWriterTests extends TestCase {
assertEquals("<textarea width=\"10\" height=\"20\">foobar</textarea>", this.data.toString());
}
public void testNestedTags() throws Exception {
@Test
public void nestedTags() throws Exception {
this.writer.startTag("span");
this.writer.writeAttribute("style", "foo");
this.writer.startTag("strong");
@@ -82,7 +82,8 @@ public class TagWriterTests extends TestCase {
assertEquals("<span style=\"foo\"><strong>Rob Harrop</strong></span>", this.data.toString());
}
public void testMultipleNestedTags() throws Exception {
@Test
public void multipleNestedTags() throws Exception {
this.writer.startTag("span");
this.writer.writeAttribute("class", "highlight");
{
@@ -101,7 +102,8 @@ public class TagWriterTests extends TestCase {
assertEquals("<span class=\"highlight\"><strong>Rob</strong> <emphasis>Harrop</emphasis></span>", this.data.toString());
}
public void testWriteInterleavedWithForceBlock() throws Exception {
@Test
public void writeInterleavedWithForceBlock() throws Exception {
this.writer.startTag("span");
this.writer.forceBlock();
this.data.write("Rob Harrop"); // interleaved writing
@@ -110,7 +112,8 @@ public class TagWriterTests extends TestCase {
assertEquals("<span>Rob Harrop</span>", this.data.toString());
}
public void testAppendingValue() throws Exception {
@Test
public void appendingValue() throws Exception {
this.writer.startTag("span");
this.writer.appendValue("Rob ");
this.writer.appendValue("Harrop");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,9 +18,13 @@ package org.springframework.web.servlet.tags.form;
import javax.servlet.jsp.tagext.Tag;
import org.junit.Test;
import org.springframework.tests.sample.beans.TestBean;
import org.springframework.validation.BeanPropertyBindingResult;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Rick Evans
@@ -45,7 +49,8 @@ public class TextareaTagTests extends AbstractFormTagTests {
this.tag.setPageContext(getPageContext());
}
public void testSimpleBind() throws Exception {
@Test
public void simpleBind() throws Exception {
this.tag.setPath("name");
this.tag.setReadonly(true);
@@ -56,7 +61,8 @@ public class TextareaTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Rob");
}
public void testSimpleBindWithDynamicAttributes() throws Exception {
@Test
public void simpleBindWithDynamicAttributes() throws Exception {
String dynamicAttribute1 = "attr1";
String dynamicAttribute2 = "attr2";
@@ -74,7 +80,8 @@ public class TextareaTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, "Rob");
}
public void testComplexBind() throws Exception {
@Test
public void complexBind() throws Exception {
String onselect = "doSelect()";
this.tag.setPath("spouse.name");
@@ -87,7 +94,8 @@ public class TextareaTagTests extends AbstractFormTagTests {
assertAttributeNotPresent(output, "readonly");
}
public void testSimpleBindWithHtmlEscaping() throws Exception {
@Test
public void simpleBindWithHtmlEscaping() throws Exception {
final String NAME = "Rob \"I Love Mangos\" Harrop";
final String HTML_ESCAPED_NAME = "Rob &quot;I Love Mangos&quot; Harrop";
@@ -101,7 +109,8 @@ public class TextareaTagTests extends AbstractFormTagTests {
assertBlockTagContains(output, HTML_ESCAPED_NAME);
}
public void testCustomBind() throws Exception {
@Test
public void customBind() throws Exception {
BeanPropertyBindingResult result = new BeanPropertyBindingResult(createTestBean(), "testBean");
result.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
exposeBindingResult(result);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,19 +16,21 @@
package org.springframework.web.servlet.theme;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.servlet.ThemeResolver;
import static org.junit.Assert.*;
/**
* @author Jean-Pierre Pawlak
* @author Juergen Hoeller
* @since 19.06.2003
*/
public class ThemeResolverTests extends TestCase {
public class ThemeResolverTests {
private static final String TEST_THEME_NAME = "test.theme";
private static final String DEFAULT_TEST_THEME_NAME = "default.theme";
@@ -59,19 +61,23 @@ public class ThemeResolverTests extends TestCase {
}
}
public void testFixedThemeResolver() {
@Test
public void fixedThemeResolver() {
internalTest(new FixedThemeResolver(), false, AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME);
}
public void testCookieThemeResolver() {
@Test
public void cookieThemeResolver() {
internalTest(new CookieThemeResolver(), true, AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME);
}
public void testSessionThemeResolver() {
@Test
public void sessionThemeResolver() {
internalTest(new SessionThemeResolver(), true,AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME);
}
public void testSessionThemeResolverWithDefault() {
@Test
public void sessionThemeResolverWithDefault() {
SessionThemeResolver tr = new SessionThemeResolver();
tr.setDefaultThemeName(DEFAULT_TEST_THEME_NAME);
internalTest(tr, true, DEFAULT_TEST_THEME_NAME);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,15 +18,14 @@ package org.springframework.web.servlet.view;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.context.ApplicationContextException;
import org.springframework.mock.web.test.MockHttpServletRequest;
@@ -35,17 +34,22 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.View;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/**
* Tests for AbstractView. Not called AbstractViewTests as
* would otherwise be excluded by Ant build script wildcard.
* Base tests for {@link AbstractView}.
*
* <p>Not called {@code AbstractViewTests} since doing so would cause it
* to be ignored in the Gradle build.
*
* @author Rod Johnson
* @author Sam Brannen
*/
public class BaseViewTests extends TestCase {
public class BaseViewTests {
public void testRenderWithoutStaticAttributes() throws Exception {
@Test
public void renderWithoutStaticAttributes() throws Exception {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getServletContext()).willReturn(new MockServletContext());
@@ -62,16 +66,16 @@ public class BaseViewTests extends TestCase {
model.put("something", new Object());
tv.render(model, request, response);
// check it contains all
checkContainsAll(model, tv.model);
assertTrue(tv.inited);
assertTrue(tv.initialized);
}
/**
* Test attribute passing, NOT CSV parsing.
*/
public void testRenderWithStaticAttributesNoCollision() throws Exception {
@Test
public void renderWithStaticAttributesNoCollision() throws Exception {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getServletContext()).willReturn(new MockServletContext());
@@ -90,14 +94,14 @@ public class BaseViewTests extends TestCase {
model.put("two", new Object());
tv.render(model, request, response);
// Check it contains all
checkContainsAll(model, tv.model);
checkContainsAll(p, tv.model);
assertTrue(tv.inited);
assertTrue(tv.initialized);
}
public void testPathVarsOverrideStaticAttributes() throws Exception {
@Test
public void pathVarsOverrideStaticAttributes() throws Exception {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getServletContext()).willReturn(new MockServletContext());
@@ -119,16 +123,15 @@ public class BaseViewTests extends TestCase {
tv.render(new HashMap<String, Object>(), request, response);
// Check it contains all
checkContainsAll(pathVars, tv.model);
assertTrue(tv.model.size() == 3);
// will have old something from properties
assertTrue(tv.model.get("something").equals("else"));
assertTrue(tv.inited);
assertEquals(3, tv.model.size());
assertEquals("else", tv.model.get("something"));
assertTrue(tv.initialized);
}
public void testDynamicModelOverridesStaticAttributesIfCollision() throws Exception {
@Test
public void dynamicModelOverridesStaticAttributesIfCollision() throws Exception {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getServletContext()).willReturn(new MockServletContext());
@@ -149,14 +152,14 @@ public class BaseViewTests extends TestCase {
// Check it contains all
checkContainsAll(model, tv.model);
assertTrue(tv.model.size() == 3);
// will have old something from properties
assertTrue(tv.model.get("something").equals("else"));
assertTrue(tv.inited);
assertEquals(3, tv.model.size());
assertEquals("else", tv.model.get("something"));
assertTrue(tv.initialized);
}
public void testDynamicModelOverridesPathVariables() throws Exception {
@Test
public void dynamicModelOverridesPathVariables() throws Exception {
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getServletContext()).willReturn(new MockServletContext());
@@ -177,40 +180,41 @@ public class BaseViewTests extends TestCase {
tv.render(model, request, response);
// Check it contains all
checkContainsAll(model, tv.model);
assertEquals(3, tv.model.size());
// will have old something from path variables
assertTrue(tv.model.get("something").equals("else"));
assertTrue(tv.inited);
assertEquals("else", tv.model.get("something"));
assertTrue(tv.initialized);
}
public void testIgnoresNullAttributes() {
@Test
public void ignoresNullAttributes() {
AbstractView v = new ConcreteView();
v.setAttributes(null);
assertTrue(v.getStaticAttributes().size() == 0);
assertEquals(0, v.getStaticAttributes().size());
}
/**
* Test only the CSV parsing implementation.
*/
public void testAttributeCSVParsingIgnoresNull() {
@Test
public void attributeCSVParsingIgnoresNull() {
AbstractView v = new ConcreteView();
v.setAttributesCSV(null);
assertTrue(v.getStaticAttributes().size() == 0);
assertEquals(0, v.getStaticAttributes().size());
}
public void testAttributeCSVParsingIgnoresEmptyString() {
@Test
public void attributeCSVParsingIgnoresEmptyString() {
AbstractView v = new ConcreteView();
v.setAttributesCSV("");
assertTrue(v.getStaticAttributes().size() == 0);
assertEquals(0, v.getStaticAttributes().size());
}
/**
* Format is attname0={value1},attname1={value1}
*/
public void testAttributeCSVParsingValid() {
@Test
public void attributeCSVParsingValid() {
AbstractView v = new ConcreteView();
v.setAttributesCSV("foo=[bar],king=[kong]");
assertTrue(v.getStaticAttributes().size() == 2);
@@ -218,7 +222,8 @@ public class BaseViewTests extends TestCase {
assertTrue(v.getStaticAttributes().get("king").equals("kong"));
}
public void testAttributeCSVParsingValidWithWeirdCharacters() {
@Test
public void attributeCSVParsingValidWithWeirdCharacters() {
AbstractView v = new ConcreteView();
String fooval = "owfie fue&3[][[[2 \n\n \r \t 8\ufffd3";
// Also tests empty value
@@ -229,7 +234,8 @@ public class BaseViewTests extends TestCase {
assertTrue(v.getStaticAttributes().get("king").equals(kingval));
}
public void testAttributeCSVParsingInvalid() {
@Test
public void attributeCSVParsingInvalid() {
AbstractView v = new ConcreteView();
try {
// No equals
@@ -263,32 +269,29 @@ public class BaseViewTests extends TestCase {
}
}
public void testAttributeCSVParsingIgoresTrailingComma() {
@Test
public void attributeCSVParsingIgoresTrailingComma() {
AbstractView v = new ConcreteView();
v.setAttributesCSV("foo=[de],");
assertTrue(v.getStaticAttributes().size() == 1);
assertEquals(1, v.getStaticAttributes().size());
}
/**
* Check that all keys in expected have same values in actual
* @param expected
* @param actual
* Check that all keys in expected have same values in actual.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private void checkContainsAll(Map expected, Map<String, Object> actual) {
Set<String> keys = expected.keySet();
for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
String key = iter.next();
//System.out.println("Checking model key " + key);
assertTrue("Value for model key '" + key + "' must match", actual.get(key) == expected.get(key));
}
expected.keySet().stream().forEach(
key -> assertEquals("Values for model key '" + key + "' must match", expected.get(key), actual.get(key))
);
}
/**
* Trivial concrete subclass we can use when we're interested only
* in CSV parsing, which doesn't require lifecycle management
*/
private class ConcreteView extends AbstractView {
private static class ConcreteView extends AbstractView {
// Do-nothing concrete subclass
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
@@ -297,38 +300,40 @@ public class BaseViewTests extends TestCase {
}
}
/**
* Single threaded subclass of AbstractView to check superclass
* behaviour
* Single threaded subclass of AbstractView to check superclass behavior.
*/
private class TestView extends AbstractView {
private WebApplicationContext wac;
public boolean inited;
private static class TestView extends AbstractView {
private final WebApplicationContext wac;
boolean initialized;
/** Captured model in render */
public Map<String, Object> model;
Map<String, Object> model;
public TestView(WebApplicationContext wac) {
TestView(WebApplicationContext wac) {
this.wac = wac;
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// do nothing
this.model = model;
}
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.model = model;
}
/**
* @see org.springframework.context.support.ApplicationObjectSupport#initApplicationContext()
*/
@Override
protected void initApplicationContext() throws ApplicationContextException {
if (inited)
if (initialized) {
throw new RuntimeException("Already initialized");
this.inited = true;
}
this.initialized = true;
assertTrue(getApplicationContext() == wac);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,12 @@
package org.springframework.web.servlet.view;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
@@ -29,43 +30,49 @@ import org.springframework.mock.web.test.MockServletContext;
import org.springframework.web.servlet.View;
import org.springframework.web.util.WebUtils;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/**
* Unit tests for {@link InternalResourceView}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
*/
public class InternalResourceViewTests extends TestCase {
public class InternalResourceViewTests {
@SuppressWarnings("serial")
private static final Map<String, Object> model = Collections.unmodifiableMap(new HashMap<String, Object>() {{
put("foo", "bar");
put("I", 1L);
}});
private static final String url = "forward-to";
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final MockHttpServletResponse response = new MockHttpServletResponse();
private final InternalResourceView view = new InternalResourceView();
/**
* Test that if the url property isn't supplied, view initialization fails.
* If the url property isn't supplied, view initialization should fail.
*/
public void testRejectsNullUrl() throws Exception {
InternalResourceView view = new InternalResourceView();
try {
view.afterPropertiesSet();
fail("Should be forced to set URL");
}
catch (IllegalArgumentException ex) {
// expected
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullUrl() throws Exception {
view.afterPropertiesSet();
}
public void testForward() throws Exception {
HashMap<String, Object> model = new HashMap<String, Object>();
Object obj = 1;
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
@Test
public void forward() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myservlet/handler.do");
request.setContextPath("/mycontext");
request.setServletPath("/myservlet");
request.setPathInfo(";mypathinfo");
request.setQueryString("?param1=value1");
InternalResourceView view = new InternalResourceView();
view.setUrl(url);
view.setServletContext(new MockServletContext() {
@Override
@@ -74,98 +81,58 @@ public class InternalResourceViewTests extends TestCase {
}
});
MockHttpServletResponse response = new MockHttpServletResponse();
view.render(model, request, response);
assertEquals(url, response.getForwardedUrl());
Set<String> keys = model.keySet();
for (String key : keys) {
assertEquals(model.get(key), request.getAttribute(key));
}
model.keySet().stream().forEach(
key -> assertEquals("Values for model key '" + key + "' must match", model.get(key), request.getAttribute(key))
);
}
public void testAlwaysInclude() throws Exception {
HashMap<String, Object> model = new HashMap<String, Object>();
Object obj = 1;
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
HttpServletRequest request = mock(HttpServletRequest.class);
@Test
public void alwaysInclude() throws Exception {
given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null);
given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url));
MockHttpServletResponse response = new MockHttpServletResponse();
InternalResourceView v = new InternalResourceView();
v.setUrl(url);
v.setAlwaysInclude(true);
view.setUrl(url);
view.setAlwaysInclude(true);
// Can now try multiple tests
v.render(model, request, response);
view.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
Set<String> keys = model.keySet();
for (String key : keys) {
verify(request).setAttribute(key, model.get(key));
}
model.keySet().stream().forEach(key -> verify(request).setAttribute(key, model.get(key)));
}
public void testIncludeOnAttribute() throws Exception {
HashMap<String, Object> model = new HashMap<String, Object>();
Object obj = 1;
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
HttpServletRequest request = mock(HttpServletRequest.class);
@Test
public void includeOnAttribute() throws Exception {
given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null);
given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn("somepath");
given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url));
MockHttpServletResponse response = new MockHttpServletResponse();
InternalResourceView v = new InternalResourceView();
v.setUrl(url);
view.setUrl(url);
// Can now try multiple tests
v.render(model, request, response);
view.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
Set<String> keys = model.keySet();
for (String key : keys) {
verify(request).setAttribute(key, model.get(key));
}
model.keySet().stream().forEach(key -> verify(request).setAttribute(key, model.get(key)));
}
public void testIncludeOnCommitted() throws Exception {
HashMap<String, Object> model = new HashMap<String, Object>();
Object obj = 1;
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
HttpServletRequest request = mock(HttpServletRequest.class);
@Test
public void includeOnCommitted() throws Exception {
given(request.getAttribute(View.PATH_VARIABLES)).willReturn(null);
given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn(null);
given(request.getRequestDispatcher(url)).willReturn(new MockRequestDispatcher(url));
MockHttpServletResponse response = new MockHttpServletResponse();
response.setCommitted(true);
InternalResourceView v = new InternalResourceView();
v.setUrl(url);
view.setUrl(url);
// Can now try multiple tests
v.render(model, request, response);
view.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
Set<String> keys = model.keySet();
for (String key : keys) {
verify(request).setAttribute(key, model.get(key));
}
model.keySet().stream().forEach(key -> verify(request).setAttribute(key, model.get(key)));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,10 +19,12 @@ package org.springframework.web.servlet.view;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanIsAbstractException;
import org.springframework.core.io.Resource;
@@ -31,28 +33,32 @@ import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.View;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.junit.Assume.*;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
*/
public class ResourceBundleViewResolverTests extends TestCase {
public class ResourceBundleViewResolverTests {
/** Comes from this package */
private static String PROPS_FILE = "org.springframework.web.servlet.view.testviews";
private ResourceBundleViewResolver rb;
private final ResourceBundleViewResolver rb = new ResourceBundleViewResolver();
private StaticWebApplicationContext wac;
private final StaticWebApplicationContext wac = new StaticWebApplicationContext();
@Override
protected void setUp() throws Exception {
rb = new ResourceBundleViewResolver();
@Before
public void setUp() throws Exception {
rb.setBasename(PROPS_FILE);
rb.setCache(getCache());
rb.setDefaultParentView("testParent");
wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext());
wac.refresh();
@@ -69,7 +75,8 @@ public class ResourceBundleViewResolverTests extends TestCase {
}
public void testParentsAreAbstract() throws Exception {
@Test
public void parentsAreAbstract() throws Exception {
try {
rb.resolveViewName("debug.Parent", Locale.ENGLISH);
fail("Should have thrown BeanIsAbstractException");
@@ -86,31 +93,32 @@ public class ResourceBundleViewResolverTests extends TestCase {
}
}
public void testDebugViewEnglish() throws Exception {
@Test
public void debugViewEnglish() throws Exception {
View v = rb.resolveViewName("debugView", Locale.ENGLISH);
assertTrue("debugView must be of type InternalResourceView", v instanceof InternalResourceView);
assertThat(v, instanceOf(InternalResourceView.class));
InternalResourceView jv = (InternalResourceView) v;
assertTrue("debugView must have correct URL", "jsp/debug/debug.jsp".equals(jv.getUrl()));
assertEquals("debugView must have correct URL", "jsp/debug/debug.jsp", jv.getUrl());
Map m = jv.getStaticAttributes();
assertTrue("Must have 2 static attributes, not " + m.size(), m.size() == 2);
assertTrue("attribute foo = bar, not '" + m.get("foo") + "'", m.get("foo").equals("bar"));
assertTrue("attribute postcode = SE10 9JY", m.get("postcode").equals("SE10 9JY"));
Map<String, Object> m = jv.getStaticAttributes();
assertEquals("Must have 2 static attributes", 2, m.size());
assertEquals("attribute foo", "bar", m.get("foo"));
assertEquals("attribute postcode", "SE10 9JY", m.get("postcode"));
assertTrue("Correct default content type", jv.getContentType().equals(AbstractView.DEFAULT_CONTENT_TYPE));
assertEquals("Correct default content type", AbstractView.DEFAULT_CONTENT_TYPE, jv.getContentType());
}
public void testDebugViewFrench() throws Exception {
@Test
public void debugViewFrench() throws Exception {
View v = rb.resolveViewName("debugView", Locale.FRENCH);
assertTrue("French debugView must be of type InternalResourceView", v instanceof InternalResourceView);
assertThat(v, instanceOf(InternalResourceView.class));
InternalResourceView jv = (InternalResourceView) v;
assertTrue("French debugView must have correct URL", "jsp/debug/deboug.jsp".equals(jv.getUrl()));
assertTrue(
"Correct overridden (XML) content type, not '" + jv.getContentType() + "'",
jv.getContentType().equals("text/xml;charset=ISO-8859-1"));
assertEquals("French debugView must have correct URL", "jsp/debug/deboug.jsp", jv.getUrl());
assertEquals("Correct overridden (XML) content type", "text/xml;charset=ISO-8859-1", jv.getContentType());
}
public void testEagerInitialization() throws Exception {
@Test
public void eagerInitialization() throws Exception {
ResourceBundleViewResolver rb = new ResourceBundleViewResolver();
rb.setBasename(PROPS_FILE);
rb.setCache(getCache());
@@ -119,48 +127,43 @@ public class ResourceBundleViewResolverTests extends TestCase {
rb.setApplicationContext(wac);
View v = rb.resolveViewName("debugView", Locale.FRENCH);
assertTrue("French debugView must be of type InternalResourceView", v instanceof InternalResourceView);
assertThat(v, instanceOf(InternalResourceView.class));
InternalResourceView jv = (InternalResourceView) v;
assertTrue("French debugView must have correct URL", "jsp/debug/deboug.jsp".equals(jv.getUrl()));
assertTrue(
"Correct overridden (XML) content type, not '" + jv.getContentType() + "'",
jv.getContentType().equals("text/xml;charset=ISO-8859-1"));
assertEquals("French debugView must have correct URL", "jsp/debug/deboug.jsp", jv.getUrl());
assertEquals("Correct overridden (XML) content type", "text/xml;charset=ISO-8859-1", jv.getContentType());
}
public void testSameBundleOnlyCachedOnce() throws Exception {
if (rb.isCache()) {
View v1 = rb.resolveViewName("debugView", Locale.ENGLISH);
View v2 = rb.resolveViewName("debugView", Locale.UK);
assertSame(v1, v2);
}
@Test
public void sameBundleOnlyCachedOnce() throws Exception {
assumeTrue(rb.isCache());
View v1 = rb.resolveViewName("debugView", Locale.ENGLISH);
View v2 = rb.resolveViewName("debugView", Locale.UK);
assertSame(v1, v2);
}
public void testNoSuchViewEnglish() throws Exception {
View v = rb.resolveViewName("xxxxxxweorqiwuopeir", Locale.ENGLISH);
assertTrue(v == null);
@Test
public void noSuchViewEnglish() throws Exception {
assertNull(rb.resolveViewName("xxxxxxweorqiwuopeir", Locale.ENGLISH));
}
public void testOnSetContextCalledOnce() throws Exception {
@Test
public void onSetContextCalledOnce() throws Exception {
TestView tv = (TestView) rb.resolveViewName("test", Locale.ENGLISH);
tv = (TestView) rb.resolveViewName("test", Locale.ENGLISH);
tv = (TestView) rb.resolveViewName("test", Locale.ENGLISH);
assertTrue("test has correct name", "test".equals(tv.getBeanName()));
assertTrue("test should have been initialized once, not " + tv.initCount + " times", tv.initCount == 1);
assertEquals("test has correct name", "test", tv.getBeanName());
assertEquals("test should have been initialized once, not ", 1, tv.initCount);
}
public void testNoSuchBasename() throws Exception {
try {
rb.setBasename("weoriwoierqupowiuer");
rb.resolveViewName("debugView", Locale.ENGLISH);
fail("No such basename: all requests should fail with exception");
}
catch (MissingResourceException ex) {
// OK
}
@Test(expected = MissingResourceException.class)
public void noSuchBasename() throws Exception {
rb.setBasename("weoriwoierqupowiuer");
rb.resolveViewName("debugView", Locale.ENGLISH);
}
public static class TestView extends AbstractView {
static class TestView extends AbstractView {
public int initCount;
@@ -171,7 +174,8 @@ public class ResourceBundleViewResolverTests extends TestCase {
}
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) {
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) {
}
@Override

View File

@@ -18,17 +18,20 @@ package org.springframework.web.servlet.view.jasperreports;
import java.util.Locale;
import junit.framework.TestCase;
import org.junit.Test;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.web.servlet.view.velocity.VelocityView;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
*/
public class JasperReportViewResolverTests extends TestCase {
public class JasperReportViewResolverTests {
public void testResolveView() throws Exception {
@Test
public void resolveView() throws Exception {
StaticApplicationContext ctx = new StaticApplicationContext();
String prefix = "org/springframework/ui/jasperreports/";
@@ -47,7 +50,8 @@ public class JasperReportViewResolverTests extends TestCase {
assertEquals("Incorrect URL", prefix + viewName + suffix, view.getUrl());
}
public void testSetIncorrectViewClass() {
@Test
public void setIncorrectViewClass() {
try {
new JasperReportsViewResolver().setViewClass(VelocityView.class);
fail("Should not be able to set view class to a class that does not extend AbstractJasperReportsView");
@@ -57,15 +61,18 @@ public class JasperReportViewResolverTests extends TestCase {
}
}
public void testWithViewNamesAndEndsWithPattern() throws Exception {
@Test
public void withViewNamesAndEndsWithPattern() throws Exception {
doViewNamesTest(new String[]{"DataSource*"});
}
public void testWithViewNamesAndStartsWithPattern() throws Exception {
@Test
public void withViewNamesAndStartsWithPattern() throws Exception {
doViewNamesTest(new String[]{"*Report"});
}
public void testWithViewNamesAndStatic() throws Exception {
@Test
public void withViewNamesAndStatic() throws Exception {
doViewNamesTest(new String[]{"DataSourceReport"});
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,9 +27,9 @@ import org.apache.velocity.exception.ResourceNotFoundException;
* @author Juergen Hoeller
* @since 09.10.2004
*/
public class TestVelocityEngine extends VelocityEngine {
class TestVelocityEngine extends VelocityEngine {
private final Map templates = new HashMap();
private final Map<String, Template> templates = new HashMap<>();
public TestVelocityEngine() {
@@ -46,7 +46,7 @@ public class TestVelocityEngine extends VelocityEngine {
@Override
public Template getTemplate(String name) throws ResourceNotFoundException {
Template template = (Template) this.templates.get(name);
Template template = this.templates.get(name);
if (template == null) {
throw new ResourceNotFoundException("No template registered for name [" + name + "]");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,15 +19,17 @@ package org.springframework.web.servlet.view.velocity;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import junit.framework.TestCase;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.DescriptiveResource;
import org.springframework.core.io.FileSystemResource;
@@ -44,9 +46,10 @@ import static org.junit.Assert.*;
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class VelocityConfigurerTests extends TestCase {
public class VelocityConfigurerTests {
public void testVelocityEngineFactoryBeanWithConfigLocation() throws VelocityException {
@Test
public void velocityEngineFactoryBeanWithConfigLocation() throws VelocityException {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
vefb.setConfigLocation(new FileSystemResource("myprops.properties"));
Properties props = new Properties();
@@ -61,13 +64,14 @@ public class VelocityConfigurerTests extends TestCase {
}
}
public void testVelocityEngineFactoryBeanWithVelocityProperties() throws VelocityException, IOException {
@Test
public void velocityEngineFactoryBeanWithVelocityProperties() throws VelocityException, IOException {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
Properties props = new Properties();
props.setProperty("myprop", "/mydir");
vefb.setVelocityProperties(props);
Object value = new Object();
Map map = new HashMap();
Map<String, Object> map = new HashMap<>();
map.put("myentry", value);
vefb.setVelocityPropertiesMap(map);
vefb.afterPropertiesSet();
@@ -77,7 +81,8 @@ public class VelocityConfigurerTests extends TestCase {
assertEquals(value, ve.getProperty("myentry"));
}
public void testVelocityEngineFactoryBeanWithResourceLoaderPath() throws IOException, VelocityException {
@Test
public void velocityEngineFactoryBeanWithResourceLoaderPath() throws IOException, VelocityException {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
vefb.setResourceLoaderPath("file:/mydir");
vefb.afterPropertiesSet();
@@ -86,7 +91,9 @@ public class VelocityConfigurerTests extends TestCase {
assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
}
public void testVelocityEngineFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
@Test
@SuppressWarnings("deprecation")
public void velocityEngineFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
vefb.setResourceLoaderPath("file:/mydir");
vefb.setResourceLoader(new ResourceLoader() {
@@ -110,10 +117,11 @@ public class VelocityConfigurerTests extends TestCase {
vefb.afterPropertiesSet();
assertThat(vefb.getObject(), instanceOf(VelocityEngine.class));
VelocityEngine ve = vefb.getObject();
assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap()));
assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", Collections.emptyMap()));
}
public void testVelocityConfigurer() throws IOException, VelocityException {
@Test
public void velocityConfigurer() throws IOException, VelocityException {
VelocityConfigurer vc = new VelocityConfigurer();
vc.setResourceLoaderPath("file:/mydir");
vc.afterPropertiesSet();
@@ -122,19 +130,22 @@ public class VelocityConfigurerTests extends TestCase {
assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
}
public void testVelocityConfigurerWithCsvPath() throws IOException, VelocityException {
@Test
public void velocityConfigurerWithCsvPath() throws IOException, VelocityException {
VelocityConfigurer vc = new VelocityConfigurer();
vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
vc.afterPropertiesSet();
assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class));
VelocityEngine ve = vc.createVelocityEngine();
Vector paths = new Vector();
Vector<String> paths = new Vector<>();
paths.add(new File("/mydir").getAbsolutePath());
paths.add(new File("/yourdir").getAbsolutePath());
assertEquals(paths, ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
}
public void testVelocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException {
@Test
@SuppressWarnings("deprecation")
public void velocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException {
VelocityConfigurer vc = new VelocityConfigurer();
vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
vc.setResourceLoader(new ResourceLoader() {
@@ -154,7 +165,7 @@ public class VelocityConfigurerTests extends TestCase {
vc.afterPropertiesSet();
assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class));
VelocityEngine ve = vc.createVelocityEngine();
assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap()));
assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", Collections.emptyMap()));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,11 +21,13 @@ import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.mock.web.test.MockServletContext;
@@ -39,16 +41,17 @@ import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.theme.FixedThemeResolver;
import org.springframework.web.servlet.view.DummyMacroRequestContext;
import static org.junit.Assert.*;
/**
* @author Darren Davison
* @author Juergen Hoeller
* @since 18.06.2004
*/
public class VelocityMacroTests extends TestCase {
public class VelocityMacroTests {
private static final String TEMPLATE_FILE = "test.vm";
private StaticWebApplicationContext wac;
private MockHttpServletRequest request;
@@ -56,7 +59,7 @@ public class VelocityMacroTests extends TestCase {
private MockHttpServletResponse response;
@Override
@Before
public void setUp() throws Exception {
wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext());
@@ -78,7 +81,8 @@ public class VelocityMacroTests extends TestCase {
response = new MockHttpServletResponse();
}
public void testExposeSpringMacroHelpers() throws Exception {
@Test
public void exposeSpringMacroHelpers() throws Exception {
VelocityView vv = new VelocityView() {
@Override
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
@@ -98,7 +102,8 @@ public class VelocityMacroTests extends TestCase {
vv.render(model, request, response);
}
public void testSpringMacroRequestContextAttributeUsed() {
@Test
public void springMacroRequestContextAttributeUsed() {
final String helperTool = "wrongType";
VelocityView vv = new VelocityView() {
@@ -123,7 +128,8 @@ public class VelocityMacroTests extends TestCase {
}
}
public void testAllMacros() throws Exception {
@Test
public void allMacros() throws Exception {
DummyMacroRequestContext rc = new DummyMacroRequestContext(request);
Map<String, String> msgMap = new HashMap<String, String>();
msgMap.put("hello", "Howdy");
@@ -192,7 +198,8 @@ public class VelocityMacroTests extends TestCase {
// SPR-5172
public void testIdContainsBraces() throws Exception {
@Test
public void idContainsBraces() throws Exception {
DummyMacroRequestContext rc = new DummyMacroRequestContext(request);
Map<String, String> msgMap = new HashMap<String, String>();
msgMap.put("hello", "Howdy");

View File

@@ -16,9 +16,11 @@
package org.springframework.web.servlet.view.xslt;
import org.junit.Test;
import java.util.Locale;
import junit.framework.TestCase;
import static org.junit.Assert.*;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.util.ClassUtils;
@@ -27,9 +29,10 @@ import org.springframework.util.ClassUtils;
* @author Rob Harrop
* @since 2.0
*/
public class XsltViewResolverTests extends TestCase {
public class XsltViewResolverTests {
public void testResolveView() throws Exception {
@Test
public void resolveView() throws Exception {
StaticApplicationContext ctx = new StaticApplicationContext();
String prefix = ClassUtils.classPackageAsResourcePath(getClass());

View File

@@ -31,9 +31,8 @@ import javax.xml.transform.stream.StreamSource;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.core.io.ClassPathResource;
@@ -41,30 +40,29 @@ import org.springframework.core.io.Resource;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.xml.sax.SAXException;
import static java.util.Collections.*;
import static org.junit.Assert.*;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Sam Brannen
*/
public class XsltViewTests {
private static final String HTML_OUTPUT = "/org/springframework/web/servlet/view/xslt/products.xsl";
private MockHttpServletRequest request;
private final MockHttpServletRequest request = new MockHttpServletRequest();
private MockHttpServletResponse response;
private final MockHttpServletResponse response = new MockHttpServletResponse();
@Before
public void setUp() throws Exception {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
}
@Test(expected = IllegalArgumentException.class)
public void withNoSource() throws Exception {
final XsltView view = getXsltView(HTML_OUTPUT);
view.render(new HashMap(), request, response);
view.render(emptyMap(), request, response);
}
@Test(expected = IllegalArgumentException.class)
@@ -76,46 +74,34 @@ public class XsltViewTests {
@Test
public void simpleTransformWithSource() throws Exception {
Source source = new StreamSource(getProductDataResource().getInputStream());
Map model = new HashMap();
model.put("someKey", source);
doTestWithModel(model);
doTestWithModel(singletonMap("someKey", source));
}
@Test
public void testSimpleTransformWithDocument() throws Exception {
org.w3c.dom.Document document = getDomDocument();
Map model = new HashMap();
model.put("someKey", document);
doTestWithModel(model);
doTestWithModel(singletonMap("someKey", document));
}
@Test
public void testSimpleTransformWithNode() throws Exception {
org.w3c.dom.Document document = getDomDocument();
Map model = new HashMap();
model.put("someKey", document.getDocumentElement());
doTestWithModel(model);
doTestWithModel(singletonMap("someKey", document.getDocumentElement()));
}
@Test
public void testSimpleTransformWithInputStream() throws Exception {
Map model = new HashMap();
model.put("someKey", getProductDataResource().getInputStream());
doTestWithModel(model);
doTestWithModel(singletonMap("someKey", getProductDataResource().getInputStream()));
}
@Test
public void testSimpleTransformWithReader() throws Exception {
Map model = new HashMap();
model.put("someKey", new InputStreamReader(getProductDataResource().getInputStream()));
doTestWithModel(model);
doTestWithModel(singletonMap("someKey", new InputStreamReader(getProductDataResource().getInputStream())));
}
@Test
public void testSimpleTransformWithResource() throws Exception {
Map model = new HashMap();
model.put("someKey", getProductDataResource());
doTestWithModel(model);
doTestWithModel(singletonMap("someKey", getProductDataResource()));
}
@Test
@@ -123,7 +109,7 @@ public class XsltViewTests {
XsltView view = getXsltView(HTML_OUTPUT);
view.setSourceKey("actualData");
Map model = new HashMap();
Map<String, Object> model = new HashMap<>();
model.put("actualData", getProductDataResource());
model.put("otherData", new ClassPathResource("dummyData.xsl", getClass()));
@@ -136,17 +122,14 @@ public class XsltViewTests {
XsltView view = getXsltView(HTML_OUTPUT);
Source source = new StreamSource(getProductDataResource().getInputStream());
Map model = new HashMap();
model.put("someKey", source);
view.render(model, this.request, this.response);
view.render(singletonMap("someKey", source), this.request, this.response);
assertTrue(this.response.getContentType().startsWith("text/html"));
assertEquals("UTF-8", this.response.getCharacterEncoding());
}
@Test
public void testModelParametersCarriedAcross() throws Exception {
Map model = new HashMap();
Map<String, Object> model = new HashMap<>();
model.put("someKey", getProductDataResource());
model.put("title", "Product List");
doTestWithModel(model);
@@ -159,7 +142,7 @@ public class XsltViewTests {
view.setSourceKey("actualData");
view.addStaticAttribute("title", "Product List");
Map model = new HashMap();
Map<String, Object> model = new HashMap<>();
model.put("actualData", getProductDataResource());
model.put("otherData", new ClassPathResource("dummyData.xsl", getClass()));
@@ -176,12 +159,13 @@ public class XsltViewTests {
return document;
}
private void doTestWithModel(Map model) throws Exception {
private void doTestWithModel(Map<String, Object> model) throws Exception {
XsltView view = getXsltView(HTML_OUTPUT);
view.render(model, this.request, this.response);
assertHtmlOutput(this.response.getContentAsString());
}
@SuppressWarnings("rawtypes")
private void assertHtmlOutput(String output) throws Exception {
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
@@ -218,4 +202,5 @@ public class XsltViewTests {
private Resource getProductDataResource() {
return new ClassPathResource("productData.xml", getClass());
}
}