diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java index 35828d28e0..ee9179241a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java @@ -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. @@ -15,21 +15,24 @@ */ package org.springframework.aop.support; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; +import static org.junit.Assert.*; + /** * @author Colin Sampaleanu * @author Juergen Hoeller * @author Rob Harrop * @author Rick Evans */ -public class ClassUtilsTests extends TestCase { +public class ClassUtilsTests { - public void testGetShortNameForCglibClass() { + @Test + public void getShortNameForCglibClass() { TestBean tb = new TestBean(); ProxyFactory pf = new ProxyFactory(); pf.setTarget(tb); diff --git a/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/AutoProxyWithCodeStyleAspectsTests.java b/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/AutoProxyWithCodeStyleAspectsTests.java index edf79ec8d3..c0c1e4b1d4 100644 --- a/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/AutoProxyWithCodeStyleAspectsTests.java +++ b/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/AutoProxyWithCodeStyleAspectsTests.java @@ -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,16 +16,18 @@ package org.springframework.aop.aspectj.autoproxy; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author Adrian Colyer */ -public class AutoProxyWithCodeStyleAspectsTests extends TestCase { +public class AutoProxyWithCodeStyleAspectsTests { - public void testNoAutoproxyingOfAjcCompiledAspects() { + @Test + @SuppressWarnings("resource") + public void noAutoproxyingOfAjcCompiledAspects() { new ClassPathXmlApplicationContext("org/springframework/aop/aspectj/autoproxy/ajcAutoproxyTests.xml"); } diff --git a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java index 97ebe9140b..4ee0f22820 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java +++ b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java @@ -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,18 +16,17 @@ package org.springframework.beans.factory.aspectj; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class SpringConfiguredWithAutoProxyingTests extends TestCase { +public class SpringConfiguredWithAutoProxyingTests { - @Override - protected void setUp() throws Exception { + @Test + @SuppressWarnings("resource") + public void springConfiguredAndAutoProxyUsedTogether() { + // instantiation is sufficient to trigger failure if this is going to fail... new ClassPathXmlApplicationContext("org/springframework/beans/factory/aspectj/springConfigured.xml"); } - public void testSpringConfiguredAndAutoProxyUsedTogether() { - ; // set up is sufficient to trigger failure if this is going to fail... - } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java index a1cb02b6a3..fd3036b604 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java @@ -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,18 +18,21 @@ package org.springframework.beans.factory.support; import java.util.Arrays; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller */ -public class BeanDefinitionBuilderTests extends TestCase { +public class BeanDefinitionBuilderTests { - public void testBeanClassWithSimpleProperty() { + @Test + public void beanClassWithSimpleProperty() { String[] dependsOn = new String[] { "A", "B", "C" }; BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class); bdb.setScope(BeanDefinition.SCOPE_PROTOTYPE); @@ -45,7 +48,8 @@ public class BeanDefinitionBuilderTests extends TestCase { assertTrue(rbd.getPropertyValues().contains("age")); } - public void testBeanClassWithFactoryMethod() { + @Test + public void beanClassWithFactoryMethod() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class, "create"); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); assertTrue(rbd.hasBeanClass()); @@ -53,14 +57,16 @@ public class BeanDefinitionBuilderTests extends TestCase { assertEquals("create", rbd.getFactoryMethodName()); } - public void testBeanClassName() { + @Test + public void beanClassName() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName()); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); assertFalse(rbd.hasBeanClass()); assertEquals(TestBean.class.getName(), rbd.getBeanClassName()); } - public void testBeanClassNameWithFactoryMethod() { + @Test + public void beanClassNameWithFactoryMethod() { BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class.getName(), "create"); RootBeanDefinition rbd = (RootBeanDefinition) bdb.getBeanDefinition(); assertFalse(rbd.hasBeanClass()); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java index a81e3c8d69..899bee0552 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java @@ -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,18 +16,20 @@ package org.springframework.beans.factory.support; -import junit.framework.TestCase; +import org.junit.Test; -import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller */ -public class BeanDefinitionTests extends TestCase { +public class BeanDefinitionTests { - public void testBeanDefinitionEquality() { + @Test + public void beanDefinitionEquality() { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setAbstract(true); bd.setLazyInit(true); @@ -43,7 +45,8 @@ public class BeanDefinitionTests extends TestCase { assertTrue(bd.hashCode() == otherBd.hashCode()); } - public void testBeanDefinitionEqualityWithPropertyValues() { + @Test + public void beanDefinitionEqualityWithPropertyValues() { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.getPropertyValues().add("name", "myName"); bd.getPropertyValues().add("age", "99"); @@ -60,7 +63,8 @@ public class BeanDefinitionTests extends TestCase { assertTrue(bd.hashCode() == otherBd.hashCode()); } - public void testBeanDefinitionEqualityWithConstructorArguments() { + @Test + public void beanDefinitionEqualityWithConstructorArguments() { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.getConstructorArgumentValues().addGenericArgumentValue("test"); bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5)); @@ -77,7 +81,8 @@ public class BeanDefinitionTests extends TestCase { assertTrue(bd.hashCode() == otherBd.hashCode()); } - public void testBeanDefinitionEqualityWithTypedConstructorArguments() { + @Test + public void beanDefinitionEqualityWithTypedConstructorArguments() { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.getConstructorArgumentValues().addGenericArgumentValue("test", "int"); bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5), "long"); @@ -95,7 +100,8 @@ public class BeanDefinitionTests extends TestCase { assertTrue(bd.hashCode() == otherBd.hashCode()); } - public void testBeanDefinitionHolderEquality() { + @Test + public void beanDefinitionHolderEquality() { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.setAbstract(true); bd.setLazyInit(true); @@ -113,7 +119,8 @@ public class BeanDefinitionTests extends TestCase { assertTrue(holder.hashCode() == otherHolder.hashCode()); } - public void testBeanDefinitionMerging() { + @Test + public void beanDefinitionMerging() { RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); bd.getConstructorArgumentValues().addGenericArgumentValue("test"); bd.getConstructorArgumentValues().addIndexedArgumentValue(1, new Integer(5)); @@ -124,7 +131,7 @@ public class BeanDefinitionTests extends TestCase { childBd.setParentName("bd"); RootBeanDefinition mergedBd = new RootBeanDefinition(bd); - mergedBd.overrideFrom((BeanDefinition) childBd); + mergedBd.overrideFrom(childBd); assertEquals(2, mergedBd.getConstructorArgumentValues().getArgumentCount()); assertEquals(2, mergedBd.getPropertyValues().size()); assertEquals(bd, mergedBd); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java index ee00efdec9..75e40faad9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedListTests.java @@ -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,15 +18,20 @@ package org.springframework.beans.factory.support; import java.util.List; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rick Evans * @author Juergen Hoeller + * @author Sam Brannen */ -public class ManagedListTests extends TestCase { +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class ManagedListTests { - public void testMergeSunnyDay() { + @Test + public void mergeSunnyDay() { ManagedList parent = new ManagedList(); parent.add("one"); parent.add("two"); @@ -37,36 +42,30 @@ public class ManagedListTests extends TestCase { assertEquals("merge() obviously did not work.", 3, mergedList.size()); } - public void testMergeWithNullParent() { + @Test + public void mergeWithNullParent() { ManagedList child = new ManagedList(); child.add("one"); child.setMergeEnabled(true); assertSame(child, child.merge(null)); } - public void testMergeNotAllowedWhenMergeNotEnabled() { + @Test(expected = IllegalStateException.class) + public void mergeNotAllowedWhenMergeNotEnabled() { ManagedList child = new ManagedList(); - try { - child.merge(null); - fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false."); - } - catch (IllegalStateException expected) { - } + child.merge(null); } - public void testMergeWithNonCompatibleParentType() { + @Test(expected = IllegalArgumentException.class) + public void mergeWithNonCompatibleParentType() { ManagedList child = new ManagedList(); child.add("one"); child.setMergeEnabled(true); - try { - child.merge("hello"); - fail("Must have failed by this point."); - } - catch (IllegalArgumentException expected) { - } + child.merge("hello"); } - public void testMergeEmptyChild() { + @Test + public void mergeEmptyChild() { ManagedList parent = new ManagedList(); parent.add("one"); parent.add("two"); @@ -76,8 +75,9 @@ public class ManagedListTests extends TestCase { assertEquals("merge() obviously did not work.", 2, mergedList.size()); } - public void testMergeChildValuesOverrideTheParents() { - // doesn't make a whole lotta sense in the context of a list... + @Test + public void mergeChildValuesOverrideTheParents() { + // doesn't make much sense in the context of a list... ManagedList parent = new ManagedList(); parent.add("one"); parent.add("two"); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java index c86752d8e9..0b537fd116 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedMapTests.java @@ -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. @@ -18,15 +18,20 @@ package org.springframework.beans.factory.support; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rick Evans * @author Juergen Hoeller + * @author Sam Brannen */ -public class ManagedMapTests extends TestCase { +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class ManagedMapTests { - public void testMergeSunnyDay() { + @Test + public void mergeSunnyDay() { ManagedMap parent = new ManagedMap(); parent.put("one", "one"); parent.put("two", "two"); @@ -37,34 +42,27 @@ public class ManagedMapTests extends TestCase { assertEquals("merge() obviously did not work.", 3, mergedMap.size()); } - public void testMergeWithNullParent() { + @Test + public void mergeWithNullParent() { ManagedMap child = new ManagedMap(); child.setMergeEnabled(true); assertSame(child, child.merge(null)); } - public void testMergeWithNonCompatibleParentType() { + @Test(expected = IllegalArgumentException.class) + public void mergeWithNonCompatibleParentType() { ManagedMap map = new ManagedMap(); map.setMergeEnabled(true); - try { - map.merge("hello"); - fail("Must have failed by this point."); - } - catch (IllegalArgumentException expected) { - } + map.merge("hello"); } - public void testMergeNotAllowedWhenMergeNotEnabled() { - ManagedMap map = new ManagedMap(); - try { - map.merge(null); - fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false."); - } - catch (IllegalStateException expected) { - } + @Test(expected = IllegalStateException.class) + public void mergeNotAllowedWhenMergeNotEnabled() { + new ManagedMap().merge(null); } - public void testMergeEmptyChild() { + @Test + public void mergeEmptyChild() { ManagedMap parent = new ManagedMap(); parent.put("one", "one"); parent.put("two", "two"); @@ -74,7 +72,8 @@ public class ManagedMapTests extends TestCase { assertEquals("merge() obviously did not work.", 2, mergedMap.size()); } - public void testMergeChildValuesOverrideTheParents() { + @Test + public void mergeChildValuesOverrideTheParents() { ManagedMap parent = new ManagedMap(); parent.put("one", "one"); parent.put("two", "two"); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java index 7594ab6cdd..80cc3a5cd1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedPropertiesTests.java @@ -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. @@ -18,15 +18,20 @@ package org.springframework.beans.factory.support; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rick Evans * @author Juergen Hoeller + * @author Sam Brannen */ -public class ManagedPropertiesTests extends TestCase { +@SuppressWarnings("rawtypes") +public class ManagedPropertiesTests { - public void testMergeSunnyDay() { + @Test + public void mergeSunnyDay() { ManagedProperties parent = new ManagedProperties(); parent.setProperty("one", "one"); parent.setProperty("two", "two"); @@ -37,34 +42,28 @@ public class ManagedPropertiesTests extends TestCase { assertEquals("merge() obviously did not work.", 3, mergedMap.size()); } - public void testMergeWithNullParent() { + @Test + public void mergeWithNullParent() { ManagedProperties child = new ManagedProperties(); child.setMergeEnabled(true); assertSame(child, child.merge(null)); } - public void testMergeWithNonCompatibleParentType() { + @Test(expected = IllegalArgumentException.class) + public void mergeWithNonCompatibleParentType() { ManagedProperties map = new ManagedProperties(); map.setMergeEnabled(true); - try { - map.merge("hello"); - fail("Must have failed by this point."); - } - catch (IllegalArgumentException expected) { - } + map.merge("hello"); } - public void testMergeNotAllowedWhenMergeNotEnabled() { + @Test(expected = IllegalStateException.class) + public void mergeNotAllowedWhenMergeNotEnabled() { ManagedProperties map = new ManagedProperties(); - try { - map.merge(null); - fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false."); - } - catch (IllegalStateException expected) { - } + map.merge(null); } - public void testMergeEmptyChild() { + @Test + public void mergeEmptyChild() { ManagedProperties parent = new ManagedProperties(); parent.setProperty("one", "one"); parent.setProperty("two", "two"); @@ -74,7 +73,8 @@ public class ManagedPropertiesTests extends TestCase { assertEquals("merge() obviously did not work.", 2, mergedMap.size()); } - public void testMergeChildValuesOverrideTheParents() { + @Test + public void mergeChildValuesOverrideTheParents() { ManagedProperties parent = new ManagedProperties(); parent.setProperty("one", "one"); parent.setProperty("two", "two"); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java index 22972e96fd..260a00d99a 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/ManagedSetTests.java @@ -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,15 +18,20 @@ package org.springframework.beans.factory.support; import java.util.Set; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rick Evans * @author Juergen Hoeller + * @author Sam Brannen */ -public class ManagedSetTests extends TestCase { +@SuppressWarnings({ "rawtypes", "unchecked" }) +public class ManagedSetTests { - public void testMergeSunnyDay() { + @Test + public void mergeSunnyDay() { ManagedSet parent = new ManagedSet(); parent.add("one"); parent.add("two"); @@ -37,36 +42,29 @@ public class ManagedSetTests extends TestCase { assertEquals("merge() obviously did not work.", 3, mergedSet.size()); } - public void testMergeWithNullParent() { + @Test + public void mergeWithNullParent() { ManagedSet child = new ManagedSet(); child.add("one"); child.setMergeEnabled(true); assertSame(child, child.merge(null)); } - public void testMergeNotAllowedWhenMergeNotEnabled() { - ManagedSet child = new ManagedSet(); - try { - child.merge(null); - fail("Must have failed by this point (cannot merge() when the mergeEnabled property is false."); - } - catch (IllegalStateException expected) { - } + @Test(expected = IllegalStateException.class) + public void mergeNotAllowedWhenMergeNotEnabled() { + new ManagedSet().merge(null); } - public void testMergeWithNonCompatibleParentType() { + @Test(expected = IllegalArgumentException.class) + public void mergeWithNonCompatibleParentType() { ManagedSet child = new ManagedSet(); child.add("one"); child.setMergeEnabled(true); - try { - child.merge("hello"); - fail("Must have failed by this point."); - } - catch (IllegalArgumentException expected) { - } + child.merge("hello"); } - public void testMergeEmptyChild() { + @Test + public void mergeEmptyChild() { ManagedSet parent = new ManagedSet(); parent.add("one"); parent.add("two"); @@ -76,7 +74,8 @@ public class ManagedSetTests extends TestCase { assertEquals("merge() obviously did not work.", 2, mergedSet.size()); } - public void testMergeChildValuesOverrideTheParents() { + @Test + public void mergeChildValuesOverrideTheParents() { // asserts that the set contract is not violated during a merge() operation... ManagedSet parent = new ManagedSet(); parent.add("one"); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java index 0ac52f002f..f8dbf4c1db 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java @@ -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,43 +16,45 @@ package org.springframework.beans.factory.support; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Rob Harrop */ -public class PropertiesBeanDefinitionReaderTests extends TestCase { +public class PropertiesBeanDefinitionReaderTests { - private DefaultListableBeanFactory beanFactory; + private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - private PropertiesBeanDefinitionReader reader; + private final PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader( + beanFactory); - @Override - protected void setUp() throws Exception { - this.beanFactory = new DefaultListableBeanFactory(); - this.reader = new PropertiesBeanDefinitionReader(beanFactory); - } - public void testWithSimpleConstructorArg() { + @Test + public void withSimpleConstructorArg() { this.reader.loadBeanDefinitions(new ClassPathResource("simpleConstructorArg.properties", getClass())); TestBean bean = (TestBean)this.beanFactory.getBean("testBean"); assertEquals("Rob Harrop", bean.getName()); } - public void testWithConstructorArgRef() throws Exception { + @Test + public void withConstructorArgRef() throws Exception { this.reader.loadBeanDefinitions(new ClassPathResource("refConstructorArg.properties", getClass())); TestBean rob = (TestBean)this.beanFactory.getBean("rob"); TestBean sally = (TestBean)this.beanFactory.getBean("sally"); assertEquals(sally, rob.getSpouse()); } - public void testWithMultipleConstructorsArgs() throws Exception { + @Test + public void withMultipleConstructorsArgs() throws Exception { this.reader.loadBeanDefinitions(new ClassPathResource("multiConstructorArgs.properties", getClass())); TestBean bean = (TestBean)this.beanFactory.getBean("testBean"); assertEquals("Rob Harrop", bean.getName()); assertEquals(23, bean.getAge()); } + } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java index 835269ea82..d6df28bef2 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java @@ -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,31 +16,30 @@ package org.springframework.beans.factory.wiring; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Rick Evans * @author Juergen Hoeller + * @author Sam Brannen */ -public class BeanConfigurerSupportTests extends TestCase { +public class BeanConfigurerSupportTests { - public void testSupplyIncompatibleBeanFactoryImplementation() throws Exception { - try { - new StubBeanConfigurerSupport().setBeanFactory(mock(BeanFactory.class)); - fail("Must have thrown an IllegalArgumentException by this point (incompatible BeanFactory implementation supplied)"); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void supplyIncompatibleBeanFactoryImplementation() throws Exception { + new StubBeanConfigurerSupport().setBeanFactory(mock(BeanFactory.class)); } - public void testConfigureBeanDoesNothingIfBeanWiringInfoResolverResolvesToNull() throws Exception { + @Test + public void configureBeanDoesNothingIfBeanWiringInfoResolverResolvesToNull() throws Exception { TestBean beanInstance = new TestBean(); BeanWiringInfoResolver resolver = mock(BeanWiringInfoResolver.class); @@ -53,14 +52,16 @@ public class BeanConfigurerSupportTests extends TestCase { assertNull(beanInstance.getName()); } - public void testConfigureBeanDoesNothingIfNoBeanFactoryHasBeenSet() throws Exception { + @Test + public void configureBeanDoesNothingIfNoBeanFactoryHasBeenSet() throws Exception { TestBean beanInstance = new TestBean(); BeanConfigurerSupport configurer = new StubBeanConfigurerSupport(); configurer.configureBean(beanInstance); assertNull(beanInstance.getName()); } - public void testConfigureBeanReallyDoesDefaultToUsingTheFullyQualifiedClassNameOfTheSuppliedBeanInstance() throws Exception { + @Test + public void configureBeanReallyDoesDefaultToUsingTheFullyQualifiedClassNameOfTheSuppliedBeanInstance() throws Exception { TestBean beanInstance = new TestBean(); BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class); builder.addPropertyValue("name", "Harriet Wheeler"); @@ -75,7 +76,8 @@ public class BeanConfigurerSupportTests extends TestCase { assertEquals("Bean is evidently not being configured (for some reason)", "Harriet Wheeler", beanInstance.getName()); } - public void testConfigureBeanPerformsAutowiringByNameIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception { + @Test + public void configureBeanPerformsAutowiringByNameIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception { TestBean beanInstance = new TestBean(); // spouse for autowiring by name... BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class); @@ -94,7 +96,8 @@ public class BeanConfigurerSupportTests extends TestCase { assertEquals("Bean is evidently not being configured (for some reason)", "David Gavurin", beanInstance.getSpouse().getName()); } - public void testConfigureBeanPerformsAutowiringByTypeIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception { + @Test + public void configureBeanPerformsAutowiringByTypeIfAppropriateBeanWiringInfoResolverIsPluggedIn() throws Exception { TestBean beanInstance = new TestBean(); // spouse for autowiring by type... BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TestBean.class); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java index 18ab24bedf..59f9566e88 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanWiringInfoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 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,76 +16,63 @@ package org.springframework.beans.factory.wiring; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Unit tests for the BeanWiringInfo class. * * @author Rick Evans + * @author Sam Brannen */ -public final class BeanWiringInfoTests extends TestCase { +public final class BeanWiringInfoTests { - public void testCtorWithNullBeanName() throws Exception { - try { - new BeanWiringInfo(null); - fail("Must have thrown an IllegalArgumentException by this point (null argument)."); - } - catch (IllegalArgumentException ex) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorWithNullBeanName() throws Exception { + new BeanWiringInfo(null); } - public void testCtorWithWhitespacedBeanName() throws Exception { - try { - new BeanWiringInfo(" \t"); - fail("Must have thrown an IllegalArgumentException by this point (bean name has only whitespace)."); - } - catch (IllegalArgumentException ex) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorWithWhitespacedBeanName() throws Exception { + new BeanWiringInfo(" \t"); } - public void testCtorWithEmptyBeanName() throws Exception { - try { - new BeanWiringInfo(""); - fail("Must have thrown an IllegalArgumentException by this point (bean name is empty)."); - } - catch (IllegalArgumentException ex) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorWithEmptyBeanName() throws Exception { + new BeanWiringInfo(""); } - public void testCtorWithNegativeIllegalAutowiringValue() throws Exception { - try { - new BeanWiringInfo(-1, true); - fail("Must have thrown an IllegalArgumentException by this point (out-of-range argument)."); - } - catch (IllegalArgumentException ex) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorWithNegativeIllegalAutowiringValue() throws Exception { + new BeanWiringInfo(-1, true); } - public void testCtorWithPositiveOutOfRangeAutowiringValue() throws Exception { - try { - new BeanWiringInfo(123871, true); - fail("Must have thrown an IllegalArgumentException by this point (out-of-range argument)."); - } - catch (IllegalArgumentException ex) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorWithPositiveOutOfRangeAutowiringValue() throws Exception { + new BeanWiringInfo(123871, true); } - public void testUsingAutowireCtorIndicatesAutowiring() throws Exception { + @Test + public void usingAutowireCtorIndicatesAutowiring() throws Exception { BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, true); assertTrue(info.indicatesAutowiring()); } - public void testUsingBeanNameCtorDoesNotIndicateAutowiring() throws Exception { + @Test + public void usingBeanNameCtorDoesNotIndicateAutowiring() throws Exception { BeanWiringInfo info = new BeanWiringInfo("fooService"); assertFalse(info.indicatesAutowiring()); } - public void testNoDependencyCheckValueIsPreserved() throws Exception { + @Test + public void noDependencyCheckValueIsPreserved() throws Exception { BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_NAME, true); assertTrue(info.getDependencyCheck()); } - public void testDependencyCheckValueIsPreserved() throws Exception { + @Test + public void dependencyCheckValueIsPreserved() throws Exception { BeanWiringInfo info = new BeanWiringInfo(BeanWiringInfo.AUTOWIRE_BY_TYPE, false); assertFalse(info.getDependencyCheck()); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java index 6bacb2ce70..cec8d1f766 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/ClassNameBeanWiringInfoResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 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,25 +16,24 @@ package org.springframework.beans.factory.wiring; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Unit tests for the ClassNameBeanWiringInfoResolver class. * * @author Rick Evans */ -public final class ClassNameBeanWiringInfoResolverTests extends TestCase { +public final class ClassNameBeanWiringInfoResolverTests { - public void testResolveWiringInfoWithNullBeanInstance() throws Exception { - try { - new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null); - fail("Must have thrown an IllegalArgumentException by this point (null argument)."); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void resolveWiringInfoWithNullBeanInstance() throws Exception { + new ClassNameBeanWiringInfoResolver().resolveWiringInfo(null); } - public void testResolveWiringInfo() { + @Test + public void resolveWiringInfo() { ClassNameBeanWiringInfoResolver resolver = new ClassNameBeanWiringInfoResolver(); Long beanInstance = new Long(1); BeanWiringInfo info = resolver.resolveWiringInfo(beanInstance); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java index e56ea1f355..64d96f0b16 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java @@ -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,7 +19,7 @@ package org.springframework.beans.factory.xml; import java.beans.PropertyEditorSupport; import java.util.StringTokenizer; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyBatchUpdateException; @@ -34,21 +34,24 @@ import org.springframework.tests.sample.beans.MustBeInitialized; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; +import static org.junit.Assert.*; + /** - * Subclasses must implement setUp() to initialize bean factory - * and any other variables they need. + * Subclasses must initialize the bean factory and any other variables they need. * * @author Rod Johnson * @author Juergen Hoeller + * @author Sam Brannen */ -public abstract class AbstractBeanFactoryTests extends TestCase { +public abstract class AbstractBeanFactoryTests { protected abstract BeanFactory getBeanFactory(); /** - * Roderick beans inherits from rod, overriding name only. + * Roderick bean inherits from rod, overriding name only. */ - public void testInheritance() { + @Test + public void inheritance() { assertTrue(getBeanFactory().containsBean("rod")); assertTrue(getBeanFactory().containsBean("roderick")); TestBean rod = (TestBean) getBeanFactory().getBean("rod"); @@ -60,20 +63,16 @@ public abstract class AbstractBeanFactoryTests extends TestCase { assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge()); } - public void testGetBeanWithNullArg() { - try { - getBeanFactory().getBean((String) null); - fail("Can't get null bean"); - } - catch (IllegalArgumentException ex) { - // OK - } + @Test(expected = IllegalArgumentException.class) + public void getBeanWithNullArg() { + getBeanFactory().getBean((String) null); } /** * Test that InitializingBean objects receive the afterPropertiesSet() callback */ - public void testInitializingBeanCallback() { + @Test + public void initializingBeanCallback() { MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized"); // The dummy business method will throw an exception if the // afterPropertiesSet() callback wasn't invoked @@ -84,7 +83,8 @@ public abstract class AbstractBeanFactoryTests extends TestCase { * Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the * afterPropertiesSet() callback before BeanFactoryAware callbacks */ - public void testLifecycleCallbacks() { + @Test + public void lifecycleCallbacks() { LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle"); assertEquals("lifecycle", lb.getBeanName()); // The dummy business method will throw an exception if the @@ -93,32 +93,23 @@ public abstract class AbstractBeanFactoryTests extends TestCase { assertTrue("Not destroyed", !lb.isDestroyed()); } - public void testFindsValidInstance() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - TestBean rod = (TestBean) o; - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } + @Test + public void findsValidInstance() { + Object o = getBeanFactory().getBean("rod"); + assertTrue("Rod bean is a TestBean", o instanceof TestBean); + TestBean rod = (TestBean) o; + assertTrue("rod.name is Rod", rod.getName().equals("Rod")); + assertTrue("rod.age is 31", rod.getAge() == 31); } - public void testGetInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } + @Test + public void getInstanceByMatchingClass() { + Object o = getBeanFactory().getBean("rod", TestBean.class); + assertTrue("Rod bean is a TestBean", o instanceof TestBean); } - public void testGetInstanceByNonmatchingClass() { + @Test + public void getInstanceByNonmatchingClass() { try { getBeanFactory().getBean("rod", BeanFactory.class); fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); @@ -130,29 +121,22 @@ public abstract class AbstractBeanFactoryTests extends TestCase { assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass()); } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } } - public void testGetSharedInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } - } - - public void testGetSharedInstanceByMatchingClassNoCatch() { + @Test + public void getSharedInstanceByMatchingClass() { Object o = getBeanFactory().getBean("rod", TestBean.class); assertTrue("Rod bean is a TestBean", o instanceof TestBean); } - public void testGetSharedInstanceByNonmatchingClass() { + @Test + public void getSharedInstanceByMatchingClassNoCatch() { + Object o = getBeanFactory().getBean("rod", TestBean.class); + assertTrue("Rod bean is a TestBean", o instanceof TestBean); + } + + @Test + public void getSharedInstanceByNonmatchingClass() { try { getBeanFactory().getBean("rod", BeanFactory.class); fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); @@ -163,27 +147,19 @@ public abstract class AbstractBeanFactoryTests extends TestCase { assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } } - public void testSharedInstancesAreEqual() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean1 is a TestBean", o instanceof TestBean); - Object o1 = getBeanFactory().getBean("rod"); - assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean); - assertTrue("Object equals applies", o == o1); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } + @Test + public void sharedInstancesAreEqual() { + Object o = getBeanFactory().getBean("rod"); + assertTrue("Rod bean1 is a TestBean", o instanceof TestBean); + Object o1 = getBeanFactory().getBean("rod"); + assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean); + assertTrue("Object equals applies", o == o1); } - public void testPrototypeInstancesAreIndependent() { + @Test + public void prototypeInstancesAreIndependent() { TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy"); TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy"); assertTrue("ref equal DOES NOT apply", tb1 != tb2); @@ -195,29 +171,18 @@ public abstract class AbstractBeanFactoryTests extends TestCase { assertTrue("object equal now false", !tb1.equals(tb2)); } - public void testNotThere() { + @Test(expected = BeansException.class) + public void notThere() { assertFalse(getBeanFactory().containsBean("Mr Squiggle")); - try { - getBeanFactory().getBean("Mr Squiggle"); - fail("Can't find missing bean"); - } - catch (BeansException ex) { - //ex.printStackTrace(); - //fail("Shouldn't throw exception on getting valid instance"); - } + getBeanFactory().getBean("Mr Squiggle"); } - public void testValidEmpty() { - try { - Object o = getBeanFactory().getBean("validEmpty"); - assertTrue("validEmpty bean is a TestBean", o instanceof TestBean); - TestBean ve = (TestBean) o; - assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null); - } - catch (BeansException ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on valid empty"); - } + @Test + public void validEmpty() { + Object o = getBeanFactory().getBean("validEmpty"); + assertTrue("validEmpty bean is a TestBean", o instanceof TestBean); + TestBean ve = (TestBean) o; + assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null); } public void xtestTypeMismatch() { @@ -236,12 +201,14 @@ public abstract class AbstractBeanFactoryTests extends TestCase { } } - public void testGrandparentDefinitionFoundInBeanFactory() throws Exception { + @Test + public void grandparentDefinitionFoundInBeanFactory() throws Exception { TestBean dad = (TestBean) getBeanFactory().getBean("father"); assertTrue("Dad has correct name", dad.getName().equals("Albert")); } - public void testFactorySingleton() throws Exception { + @Test + public void factorySingleton() throws Exception { assertTrue(getBeanFactory().isSingleton("&singletonFactory")); assertTrue(getBeanFactory().isSingleton("singletonFactory")); TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); @@ -252,7 +219,8 @@ public abstract class AbstractBeanFactoryTests extends TestCase { assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null); } - public void testFactoryPrototype() throws Exception { + @Test + public void factoryPrototype() throws Exception { assertTrue(getBeanFactory().isSingleton("&prototypeFactory")); assertFalse(getBeanFactory().isSingleton("prototypeFactory")); TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory"); @@ -266,16 +234,17 @@ public abstract class AbstractBeanFactoryTests extends TestCase { * This is only possible if we're dealing with a factory * @throws Exception */ - public void testGetFactoryItself() throws Exception { - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue(factory != null); + @Test + public void getFactoryItself() throws Exception { + assertNotNull(getBeanFactory().getBean("&singletonFactory")); } /** * Check that afterPropertiesSet gets called on factory * @throws Exception */ - public void testFactoryIsInitialized() throws Exception { + @Test + public void factoryIsInitialized() throws Exception { TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); assertNotNull(tb); DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); @@ -283,22 +252,17 @@ public abstract class AbstractBeanFactoryTests extends TestCase { } /** - * It should be illegal to dereference a normal bean - * as a factory + * It should be illegal to dereference a normal bean as a factory. */ - public void testRejectsFactoryGetOnNormalBean() { - try { - getBeanFactory().getBean("&rod"); - fail("Shouldn't permit factory get on normal bean"); - } - catch (BeanIsNotAFactoryException ex) { - // Ok - } + @Test(expected = BeanIsNotAFactoryException.class) + public void rejectsFactoryGetOnNormalBean() { + getBeanFactory().getBean("&rod"); } // TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory) // and rename this class - public void testAliasing() { + @Test + public void aliasing() { BeanFactory bf = getBeanFactory(); if (!(bf instanceof ConfigurableBeanFactory)) { return; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java index 30c060cfaa..b0a9ea0771 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java @@ -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,15 @@ package org.springframework.beans.factory.xml; +import org.junit.Test; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller @@ -39,7 +43,8 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto /** * Subclasses can override this. */ - public void testCount() { + @Test + public void count() { assertCount(13); } @@ -48,7 +53,7 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count); } - public void assertTestBeanCount(int count) { + protected void assertTestBeanCount(int count) { String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false); assertTrue("We should have " + count + " beans for class org.springframework.tests.sample.beans.TestBean, not " + defNames.length, defNames.length == count); @@ -60,7 +65,8 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto names.length == countIncludingFactoryBeans); } - public void testGetDefinitionsForNoSuchClass() { + @Test + public void getDefinitionsForNoSuchClass() { String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class); assertTrue("No string definitions", defnames.length == 0); } @@ -69,7 +75,8 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto * Check that count refers to factory class, not bean class. (We don't know * what type factories may return, and it may even change over time.) */ - public void testGetCountForFactoryClass() { + @Test + public void getCountForFactoryClass() { assertTrue("Should have 2 factories, not " + getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); @@ -79,7 +86,8 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); } - public void testContainsBeanDefinition() { + @Test + public void containsBeanDefinition() { assertTrue(getListableBeanFactory().containsBeanDefinition("rod")); assertTrue(getListableBeanFactory().containsBeanDefinition("roderick")); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java index dd17fe369c..0bd5cc414a 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java @@ -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,7 +16,7 @@ package org.springframework.beans.factory.xml; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.beans.factory.config.RuntimeBeanReference; @@ -25,13 +25,16 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller */ -public class AutowireWithExclusionTests extends TestCase { +public class AutowireWithExclusionTests { - public void testByTypeAutowireWithAutoSelfExclusion() throws Exception { + @Test + public void byTypeAutowireWithAutoSelfExclusion() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-with-exclusion.xml"); beanFactory.preInstantiateSingletons(); @@ -41,7 +44,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testByTypeAutowireWithExclusion() throws Exception { + @Test + public void byTypeAutowireWithExclusion() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-with-exclusion.xml"); beanFactory.preInstantiateSingletons(); @@ -50,7 +54,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testByTypeAutowireWithExclusionInParentFactory() throws Exception { + @Test + public void byTypeAutowireWithExclusionInParentFactory() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.preInstantiateSingletons(); @@ -64,7 +69,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testByTypeAutowireWithPrimaryInParentFactory() throws Exception { + @Test + public void byTypeAutowireWithPrimaryInParentFactory() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.getBeanDefinition("props1").setPrimary(true); @@ -82,7 +88,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testByTypeAutowireWithPrimaryOverridingParentFactory() throws Exception { + @Test + public void byTypeAutowireWithPrimaryOverridingParentFactory() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.preInstantiateSingletons(); @@ -100,7 +107,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testByTypeAutowireWithPrimaryInParentAndChild() throws Exception { + @Test + public void byTypeAutowireWithPrimaryInParentAndChild() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory parent = getBeanFactory("autowire-with-exclusion.xml"); parent.getBeanDefinition("props1").setPrimary(true); @@ -119,7 +127,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testByTypeAutowireWithInclusion() throws Exception { + @Test + public void byTypeAutowireWithInclusion() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-with-inclusion.xml"); beanFactory.preInstantiateSingletons(); @@ -128,7 +137,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testByTypeAutowireWithSelectiveInclusion() throws Exception { + @Test + public void byTypeAutowireWithSelectiveInclusion() throws Exception { CountingFactory.reset(); DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-with-selective-inclusion.xml"); beanFactory.preInstantiateSingletons(); @@ -137,7 +147,8 @@ public class AutowireWithExclusionTests extends TestCase { assertEquals(1, CountingFactory.getFactoryBeanInstanceCount()); } - public void testConstructorAutowireWithAutoSelfExclusion() throws Exception { + @Test + public void constructorAutowireWithAutoSelfExclusion() throws Exception { DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml"); TestBean rob = (TestBean) beanFactory.getBean("rob"); TestBean sally = (TestBean) beanFactory.getBean("sally"); @@ -149,7 +160,8 @@ public class AutowireWithExclusionTests extends TestCase { assertNotSame(rob.getSpouse(), rob2.getSpouse()); } - public void testConstructorAutowireWithExclusion() throws Exception { + @Test + public void constructorAutowireWithExclusion() throws Exception { DefaultListableBeanFactory beanFactory = getBeanFactory("autowire-constructor-with-exclusion.xml"); TestBean rob = (TestBean) beanFactory.getBean("rob"); assertEquals("props1", rob.getSomeProperties().getProperty("name")); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java index cfe24570a3..c836798219 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/BeanNameGenerationTests.java @@ -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,21 +16,25 @@ package org.springframework.beans.factory.xml; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.support.BeanDefinitionReaderUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller */ -public class BeanNameGenerationTests extends TestCase { +public class BeanNameGenerationTests { private DefaultListableBeanFactory beanFactory; - @Override + + @Before public void setUp() { this.beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); @@ -38,7 +42,8 @@ public class BeanNameGenerationTests extends TestCase { reader.loadBeanDefinitions(new ClassPathResource("beanNameGeneration.xml", getClass())); } - public void testNaming() { + @Test + public void naming() { String className = GeneratedNameBean.class.getName(); String targetName = className + BeanDefinitionReaderUtils.GENERATED_BEAN_NAME_SEPARATOR + "0"; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java index 6c002d565d..1c6ce78bbd 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java @@ -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. @@ -22,31 +22,36 @@ import java.util.Map; import java.util.Properties; import java.util.Set; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.support.BeanDefinitionReader; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * Unit and integration tests for the collection merging support. * * @author Rob Harrop * @author Rick Evans */ -public class CollectionMergingTests extends TestCase { +@SuppressWarnings("rawtypes") +public class CollectionMergingTests { - private DefaultListableBeanFactory beanFactory; + private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - @Override - protected void setUp() throws Exception { - this.beanFactory = new DefaultListableBeanFactory(); + + @Before + public void setUp() throws Exception { BeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.loadBeanDefinitions(new ClassPathResource("collectionMerging.xml", getClass())); } - public void testMergeList() throws Exception { + @Test + public void mergeList() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithList"); List list = bean.getSomeList(); assertEquals("Incorrect size", 3, list.size()); @@ -55,7 +60,8 @@ public class CollectionMergingTests extends TestCase { assertEquals(list.get(2), "Juergen Hoeller"); } - public void testMergeListWithInnerBeanAsListElement() throws Exception { + @Test + public void mergeListWithInnerBeanAsListElement() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithListOfRefs"); List list = bean.getSomeList(); assertNotNull(list); @@ -64,7 +70,8 @@ public class CollectionMergingTests extends TestCase { assertTrue(list.get(2) instanceof TestBean); } - public void testMergeSet() { + @Test + public void mergeSet() { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSet"); Set set = bean.getSomeSet(); assertEquals("Incorrect size", 2, set.size()); @@ -72,7 +79,8 @@ public class CollectionMergingTests extends TestCase { assertTrue(set.contains("Sally Greenwood")); } - public void testMergeSetWithInnerBeanAsSetElement() throws Exception { + @Test + public void mergeSetWithInnerBeanAsSetElement() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetOfRefs"); Set set = bean.getSomeSet(); assertNotNull(set); @@ -85,7 +93,8 @@ public class CollectionMergingTests extends TestCase { assertEquals("Sally", ((TestBean) o).getName()); } - public void testMergeMap() throws Exception { + @Test + public void mergeMap() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMap"); Map map = bean.getSomeMap(); assertEquals("Incorrect size", 3, map.size()); @@ -94,7 +103,8 @@ public class CollectionMergingTests extends TestCase { assertEquals(map.get("Juergen"), "Eva"); } - public void testMergeMapWithInnerBeanAsMapEntryValue() throws Exception { + @Test + public void mergeMapWithInnerBeanAsMapEntryValue() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapOfRefs"); Map map = bean.getSomeMap(); assertNotNull(map); @@ -104,7 +114,8 @@ public class CollectionMergingTests extends TestCase { assertEquals("Sally", ((TestBean) map.get("Rob")).getName()); } - public void testMergeProperties() throws Exception { + @Test + public void mergeProperties() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithProps"); Properties props = bean.getSomeProperties(); assertEquals("Incorrect size", 3, props.size()); @@ -113,8 +124,8 @@ public class CollectionMergingTests extends TestCase { assertEquals(props.getProperty("Juergen"), "Eva"); } - - public void testMergeListInConstructor() throws Exception { + @Test + public void mergeListInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithListInConstructor"); List list = bean.getSomeList(); assertEquals("Incorrect size", 3, list.size()); @@ -123,7 +134,8 @@ public class CollectionMergingTests extends TestCase { assertEquals(list.get(2), "Juergen Hoeller"); } - public void testMergeListWithInnerBeanAsListElementInConstructor() throws Exception { + @Test + public void mergeListWithInnerBeanAsListElementInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithListOfRefsInConstructor"); List list = bean.getSomeList(); assertNotNull(list); @@ -132,7 +144,8 @@ public class CollectionMergingTests extends TestCase { assertTrue(list.get(2) instanceof TestBean); } - public void testMergeSetInConstructor() { + @Test + public void mergeSetInConstructor() { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetInConstructor"); Set set = bean.getSomeSet(); assertEquals("Incorrect size", 2, set.size()); @@ -140,7 +153,8 @@ public class CollectionMergingTests extends TestCase { assertTrue(set.contains("Sally Greenwood")); } - public void testMergeSetWithInnerBeanAsSetElementInConstructor() throws Exception { + @Test + public void mergeSetWithInnerBeanAsSetElementInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithSetOfRefsInConstructor"); Set set = bean.getSomeSet(); assertNotNull(set); @@ -153,7 +167,8 @@ public class CollectionMergingTests extends TestCase { assertEquals("Sally", ((TestBean) o).getName()); } - public void testMergeMapInConstructor() throws Exception { + @Test + public void mergeMapInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapInConstructor"); Map map = bean.getSomeMap(); assertEquals("Incorrect size", 3, map.size()); @@ -162,7 +177,8 @@ public class CollectionMergingTests extends TestCase { assertEquals(map.get("Juergen"), "Eva"); } - public void testMergeMapWithInnerBeanAsMapEntryValueInConstructor() throws Exception { + @Test + public void mergeMapWithInnerBeanAsMapEntryValueInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithMapOfRefsInConstructor"); Map map = bean.getSomeMap(); assertNotNull(map); @@ -172,7 +188,8 @@ public class CollectionMergingTests extends TestCase { assertEquals("Sally", ((TestBean) map.get("Rob")).getName()); } - public void testMergePropertiesInConstructor() throws Exception { + @Test + public void mergePropertiesInConstructor() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("childWithPropsInConstructor"); Properties props = bean.getSomeProperties(); assertEquals("Incorrect size", 3, props.size()); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java index d79ff06cbb..61b56fa3ed 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DefaultLifecycleMethodsTests.java @@ -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,26 +16,30 @@ package org.springframework.beans.factory.xml; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import static org.junit.Assert.*; + /** * @author Rob Harrop */ -public class DefaultLifecycleMethodsTests extends TestCase { +public class DefaultLifecycleMethodsTests { - private DefaultListableBeanFactory beanFactory; + private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - @Override - protected void setUp() throws Exception { - this.beanFactory = new DefaultListableBeanFactory(); + + @Before + public void setUp() throws Exception { new XmlBeanDefinitionReader(this.beanFactory).loadBeanDefinitions(new ClassPathResource( "defaultLifecycleMethods.xml", getClass())); } - public void testLifecycleMethodsInvoked() { + @Test + public void lifecycleMethodsInvoked() { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("lifecycleAware"); assertTrue("Bean not initialized", bean.isInitCalled()); assertFalse("Bean destroyed too early", bean.isDestroyCalled()); @@ -43,28 +47,25 @@ public class DefaultLifecycleMethodsTests extends TestCase { assertTrue("Bean not destroyed", bean.isDestroyCalled()); } - public void testLifecycleMethodsDisabled() throws Exception { + @Test + public void lifecycleMethodsDisabled() throws Exception { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("lifecycleMethodsDisabled"); assertFalse("Bean init method called incorrectly", bean.isInitCalled()); this.beanFactory.destroySingletons(); assertFalse("Bean destroy method called incorrectly", bean.isDestroyCalled()); } - public void testIgnoreDefaultLifecycleMethods() throws Exception { - try { - DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions( - new ClassPathResource("ignoreDefaultLifecycleMethods.xml", getClass())); - bf.preInstantiateSingletons(); - bf.destroySingletons(); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Should ignore non-existent default lifecycle methods"); - } + @Test + public void ignoreDefaultLifecycleMethods() throws Exception { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource( + "ignoreDefaultLifecycleMethods.xml", getClass())); + bf.preInstantiateSingletons(); + bf.destroySingletons(); } - public void testOverrideDefaultLifecycleMethods() throws Exception { + @Test + public void overrideDefaultLifecycleMethods() throws Exception { LifecycleAwareBean bean = (LifecycleAwareBean) this.beanFactory.getBean("overrideLifecycleMethods"); assertFalse("Default init method called incorrectly.", bean.isInitCalled()); assertTrue("Custom init method not called.", bean.isCustomInitCalled()); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java index ff691358a4..d571112c42 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java @@ -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,8 +18,8 @@ package org.springframework.beans.factory.xml; import java.util.List; -import junit.framework.TestCase; -import org.w3c.dom.Element; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.TypedStringValue; @@ -32,26 +32,33 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.beans.CollectingReaderEventListener; +import org.w3c.dom.Element; + +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller */ -public class EventPublicationTests extends TestCase { +@SuppressWarnings("rawtypes") +public class EventPublicationTests { private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); private final CollectingReaderEventListener eventListener = new CollectingReaderEventListener(); - @Override - protected void setUp() throws Exception { + + @Before + public void setUp() throws Exception { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.setEventListener(this.eventListener); reader.setSourceExtractor(new PassThroughSourceExtractor()); reader.loadBeanDefinitions(new ClassPathResource("beanEvents.xml", getClass())); } - public void testDefaultsEventReceived() throws Exception { + @Test + public void defaultsEventReceived() throws Exception { List defaultsList = this.eventListener.getDefaults(); assertTrue(!defaultsList.isEmpty()); assertTrue(defaultsList.get(0) instanceof DocumentDefaultsDefinition); @@ -65,7 +72,8 @@ public class EventPublicationTests extends TestCase { assertTrue(defaults.getSource() instanceof Element); } - public void testBeanEventReceived() throws Exception { + @Test + public void beanEventReceived() throws Exception { ComponentDefinition componentDefinition1 = this.eventListener.getComponentDefinition("testBean"); assertTrue(componentDefinition1 instanceof BeanComponentDefinition); assertEquals(1, componentDefinition1.getBeanDefinitions().length); @@ -94,7 +102,8 @@ public class EventPublicationTests extends TestCase { assertTrue(componentDefinition2.getSource() instanceof Element); } - public void testAliasEventReceived() throws Exception { + @Test + public void aliasEventReceived() throws Exception { List aliases = this.eventListener.getAliases("testBean"); assertEquals(2, aliases.size()); AliasDefinition aliasDefinition1 = (AliasDefinition) aliases.get(0); @@ -105,7 +114,8 @@ public class EventPublicationTests extends TestCase { assertTrue(aliasDefinition2.getSource() instanceof Element); } - public void testImportEventReceived() throws Exception { + @Test + public void importEventReceived() throws Exception { List imports = this.eventListener.getImports(); assertEquals(1, imports.size()); ImportDefinition importDefinition = (ImportDefinition) imports.get(0); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java index 9a98ab4c15..ff66dec977 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/MetadataAttachmentTests.java @@ -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,39 +16,46 @@ package org.springframework.beans.factory.xml; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import static org.junit.Assert.*; + /** * @author Rob Harrop */ -public class MetadataAttachmentTests extends TestCase { +public class MetadataAttachmentTests { private DefaultListableBeanFactory beanFactory; - @Override - protected void setUp() throws Exception { + + @Before + public void setUp() throws Exception { this.beanFactory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(this.beanFactory).loadBeanDefinitions( new ClassPathResource("withMeta.xml", getClass())); } - public void testMetadataAttachment() throws Exception { + @Test + public void metadataAttachment() throws Exception { BeanDefinition beanDefinition1 = this.beanFactory.getMergedBeanDefinition("testBean1"); assertEquals("bar", beanDefinition1.getAttribute("foo")); } - public void testMetadataIsInherited() throws Exception { + @Test + public void metadataIsInherited() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("testBean2"); assertEquals("Metadata not inherited", "bar", beanDefinition.getAttribute("foo")); assertEquals("Child metdata not attached", "123", beanDefinition.getAttribute("abc")); } - public void testPropertyMetadata() throws Exception { + @Test + public void propertyMetadata() throws Exception { BeanDefinition beanDefinition = this.beanFactory.getMergedBeanDefinition("testBean3"); PropertyValue pv = beanDefinition.getPropertyValues().getPropertyValue("name"); assertEquals("Harrop", pv.getAttribute("surname")); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java index 27acaa17ff..81d464c015 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java @@ -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,20 +16,24 @@ package org.springframework.beans.factory.xml; -import junit.framework.TestCase; -import org.xml.sax.SAXParseException; +import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.sample.beans.TestBean; +import org.xml.sax.SAXParseException; + +import static org.junit.Assert.*; + /** * @author Rob Harrop */ -public class SchemaValidationTests extends TestCase { +public class SchemaValidationTests { - public void testWithAutodetection() throws Exception { + @Test + public void withAutodetection() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); try { @@ -41,7 +45,8 @@ public class SchemaValidationTests extends TestCase { } } - public void testWithExplicitValidationMode() throws Exception { + @Test + public void withExplicitValidationMode() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); @@ -54,7 +59,8 @@ public class SchemaValidationTests extends TestCase { } } - public void testLoadDefinitions() throws Exception { + @Test + public void loadDefinitions() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java index 04f39e6909..a59fc3bc98 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java @@ -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,8 +18,7 @@ package org.springframework.beans.factory.xml; import java.util.Arrays; -import junit.framework.TestCase; -import org.xml.sax.InputSource; +import org.junit.Test; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -31,49 +30,45 @@ import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; +import org.xml.sax.InputSource; + +import static org.junit.Assert.*; + /** * @author Rick Evans * @author Juergen Hoeller + * @author Sam Brannen */ -public class XmlBeanDefinitionReaderTests extends TestCase { +public class XmlBeanDefinitionReaderTests { - public void testSetParserClassSunnyDay() { + @Test + public void setParserClassSunnyDay() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); new XmlBeanDefinitionReader(registry).setDocumentReaderClass(DefaultBeanDefinitionDocumentReader.class); } - public void testSetParserClassToNull() { - try { - SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); - new XmlBeanDefinitionReader(registry).setDocumentReaderClass(null); - fail("Should have thrown IllegalArgumentException (null parserClass)"); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void setParserClassToNull() { + SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); + new XmlBeanDefinitionReader(registry).setDocumentReaderClass(null); } - public void testSetParserClassToUnsupportedParserType() throws Exception { - try { - SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); - new XmlBeanDefinitionReader(registry).setDocumentReaderClass(String.class); - fail("Should have thrown IllegalArgumentException (unsupported parserClass)"); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void setParserClassToUnsupportedParserType() throws Exception { + SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); + new XmlBeanDefinitionReader(registry).setDocumentReaderClass(String.class); } - public void testWithOpenInputStream() { - try { - SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); - Resource resource = new InputStreamResource(getClass().getResourceAsStream("test.xml")); - new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); - fail("Should have thrown BeanDefinitionStoreException (can't determine validation mode)"); - } - catch (BeanDefinitionStoreException expected) { - } + @Test(expected = BeanDefinitionStoreException.class) + public void withOpenInputStream() { + SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); + Resource resource = new InputStreamResource(getClass().getResourceAsStream( + "test.xml")); + new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); } - public void testWithOpenInputStreamAndExplicitValidationMode() { + @Test + public void withOpenInputStreamAndExplicitValidationMode() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); Resource resource = new InputStreamResource(getClass().getResourceAsStream("test.xml")); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); @@ -82,32 +77,31 @@ public class XmlBeanDefinitionReaderTests extends TestCase { testBeanDefinitions(registry); } - public void testWithImport() { + @Test + public void withImport() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); Resource resource = new ClassPathResource("import.xml", getClass()); new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); testBeanDefinitions(registry); } - public void testWithWildcardImport() { + @Test + public void withWildcardImport() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); Resource resource = new ClassPathResource("importPattern.xml", getClass()); new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); testBeanDefinitions(registry); } - public void testWithInputSource() { - try { - SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); - InputSource resource = new InputSource(getClass().getResourceAsStream("test.xml")); - new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); - fail("Should have thrown BeanDefinitionStoreException (can't determine validation mode)"); - } - catch (BeanDefinitionStoreException expected) { - } + @Test(expected = BeanDefinitionStoreException.class) + public void withInputSource() { + SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); + InputSource resource = new InputSource(getClass().getResourceAsStream("test.xml")); + new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); } - public void testWithInputSourceAndExplicitValidationMode() { + @Test + public void withInputSourceAndExplicitValidationMode() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); InputSource resource = new InputSource(getClass().getResourceAsStream("test.xml")); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); @@ -116,7 +110,8 @@ public class XmlBeanDefinitionReaderTests extends TestCase { testBeanDefinitions(registry); } - public void testWithFreshInputStream() { + @Test + public void withFreshInputStream() { SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); Resource resource = new ClassPathResource("test.xml", getClass()); new XmlBeanDefinitionReader(registry).loadBeanDefinitions(resource); @@ -139,11 +134,13 @@ public class XmlBeanDefinitionReaderTests extends TestCase { assertTrue(ObjectUtils.containsElement(aliases, "youralias")); } - public void testDtdValidationAutodetect() throws Exception { + @Test + public void dtdValidationAutodetect() throws Exception { doTestValidation("validateWithDtd.xml"); } - public void testXsdValidationAutodetect() throws Exception { + @Test + public void xsdValidationAutodetect() throws Exception { doTestValidation("validateWithXsd.xml"); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java index 011d727e94..25848af501 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java @@ -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,6 +21,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.junit.Before; +import org.junit.Test; + import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.BeanFactory; @@ -33,18 +36,21 @@ import org.springframework.tests.sample.beans.LifecycleBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @since 09.11.2003 */ +@SuppressWarnings({ "rawtypes", "unchecked" }) public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTests { private DefaultListableBeanFactory parent; private DefaultListableBeanFactory factory; - @Override - protected void setUp() { + @Before + public void setUp() { parent = new DefaultListableBeanFactory(); Map m = new HashMap(); m.put("name", "Albert"); @@ -86,26 +92,31 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest return factory; } + @Test @Override - public void testCount() { + public void count() { assertCount(24); } - public void testTestBeanCount() { + @Test + public void beanCount() { assertTestBeanCount(13); } - public void testLifecycleMethods() throws Exception { + @Test + public void lifecycleMethods() throws Exception { LifecycleBean bean = (LifecycleBean) getBeanFactory().getBean("lifecycle"); bean.businessMethod(); } - public void testProtectedLifecycleMethods() throws Exception { + @Test + public void protectedLifecycleMethods() throws Exception { ProtectedLifecycleBean bean = (ProtectedLifecycleBean) getBeanFactory().getBean("protectedLifecycle"); bean.businessMethod(); } - public void testDescriptionButNoProperties() throws Exception { + @Test + public void descriptionButNoProperties() throws Exception { TestBean validEmpty = (TestBean) getBeanFactory().getBean("validEmptyWithDescription"); assertEquals(0, validEmpty.getAge()); } @@ -113,7 +124,8 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest /** * Test that properties with name as well as id creating an alias up front. */ - public void testAutoAliasing() throws Exception { + @Test + public void autoAliasing() throws Exception { List beanNames = Arrays.asList(getListableBeanFactory().getBeanDefinitionNames()); TestBean tb1 = (TestBean) getBeanFactory().getBean("aliased"); @@ -172,7 +184,8 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest assertTrue(drs.containsKey(DummyReferencer.class.getName() + "#2")); } - public void testFactoryNesting() { + @Test + public void factoryNesting() { ITestBean father = (ITestBean) getBeanFactory().getBean("father"); assertTrue("Bean from root context", father != null); @@ -184,7 +197,8 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest assertTrue("Bean from root context", "Roderick".equals(rod.getName())); } - public void testFactoryReferences() { + @Test + public void factoryReferences() { DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); DummyReferencer ref = (DummyReferencer) getBeanFactory().getBean("factoryReferencer"); @@ -196,7 +210,8 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest assertTrue(ref2.getDummyFactory() == factory); } - public void testPrototypeReferences() { + @Test + public void prototypeReferences() { // check that not broken by circular reference resolution mechanism DummyReferencer ref1 = (DummyReferencer) getBeanFactory().getBean("prototypeReferencer"); assertTrue("Not referencing same bean twice", ref1.getTestBean1() != ref1.getTestBean2()); @@ -208,7 +223,8 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest assertTrue("Not referencing same bean twice", ref1.getTestBean1() != ref2.getTestBean2()); } - public void testBeanPostProcessor() throws Exception { + @Test + public void beanPostProcessor() throws Exception { TestBean kerry = (TestBean) getBeanFactory().getBean("kerry"); TestBean kathy = (TestBean) getBeanFactory().getBean("kathy"); DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); @@ -219,14 +235,16 @@ public class XmlListableBeanFactoryTests extends AbstractListableBeanFactoryTest assertTrue(factoryCreated.isPostProcessed()); } - public void testEmptyValues() { + @Test + public void emptyValues() { TestBean rod = (TestBean) getBeanFactory().getBean("rod"); TestBean kerry = (TestBean) getBeanFactory().getBean("kerry"); assertTrue("Touchy is empty", "".equals(rod.getTouchy())); assertTrue("Touchy is empty", "".equals(kerry.getTouchy())); } - public void testCommentsAndCdataInValue() { + @Test + public void commentsAndCdataInValue() { TestBean bean = (TestBean) getBeanFactory().getBean("commentsInValue"); assertEquals("Failed to handle comments and CDATA properly", "this is a ", bean.getName()); } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java index e0e2dba8da..a6d268610c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ByteArrayPropertyEditorTests.java @@ -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,19 +18,22 @@ package org.springframework.beans.propertyeditors; import java.beans.PropertyEditor; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Unit tests for the {@link ByteArrayPropertyEditor} class. * * @author Rick Evans */ -public final class ByteArrayPropertyEditorTests extends TestCase { +public final class ByteArrayPropertyEditorTests { - public void testSunnyDaySetAsText() throws Exception { + private final PropertyEditor byteEditor = new ByteArrayPropertyEditor(); + + @Test + public void sunnyDaySetAsText() throws Exception { final String text = "Hideous towns make me throw... up"; - - PropertyEditor byteEditor = new ByteArrayPropertyEditor(); byteEditor.setAsText(text); Object value = byteEditor.getValue(); @@ -43,8 +46,8 @@ public final class ByteArrayPropertyEditorTests extends TestCase { assertEquals(text, byteEditor.getAsText()); } - public void testGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception { - PropertyEditor byteEditor = new ByteArrayPropertyEditor(); + @Test + public void getAsTextReturnsEmptyStringIfValueIsNull() throws Exception { assertEquals("", byteEditor.getAsText()); byteEditor.setAsText(null); diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java index 24084ddcd0..5b7b47105c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CharArrayPropertyEditorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 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,19 +18,22 @@ package org.springframework.beans.propertyeditors; import java.beans.PropertyEditor; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Unit tests for the {@link CharArrayPropertyEditor} class. * * @author Rick Evans */ -public final class CharArrayPropertyEditorTests extends TestCase { +public final class CharArrayPropertyEditorTests { - public void testSunnyDaySetAsText() throws Exception { + private final PropertyEditor charEditor = new CharArrayPropertyEditor(); + + @Test + public void sunnyDaySetAsText() throws Exception { final String text = "Hideous towns make me throw... up"; - - PropertyEditor charEditor = new CharArrayPropertyEditor(); charEditor.setAsText(text); Object value = charEditor.getValue(); @@ -43,8 +46,8 @@ public final class CharArrayPropertyEditorTests extends TestCase { assertEquals(text, charEditor.getAsText()); } - public void testGetAsTextReturnsEmptyStringIfValueIsNull() throws Exception { - PropertyEditor charEditor = new CharArrayPropertyEditor(); + @Test + public void getAsTextReturnsEmptyStringIfValueIsNull() throws Exception { assertEquals("", charEditor.getAsText()); charEditor.setAsText(null); diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java index b1cc7ee18d..31e88a9cc3 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/PropertiesEditorTests.java @@ -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,7 +20,9 @@ import java.util.HashMap; import java.util.Map; import java.util.Properties; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Test the conversion of Strings to {@link java.util.Properties} objects, @@ -30,9 +32,10 @@ import junit.framework.TestCase; * @author Juergen Hoeller * @author Rick Evans */ -public class PropertiesEditorTests extends TestCase { +public class PropertiesEditorTests { - public void testOneProperty() { + @Test + public void oneProperty() { String s = "foo=bar"; PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); @@ -41,7 +44,8 @@ public class PropertiesEditorTests extends TestCase { assertTrue("foo=bar", p.get("foo").equals("bar")); } - public void testTwoProperties() { + @Test + public void twoProperties() { String s = "foo=bar with whitespace\n" + "me=mi"; PropertiesEditor pe= new PropertiesEditor(); @@ -52,7 +56,8 @@ public class PropertiesEditorTests extends TestCase { assertTrue("me=mi", p.get("me").equals("mi")); } - public void testHandlesEqualsInValue() { + @Test + public void handlesEqualsInValue() { String s = "foo=bar\n" + "me=mi\n" + "x=y=z"; @@ -65,7 +70,8 @@ public class PropertiesEditorTests extends TestCase { assertTrue("x='y=z'", p.get("x").equals("y=z")); } - public void testHandlesEmptyProperty() { + @Test + public void handlesEmptyProperty() { String s = "foo=bar\nme=mi\nx="; PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); @@ -76,7 +82,8 @@ public class PropertiesEditorTests extends TestCase { assertTrue("x='y=z'", p.get("x").equals("")); } - public void testHandlesEmptyPropertyWithoutEquals() { + @Test + public void handlesEmptyPropertyWithoutEquals() { String s = "foo\nme=mi\nx=x"; PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(s); @@ -89,7 +96,8 @@ public class PropertiesEditorTests extends TestCase { /** * Comments begin with # */ - public void testIgnoresCommentLinesAndEmptyLines() { + @Test + public void ignoresCommentLinesAndEmptyLines() { String s = "#Ignore this comment\n" + "foo=bar\n" + "#Another=comment more junk /\n" + @@ -110,7 +118,8 @@ public class PropertiesEditorTests extends TestCase { * We must ensure that comment lines beginning with whitespace are * still ignored: The standard syntax doesn't allow this on JDK 1.3. */ - public void testIgnoresLeadingSpacesAndTabs() { + @Test + public void ignoresLeadingSpacesAndTabs() { String s = " #Ignore this comment\n" + "\t\tfoo=bar\n" + "\t#Another comment more junk \n" + @@ -125,22 +134,25 @@ public class PropertiesEditorTests extends TestCase { assertTrue("me=mi", p.get("me").equals("mi")); } - public void testNull() { + @Test + public void nullValue() { PropertiesEditor pe= new PropertiesEditor(); pe.setAsText(null); Properties p = (Properties) pe.getValue(); assertEquals(0, p.size()); } - public void testEmptyString() { + @Test + public void emptyString() { PropertiesEditor pe = new PropertiesEditor(); pe.setAsText(""); Properties p = (Properties) pe.getValue(); assertTrue("empty string means empty properties", p.isEmpty()); } - public void testUsingMapAsValueSource() throws Exception { - Map map = new HashMap(); + @Test + public void usingMapAsValueSource() throws Exception { + Map map = new HashMap<>(); map.put("one", "1"); map.put("two", "2"); map.put("three", "3"); diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java index 894a4d7878..a720f6ca28 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/StringArrayPropertyEditorTests.java @@ -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. @@ -16,15 +16,18 @@ package org.springframework.beans.propertyeditors; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rick Evans * @author Juergen Hoeller */ -public class StringArrayPropertyEditorTests extends TestCase { +public class StringArrayPropertyEditorTests { - public void testWithDefaultSeparator() throws Exception { + @Test + public void withDefaultSeparator() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(); editor.setAsText("0,1,2"); Object value = editor.getValue(); @@ -37,7 +40,8 @@ public class StringArrayPropertyEditorTests extends TestCase { assertEquals("0,1,2", editor.getAsText()); } - public void testTrimByDefault() throws Exception { + @Test + public void trimByDefault() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(); editor.setAsText(" 0,1 , 2 "); Object value = editor.getValue(); @@ -48,7 +52,8 @@ public class StringArrayPropertyEditorTests extends TestCase { assertEquals("0,1,2", editor.getAsText()); } - public void testNoTrim() throws Exception { + @Test + public void noTrim() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(",",false,false); editor.setAsText(" 0,1 , 2 "); Object value = editor.getValue(); @@ -60,7 +65,8 @@ public class StringArrayPropertyEditorTests extends TestCase { assertEquals(" 0,1 , 2 ", editor.getAsText()); } - public void testWithCustomSeparator() throws Exception { + @Test + public void withCustomSeparator() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(":"); editor.setAsText("0:1:2"); Object value = editor.getValue(); @@ -72,7 +78,8 @@ public class StringArrayPropertyEditorTests extends TestCase { assertEquals("0:1:2", editor.getAsText()); } - public void testWithCharsToDelete() throws Exception { + @Test + public void withCharsToDelete() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(",", "\r\n", false); editor.setAsText("0\r,1,\n2"); Object value = editor.getValue(); @@ -84,7 +91,8 @@ public class StringArrayPropertyEditorTests extends TestCase { assertEquals("0,1,2", editor.getAsText()); } - public void testWithEmptyArray() throws Exception { + @Test + public void withEmptyArray() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(); editor.setAsText(""); Object value = editor.getValue(); @@ -92,7 +100,8 @@ public class StringArrayPropertyEditorTests extends TestCase { assertEquals(0, ((String[]) value).length); } - public void testWithEmptyArrayAsNull() throws Exception { + @Test + public void withEmptyArrayAsNull() throws Exception { StringArrayPropertyEditor editor = new StringArrayPropertyEditor(",", true); editor.setAsText(""); assertNull(editor.getValue()); diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java index b819fb9679..f234eea4b9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/ZoneIdEditorTests.java @@ -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,19 @@ package org.springframework.beans.propertyeditors; import java.time.ZoneId; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Nicholas Williams */ -public class ZoneIdEditorTests extends TestCase { +public class ZoneIdEditorTests { - public void testAmericaChicago() { - ZoneIdEditor editor = new ZoneIdEditor(); + private final ZoneIdEditor editor = new ZoneIdEditor(); + + @Test + public void americaChicago() { editor.setAsText("America/Chicago"); ZoneId zoneId = (ZoneId) editor.getValue(); @@ -36,8 +40,8 @@ public class ZoneIdEditorTests extends TestCase { assertEquals("The text version is not correct.", "America/Chicago", editor.getAsText()); } - public void testAmericaLosAngeles() { - ZoneIdEditor editor = new ZoneIdEditor(); + @Test + public void americaLosAngeles() { editor.setAsText("America/Los_Angeles"); ZoneId zoneId = (ZoneId) editor.getValue(); @@ -47,16 +51,14 @@ public class ZoneIdEditorTests extends TestCase { assertEquals("The text version is not correct.", "America/Los_Angeles", editor.getAsText()); } - public void testGetNullAsText() { - ZoneIdEditor editor = new ZoneIdEditor(); - + @Test + public void getNullAsText() { assertEquals("The returned value is not correct.", "", editor.getAsText()); } - public void testGetValueAsText() { - ZoneIdEditor editor = new ZoneIdEditor(); + @Test + public void getValueAsText() { editor.setValue(ZoneId.of("America/New_York")); - assertEquals("The text version is not correct.", "America/New_York", editor.getAsText()); } diff --git a/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java b/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java index 4c5e108bea..5837c9566d 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/javamail/ConfigurableMimeFileTypeMapTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 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,18 +18,21 @@ package org.springframework.mail.javamail; import java.io.File; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller */ -public class ConfigurableMimeFileTypeMapTests extends TestCase { +public class ConfigurableMimeFileTypeMapTests { - public void testAgainstDefaultConfiguration() throws Exception { + @Test + public void againstDefaultConfiguration() throws Exception { ConfigurableMimeFileTypeMap ftm = new ConfigurableMimeFileTypeMap(); ftm.afterPropertiesSet(); @@ -41,12 +44,14 @@ public class ConfigurableMimeFileTypeMapTests extends TestCase { assertEquals("Invalid default content type", "application/octet-stream", ftm.getContentType("foobar.foo")); } - public void testAgainstDefaultConfigurationWithFilePath() throws Exception { + @Test + public void againstDefaultConfigurationWithFilePath() throws Exception { ConfigurableMimeFileTypeMap ftm = new ConfigurableMimeFileTypeMap(); assertEquals("Invalid content type for HTM", "text/html", ftm.getContentType(new File("/tmp/foobar.HTM"))); } - public void testWithAdditionalMappings() throws Exception { + @Test + public void withAdditionalMappings() throws Exception { ConfigurableMimeFileTypeMap ftm = new ConfigurableMimeFileTypeMap(); ftm.setMappings(new String[] {"foo/bar HTM foo", "foo/cpp c++"}); ftm.afterPropertiesSet(); @@ -56,7 +61,8 @@ public class ConfigurableMimeFileTypeMapTests extends TestCase { assertEquals("Invalid content type for foo - new mapping didn't work", "foo/bar", ftm.getContentType("bar.foo")); } - public void testWithCustomMappingLocation() throws Exception { + @Test + public void withCustomMappingLocation() throws Exception { Resource resource = new ClassPathResource("test.mime.types", getClass()); ConfigurableMimeFileTypeMap ftm = new ConfigurableMimeFileTypeMap(); diff --git a/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java b/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java index 4b397425a5..fff03d58a6 100644 --- a/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java +++ b/spring-context-support/src/test/java/org/springframework/mail/javamail/InternetAddressEditorTests.java @@ -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,62 +16,62 @@ package org.springframework.mail.javamail; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Brian Hanafee + * @author Sam Brannen * @since 09.07.2005 */ -public class InternetAddressEditorTests extends TestCase { +public class InternetAddressEditorTests { private static final String EMPTY = ""; private static final String SIMPLE = "nobody@nowhere.com"; private static final String BAD = "("; - private InternetAddressEditor editor; + private final InternetAddressEditor editor = new InternetAddressEditor(); - @Override - protected void setUp() { - editor = new InternetAddressEditor(); - } - public void testUninitialized() { + @Test + public void uninitialized() { assertEquals("Uninitialized editor did not return empty value string", EMPTY, editor.getAsText()); } - public void testSetNull() { + @Test + public void setNull() { editor.setAsText(null); assertEquals("Setting null did not result in empty value string", EMPTY, editor.getAsText()); } - public void testSetEmpty() { + @Test + public void setEmpty() { editor.setAsText(EMPTY); assertEquals("Setting empty string did not result in empty value string", EMPTY, editor.getAsText()); } - public void testAllWhitespace() { + @Test + public void allWhitespace() { editor.setAsText(" "); assertEquals("All whitespace was not recognized", EMPTY, editor.getAsText()); } - public void testSimpleGoodAddess() { + @Test + public void simpleGoodAddess() { editor.setAsText(SIMPLE); assertEquals("Simple email address failed", SIMPLE, editor.getAsText()); } - public void testExcessWhitespace() { + @Test + public void excessWhitespace() { editor.setAsText(" " + SIMPLE + " "); assertEquals("Whitespace was not stripped", SIMPLE, editor.getAsText()); } - public void testSimpleBadAddress() { - try { - editor.setAsText(BAD); - fail("Should have failed on \"" + BAD + "\", instead got " + editor.getAsText()); - } - catch (IllegalArgumentException e) { - // Passed the test - } + @Test(expected = IllegalArgumentException.class) + public void simpleBadAddress() { + editor.setAsText(BAD); } } diff --git a/spring-context-support/src/test/java/org/springframework/ui/jasperreports/JasperReportsUtilsTests.java b/spring-context-support/src/test/java/org/springframework/ui/jasperreports/JasperReportsUtilsTests.java index 5ec7234396..89f4614b89 100644 --- a/spring-context-support/src/test/java/org/springframework/ui/jasperreports/JasperReportsUtilsTests.java +++ b/spring-context-support/src/test/java/org/springframework/ui/jasperreports/JasperReportsUtilsTests.java @@ -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. @@ -41,13 +41,13 @@ import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRPdfExporterParameter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import net.sf.jasperreports.engine.util.JRLoader; + import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.junit.BeforeClass; import org.junit.Test; - import org.springframework.core.io.ClassPathResource; import org.springframework.tests.Assume; @@ -58,6 +58,7 @@ import static org.junit.Assert.*; * @author Juergen Hoeller * @since 18.11.2004 */ +@SuppressWarnings("deprecation") public class JasperReportsUtilsTests { @BeforeClass @@ -66,7 +67,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsCsvWithDataSource() throws Exception { + public void renderAsCsvWithDataSource() throws Exception { StringWriter writer = new StringWriter(); JasperReportsUtils.renderAsCsv(getReport(), getParameters(), getDataSource(), writer); String output = writer.getBuffer().toString(); @@ -74,7 +75,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsCsvWithCollection() throws Exception { + public void renderAsCsvWithCollection() throws Exception { StringWriter writer = new StringWriter(); JasperReportsUtils.renderAsCsv(getReport(), getParameters(), getData(), writer); String output = writer.getBuffer().toString(); @@ -82,7 +83,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsCsvWithExporterParameters() throws Exception { + public void renderAsCsvWithExporterParameters() throws Exception { StringWriter writer = new StringWriter(); Map exporterParameters = new HashMap(); exporterParameters.put(JRCsvExporterParameter.FIELD_DELIMITER, "~"); @@ -93,7 +94,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsHtmlWithDataSource() throws Exception { + public void renderAsHtmlWithDataSource() throws Exception { StringWriter writer = new StringWriter(); JasperReportsUtils.renderAsHtml(getReport(), getParameters(), getDataSource(), writer); String output = writer.getBuffer().toString(); @@ -101,7 +102,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsHtmlWithCollection() throws Exception { + public void renderAsHtmlWithCollection() throws Exception { StringWriter writer = new StringWriter(); JasperReportsUtils.renderAsHtml(getReport(), getParameters(), getData(), writer); String output = writer.getBuffer().toString(); @@ -109,7 +110,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsHtmlWithExporterParameters() throws Exception { + public void renderAsHtmlWithExporterParameters() throws Exception { StringWriter writer = new StringWriter(); Map exporterParameters = new HashMap(); String uri = "/my/uri"; @@ -121,7 +122,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsPdfWithDataSource() throws Exception { + public void renderAsPdfWithDataSource() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); JasperReportsUtils.renderAsPdf(getReport(), getParameters(), getDataSource(), os); byte[] output = os.toByteArray(); @@ -129,7 +130,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsPdfWithCollection() throws Exception { + public void renderAsPdfWithCollection() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); JasperReportsUtils.renderAsPdf(getReport(), getParameters(), getData(), os); byte[] output = os.toByteArray(); @@ -137,7 +138,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsPdfWithExporterParameters() throws Exception { + public void renderAsPdfWithExporterParameters() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); Map exporterParameters = new HashMap(); exporterParameters.put(JRPdfExporterParameter.PDF_VERSION, JRPdfExporterParameter.PDF_VERSION_1_6.toString()); @@ -148,7 +149,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsXlsWithDataSource() throws Exception { + public void renderAsXlsWithDataSource() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); JasperReportsUtils.renderAsXls(getReport(), getParameters(), getDataSource(), os); byte[] output = os.toByteArray(); @@ -156,7 +157,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsXlsWithCollection() throws Exception { + public void renderAsXlsWithCollection() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); JasperReportsUtils.renderAsXls(getReport(), getParameters(), getData(), os); byte[] output = os.toByteArray(); @@ -164,7 +165,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderAsXlsWithExporterParameters() throws Exception { + public void renderAsXlsWithExporterParameters() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); Map exporterParameters = new HashMap(); @@ -178,7 +179,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderWithWriter() throws Exception { + public void renderWithWriter() throws Exception { StringWriter writer = new StringWriter(); JasperPrint print = JasperFillManager.fillReport(getReport(), getParameters(), getDataSource()); JasperReportsUtils.render(new JRHtmlExporter(), print, writer); @@ -187,7 +188,7 @@ public class JasperReportsUtilsTests { } @Test - public void testRenderWithOutputStream() throws Exception { + public void renderWithOutputStream() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); JasperPrint print = JasperFillManager.fillReport(getReport(), getParameters(), getDataSource()); JasperReportsUtils.render(new JRPdfExporter(), print, os); @@ -214,6 +215,7 @@ public class JasperReportsUtilsTests { assertTrue("Output should start with %PDF", translated.startsWith("%PDF")); } + @SuppressWarnings("resource") private void assertXlsOutputCorrect(byte[] output) throws Exception { HSSFWorkbook workbook = new HSSFWorkbook(new ByteArrayInputStream(output)); HSSFSheet sheet = workbook.getSheetAt(0); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java index b70a5b4955..07a1d71c3e 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/PropertyDependentAspectTests.java @@ -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. @@ -21,7 +21,6 @@ import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.junit.Test; - import org.springframework.aop.framework.Advised; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -36,25 +35,29 @@ import static org.junit.Assert.*; * @author Juergen Hoeller * @author Chris Beams */ +@SuppressWarnings("resource") public final class PropertyDependentAspectTests { @Test - public void testPropertyDependentAspectWithPropertyDeclaredBeforeAdvice() throws Exception { + public void propertyDependentAspectWithPropertyDeclaredBeforeAdvice() + throws Exception { checkXmlAspect(getClass().getSimpleName() + "-before.xml"); } @Test - public void testPropertyDependentAspectWithPropertyDeclaredAfterAdvice() throws Exception { + public void propertyDependentAspectWithPropertyDeclaredAfterAdvice() throws Exception { checkXmlAspect(getClass().getSimpleName() + "-after.xml"); } @Test - public void testPropertyDependentAtAspectJAspectWithPropertyDeclaredBeforeAdvice() throws Exception { + public void propertyDependentAtAspectJAspectWithPropertyDeclaredBeforeAdvice() + throws Exception { checkAtAspectJAspect(getClass().getSimpleName() + "-atAspectJ-before.xml"); } @Test - public void testPropertyDependentAtAspectJAspectWithPropertyDeclaredAfterAdvice() throws Exception { + public void propertyDependentAtAspectJAspectWithPropertyDeclaredAfterAdvice() + throws Exception { checkAtAspectJAspect(getClass().getSimpleName() + "-atAspectJ-after.xml"); } diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java index 9ef470f437..693e9a219d 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/TargetPointcutSelectionTests.java @@ -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,6 +18,7 @@ package org.springframework.aop.aspectj; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; + import org.junit.Before; import org.junit.Test; @@ -27,7 +28,7 @@ import static org.junit.Assert.*; /** * Tests for target selection matching (see SPR-3783). - * Thanks to Tomasz Blachowicz for the bug report! + *

Thanks to Tomasz Blachowicz for the bug report! * * @author Ramnivas Laddad * @author Chris Beams @@ -46,6 +47,7 @@ public final class TargetPointcutSelectionTests { @Before + @SuppressWarnings("resource") public void setUp() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass()); @@ -63,7 +65,7 @@ public final class TargetPointcutSelectionTests { @Test - public void testTargetSelectionForMatchedType() { + public void targetSelectionForMatchedType() { testImpl1.interfaceMethod(); assertEquals("Should have been advised by POJO advice for impl", 1, testAspectForTestImpl1.count); assertEquals("Should have been advised by POJO advice for base type", 1, testAspectForAbstractTestImpl.count); @@ -71,7 +73,7 @@ public final class TargetPointcutSelectionTests { } @Test - public void testTargetNonSelectionForMismatchedType() { + public void targetNonSelectionForMismatchedType() { testImpl2.interfaceMethod(); assertEquals("Shouldn't have been advised by POJO advice for impl", 0, testAspectForTestImpl1.count); assertEquals("Should have been advised by POJO advice for base type", 1, testAspectForAbstractTestImpl.count); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java index 1b859b8095..764c39fad2 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.java @@ -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. @@ -22,7 +22,6 @@ import java.lang.annotation.RetentionPolicy; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.junit.Test; - import org.springframework.context.support.ClassPathXmlApplicationContext; import static org.junit.Assert.*; @@ -32,13 +31,17 @@ import static org.junit.Assert.*; * @author Chris Beams */ public final class ThisAndTargetSelectionOnlyPointcutsAtAspectJTests { - public TestInterface testBean; - public TestInterface testAnnotatedClassBean; - public TestInterface testAnnotatedMethodBean; - protected Counter counter; + private TestInterface testBean; + + private TestInterface testAnnotatedClassBean; + + private TestInterface testAnnotatedMethodBean; + + private Counter counter; @org.junit.Before + @SuppressWarnings("resource") public void setUp() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass()); @@ -50,56 +53,56 @@ public final class ThisAndTargetSelectionOnlyPointcutsAtAspectJTests { } @Test - public void testThisAsClassDoesNotMatch() { + public void thisAsClassDoesNotMatch() { testBean.doIt(); assertEquals(0, counter.thisAsClassCounter); } @Test - public void testThisAsInterfaceMatch() { + public void thisAsInterfaceMatch() { testBean.doIt(); assertEquals(1, counter.thisAsInterfaceCounter); } @Test - public void testTargetAsClassDoesMatch() { + public void targetAsClassDoesMatch() { testBean.doIt(); assertEquals(1, counter.targetAsClassCounter); } @Test - public void testTargetAsInterfaceMatch() { + public void targetAsInterfaceMatch() { testBean.doIt(); assertEquals(1, counter.targetAsInterfaceCounter); } @Test - public void testThisAsClassAndTargetAsClassCounterNotMatch() { + public void thisAsClassAndTargetAsClassCounterNotMatch() { testBean.doIt(); assertEquals(0, counter.thisAsClassAndTargetAsClassCounter); } @Test - public void testThisAsInterfaceAndTargetAsInterfaceCounterMatch() { + public void thisAsInterfaceAndTargetAsInterfaceCounterMatch() { testBean.doIt(); assertEquals(1, counter.thisAsInterfaceAndTargetAsInterfaceCounter); } @Test - public void testThisAsInterfaceAndTargetAsClassCounterMatch() { + public void thisAsInterfaceAndTargetAsClassCounterMatch() { testBean.doIt(); assertEquals(1, counter.thisAsInterfaceAndTargetAsInterfaceCounter); } @Test - public void testAtTargetClassAnnotationMatch() { + public void atTargetClassAnnotationMatch() { testAnnotatedClassBean.doIt(); assertEquals(1, counter.atTargetClassAnnotationCounter); } @Test - public void testAtAnnotationMethodAnnotationMatch() { + public void atAnnotationMethodAnnotationMatch() { testAnnotatedMethodBean.doIt(); assertEquals(1, counter.atAnnotationMethodAnnotationCounter); } diff --git a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java index 6fc672aab4..666dcd4555 100644 --- a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java @@ -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. @@ -22,16 +22,19 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Locale; +import org.junit.Before; import org.junit.Test; - import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.AbstractListableBeanFactoryTests; import org.springframework.tests.sample.beans.LifecycleBean; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller + * @author Sam Brannen */ public abstract class AbstractApplicationContextTests extends AbstractListableBeanFactoryTests { @@ -45,8 +48,8 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe protected TestListener parentListener = new TestListener(); - @Override - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { this.applicationContext = createContext(); } @@ -67,7 +70,8 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe */ protected abstract ConfigurableApplicationContext createContext() throws Exception; - public void testContextAwareSingletonWasCalledBack() throws Exception { + @Test + public void contextAwareSingletonWasCalledBack() throws Exception { ACATester aca = (ACATester) applicationContext.getBean("aca"); assertTrue("has had context set", aca.getApplicationContext() == applicationContext); Object aca2 = applicationContext.getBean("aca"); @@ -75,7 +79,8 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe assertTrue("Says is singleton", applicationContext.isSingleton("aca")); } - public void testContextAwarePrototypeWasCalledBack() throws Exception { + @Test + public void contextAwarePrototypeWasCalledBack() throws Exception { ACATester aca = (ACATester) applicationContext.getBean("aca-prototype"); assertTrue("has had context set", aca.getApplicationContext() == applicationContext); Object aca2 = applicationContext.getBean("aca-prototype"); @@ -83,30 +88,36 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype")); } - public void testParentNonNull() { + @Test + public void parentNonNull() { assertTrue("parent isn't null", applicationContext.getParent() != null); } - public void testGrandparentNull() { + @Test + public void grandparentNull() { assertTrue("grandparent is null", applicationContext.getParent().getParent() == null); } - public void testOverrideWorked() throws Exception { + @Test + public void overrideWorked() throws Exception { TestBean rod = (TestBean) applicationContext.getParent().getBean("rod"); assertTrue("Parent's name differs", rod.getName().equals("Roderick")); } - public void testGrandparentDefinitionFound() throws Exception { + @Test + public void grandparentDefinitionFound() throws Exception { TestBean dad = (TestBean) applicationContext.getBean("father"); assertTrue("Dad has correct name", dad.getName().equals("Albert")); } - public void testGrandparentTypedDefinitionFound() throws Exception { + @Test + public void grandparentTypedDefinitionFound() throws Exception { TestBean dad = applicationContext.getBean("father", TestBean.class); assertTrue("Dad has correct name", dad.getName().equals("Albert")); } - public void testCloseTriggersDestroy() { + @Test + public void closeTriggersDestroy() { LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle"); assertTrue("Not destroyed", !lb.isDestroyed()); applicationContext.close(); @@ -121,25 +132,21 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe assertTrue("Destroyed", lb.isDestroyed()); } - public void testMessageSource() throws NoSuchMessageException { + @Test(expected = NoSuchMessageException.class) + public void messageSource() throws NoSuchMessageException { assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault())); assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault())); - try { - applicationContext.getMessage("code0", null, Locale.getDefault()); - fail("looking for code0 should throw a NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // that's how it should be - } + applicationContext.getMessage("code0", null, Locale.getDefault()); } - public void testEvents() throws Exception { + @Test + public void events() throws Exception { doTestEvents(this.listener, this.parentListener, new MyEvent(this)); } @Test - public void testEventsWithNoSource() throws Exception { + public void eventsWithNoSource() throws Exception { // See SPR-10945 Serialized events result in a null source MyEvent event = new MyEvent(this); ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -162,7 +169,8 @@ public abstract class AbstractApplicationContextTests extends AbstractListableBe assertTrue("1 parent events after publication", parentListener.getEventCount() == 1); } - public void testBeanAutomaticallyHearsEvents() throws Exception { + @Test + public void beanAutomaticallyHearsEvents() throws Exception { //String[] listenerNames = ((ListableBeanFactory) applicationContext).getBeanDefinitionNames(ApplicationListener.class); //assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens")); BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens"); diff --git a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java index 8001716e48..6cdeeeb681 100644 --- a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java +++ b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java @@ -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,7 +20,7 @@ import java.util.Collection; import java.util.Map; import java.util.Set; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; @@ -28,11 +28,13 @@ import org.springframework.beans.factory.access.BootstrapException; import org.springframework.context.ApplicationContext; import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; +import static org.junit.Assert.*; + /** * @author Colin Sampaleanu * @author Chris Beams */ -public final class ContextJndiBeanFactoryLocatorTests extends TestCase { +public final class ContextJndiBeanFactoryLocatorTests { private static final String BEAN_FACTORY_PATH_ENVIRONMENT_KEY = "java:comp/env/ejb/BeanFactoryPath"; @@ -45,7 +47,8 @@ public final class ContextJndiBeanFactoryLocatorTests extends TestCase { private static final String PARENT_CONTEXT = FQ_PATH + CLASSNAME + "-parent.xml"; - public void testBeanFactoryPathRequiredFromJndiEnvironment() throws Exception { + @Test + public void beanFactoryPathRequiredFromJndiEnvironment() throws Exception { // Set up initial context but don't bind anything SimpleNamingContextBuilder.emptyActivatedContextBuilder(); @@ -60,7 +63,8 @@ public final class ContextJndiBeanFactoryLocatorTests extends TestCase { } } - public void testBeanFactoryPathFromJndiEnvironmentNotFound() throws Exception { + @Test + public void beanFactoryPathFromJndiEnvironmentNotFound() throws Exception { SimpleNamingContextBuilder sncb = SimpleNamingContextBuilder.emptyActivatedContextBuilder(); String bogusPath = "RUBBISH/com/xxxx/framework/server/test1.xml"; @@ -79,7 +83,8 @@ public final class ContextJndiBeanFactoryLocatorTests extends TestCase { } } - public void testBeanFactoryPathFromJndiEnvironmentNotValidXml() throws Exception { + @Test + public void beanFactoryPathFromJndiEnvironmentNotValidXml() throws Exception { SimpleNamingContextBuilder sncb = SimpleNamingContextBuilder.emptyActivatedContextBuilder(); String nonXmlPath = "com/xxxx/framework/server/SlsbEndpointBean.class"; @@ -98,7 +103,8 @@ public final class ContextJndiBeanFactoryLocatorTests extends TestCase { } } - public void testBeanFactoryPathFromJndiEnvironmentWithSingleFile() throws Exception { + @Test + public void beanFactoryPathFromJndiEnvironmentWithSingleFile() throws Exception { SimpleNamingContextBuilder sncb = SimpleNamingContextBuilder.emptyActivatedContextBuilder(); // Set up initial context @@ -110,7 +116,8 @@ public final class ContextJndiBeanFactoryLocatorTests extends TestCase { assertTrue(bf instanceof ApplicationContext); } - public void testBeanFactoryPathFromJndiEnvironmentWithMultipleFiles() throws Exception { + @Test + public void beanFactoryPathFromJndiEnvironmentWithMultipleFiles() throws Exception { SimpleNamingContextBuilder sncb = SimpleNamingContextBuilder.emptyActivatedContextBuilder(); String path = String.format("%s %s", COLLECTIONS_CONTEXT, PARENT_CONTEXT); diff --git a/spring-context/src/test/java/org/springframework/context/access/DefaultLocatorFactoryTests.java b/spring-context/src/test/java/org/springframework/context/access/DefaultLocatorFactoryTests.java index 633127e84b..0dbbcc7087 100644 --- a/spring-context/src/test/java/org/springframework/context/access/DefaultLocatorFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/context/access/DefaultLocatorFactoryTests.java @@ -16,19 +16,22 @@ package org.springframework.context.access; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; import org.springframework.beans.factory.access.BeanFactoryLocator; /** * @author Colin Sampaleanu */ -public class DefaultLocatorFactoryTests extends TestCase { +public class DefaultLocatorFactoryTests { /* * Class to test for BeanFactoryLocator getInstance() */ - public void testGetInstance() { + @Test + public void getInstance() { BeanFactoryLocator bf = DefaultLocatorFactory.getInstance(); BeanFactoryLocator bf2 = DefaultLocatorFactory.getInstance(); assertTrue(bf.equals(bf2)); @@ -37,7 +40,8 @@ public class DefaultLocatorFactoryTests extends TestCase { /* * Class to test for BeanFactoryLocator getInstance(String) */ - public void testGetInstanceString() { + @Test + public void getInstanceString() { BeanFactoryLocator bf = DefaultLocatorFactory.getInstance("my-bean-refs.xml"); BeanFactoryLocator bf2 = DefaultLocatorFactory.getInstance("my-bean-refs.xml"); assertTrue(bf.equals(bf2)); diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java index 99110dba16..4fd29e896c 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ImportSelectorTests.java @@ -27,7 +27,6 @@ import org.hamcrest.Matcher; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.InOrder; - import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanFactory; @@ -35,7 +34,6 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.EnvironmentAware; -import org.springframework.context.MessageSource; import org.springframework.context.ResourceLoaderAware; import org.springframework.context.annotation.ImportBeanDefinitionRegistrarTests.SampleRegistrar; import org.springframework.core.Ordered; @@ -53,6 +51,7 @@ import static org.mockito.Mockito.*; * * @author Phillip Webb */ +@SuppressWarnings("resource") public class ImportSelectorTests { static Map, String> importFrom = new HashMap, String>(); @@ -81,7 +80,6 @@ public class ImportSelectorTests { @Test public void invokeAwareMethodsInImportSelector() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AwareConfig.class); - context.getBean(MessageSource.class); assertThat(SampleRegistrar.beanFactory, is((BeanFactory) context.getBeanFactory())); assertThat(SampleRegistrar.classLoader, is(context.getBeanFactory().getBeanClassLoader())); assertThat(SampleRegistrar.resourceLoader, is(notNullValue())); @@ -90,7 +88,7 @@ public class ImportSelectorTests { @Test public void correctMetaDataOnIndirectImports() throws Exception { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(IndirectConfig.class); + new AnnotationConfigApplicationContext(IndirectConfig.class); Matcher isFromIndirect = equalTo(IndirectImport.class.getName()); assertThat(importFrom.get(ImportSelector1.class), isFromIndirect); assertThat(importFrom.get(ImportSelector2.class), isFromIndirect); diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java index 26ff3afb6b..72ed279f39 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportResourceTests.java @@ -50,7 +50,7 @@ import static org.junit.Assert.*; public class ImportResourceTests { @Test - public void testImportXml() { + public void importXml() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlConfig.class); assertTrue("did not contain java-declared bean", ctx.containsBean("javaDeclaredBean")); assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean")); @@ -61,7 +61,7 @@ public class ImportResourceTests { @Ignore // TODO: SPR-6310 @Test - public void testImportXmlWithRelativePath() { + public void importXmlWithRelativePath() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithRelativePathConfig.class); assertTrue("did not contain java-declared bean", ctx.containsBean("javaDeclaredBean")); assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean")); @@ -72,7 +72,7 @@ public class ImportResourceTests { @Ignore // TODO: SPR-6310 @Test - public void testImportXmlByConvention() { + public void importXmlByConvention() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( ImportXmlByConventionConfig.class); assertTrue("context does not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean")); @@ -80,14 +80,14 @@ public class ImportResourceTests { } @Test - public void testImportXmlIsInheritedFromSuperclassDeclarations() { + public void importXmlIsInheritedFromSuperclassDeclarations() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(FirstLevelSubConfig.class); assertTrue(ctx.containsBean("xmlDeclaredBean")); ctx.close(); } @Test - public void testImportXmlIsMergedFromSuperclassDeclarations() { + public void importXmlIsMergedFromSuperclassDeclarations() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SecondLevelSubConfig.class); assertTrue("failed to pick up second-level-declared XML bean", ctx.containsBean("secondLevelXmlDeclaredBean")); assertTrue("failed to pick up parent-declared XML bean", ctx.containsBean("xmlDeclaredBean")); @@ -95,7 +95,7 @@ public class ImportResourceTests { } @Test - public void testImportXmlWithNamespaceConfig() { + public void importXmlWithNamespaceConfig() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithAopNamespaceConfig.class); Object bean = ctx.getBean("proxiedXmlBean"); assertTrue(AopUtils.isAopProxy(bean)); @@ -103,7 +103,7 @@ public class ImportResourceTests { } @Test - public void testImportXmlWithOtherConfigurationClass() { + public void importXmlWithOtherConfigurationClass() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithConfigurationClass.class); assertTrue("did not contain java-declared bean", ctx.containsBean("javaDeclaredBean")); assertTrue("did not contain xml-declared bean", ctx.containsBean("xmlDeclaredBean")); @@ -114,7 +114,7 @@ public class ImportResourceTests { @Ignore // TODO: SPR-6327 @Test - public void testImportDifferentResourceTypes() { + public void importDifferentResourceTypes() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SubResourceConfig.class); assertTrue(ctx.containsBean("propertiesDeclaredBean")); assertTrue(ctx.containsBean("xmlDeclaredBean")); @@ -134,7 +134,7 @@ public class ImportResourceTests { } @Test - public void testImportXmlWithAutowiredConfig() { + public void importXmlWithAutowiredConfig() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlAutowiredConfig.class); String name = ctx.getBean("xmlBeanName", String.class); assertThat(name, equalTo("xml.declared")); @@ -142,7 +142,7 @@ public class ImportResourceTests { } @Test - public void testImportNonXmlResource() { + public void importNonXmlResource() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportNonXmlResourceConfig.class); assertTrue(ctx.containsBean("propertiesDeclaredBean")); ctx.close(); diff --git a/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java b/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java index 380f29125d..a69a60b9cf 100644 --- a/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/LifecycleEventTests.java @@ -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,7 @@ package org.springframework.context.event; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; @@ -24,13 +24,16 @@ import org.springframework.context.ApplicationListener; import org.springframework.context.Lifecycle; import org.springframework.context.support.StaticApplicationContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher * @author Juergen Hoeller */ -public class LifecycleEventTests extends TestCase { +public class LifecycleEventTests { - public void testContextStartedEvent() { + @Test + public void contextStartedEvent() { StaticApplicationContext context = new StaticApplicationContext(); context.registerSingleton("lifecycle", LifecycleTestBean.class); context.registerSingleton("listener", LifecycleListener.class); @@ -45,7 +48,8 @@ public class LifecycleEventTests extends TestCase { assertSame(context, listener.getApplicationContext()); } - public void testContextStoppedEvent() { + @Test + public void contextStoppedEvent() { StaticApplicationContext context = new StaticApplicationContext(); context.registerSingleton("lifecycle", LifecycleTestBean.class); context.registerSingleton("listener", LifecycleListener.class); diff --git a/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java b/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java index f0d732c718..527ca333dc 100644 --- a/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/SerializableBeanFactoryMemoryLeakTests.java @@ -1,3 +1,19 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.context.support; import java.lang.reflect.Field; @@ -5,6 +21,7 @@ import java.util.Map; import org.junit.AfterClass; import org.junit.BeforeClass; + import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java index 981b9ef883..aad1246f62 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java @@ -20,6 +20,8 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; +import org.junit.Test; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader; import org.springframework.context.ACATester; @@ -34,6 +36,8 @@ import org.springframework.core.io.Resource; import org.springframework.core.io.support.EncodedResource; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * Tests for static application context with custom application event multicaster. * @@ -43,7 +47,6 @@ public class StaticApplicationContextMulticasterTests extends AbstractApplicatio protected StaticApplicationContext sac; - /** Run for each test */ @Override protected ConfigurableApplicationContext createContext() throws Exception { StaticApplicationContext parent = new StaticApplicationContext(); @@ -74,16 +77,17 @@ public class StaticApplicationContextMulticasterTests extends AbstractApplicatio return sac; } - /** Overridden */ + @Test @Override - public void testCount() { + public void count() { assertCount(15); } + @Test @Override - public void testEvents() throws Exception { + public void events() throws Exception { TestApplicationEventMulticaster.counter = 0; - super.testEvents(); + super.events(); assertEquals(1, TestApplicationEventMulticaster.counter); } diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java index 694985b211..8a30b5424b 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java @@ -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,6 +20,8 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; +import org.junit.Test; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader; import org.springframework.context.ACATester; @@ -38,7 +40,6 @@ public class StaticApplicationContextTests extends AbstractApplicationContextTes protected StaticApplicationContext sac; - /** Run for each test */ @Override protected ConfigurableApplicationContext createContext() throws Exception { StaticApplicationContext parent = new StaticApplicationContext(); @@ -66,9 +67,9 @@ public class StaticApplicationContextTests extends AbstractApplicationContextTes return sac; } - /** Overridden */ + @Test @Override - public void testCount() { + public void count() { assertCount(15); } diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java index 908f5652c1..634dfa9e91 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java @@ -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,6 +21,10 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader; import org.springframework.context.ACATester; @@ -31,9 +35,12 @@ import org.springframework.context.MessageSourceResolvable; import org.springframework.context.NoSuchMessageException; import org.springframework.core.io.ClassPathResource; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller + * @author Sam Brannen */ public class StaticMessageSourceTests extends AbstractApplicationContextTests { @@ -48,27 +55,34 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { protected StaticApplicationContext sac; - /** Overridden */ + @Rule + public final ExpectedException exception = ExpectedException.none(); + + + @Test @Override - public void testCount() { + public void count() { // These are only checked for current Ctx (not parent ctx) assertCount(15); } + @Test @Override - public void testMessageSource() throws NoSuchMessageException { + public void messageSource() throws NoSuchMessageException { // Do nothing here since super is looking for errorCodes we // do NOT have in the Context } - public void testGetMessageWithDefaultPassedInAndFoundInMsgCatalog() { + @Test + public void getMessageWithDefaultPassedInAndFoundInMsgCatalog() { // Try with Locale.US assertTrue("valid msg from staticMsgSource with default msg passed in returned msg from msg catalog for Locale.US", sac.getMessage("message.format.example2", null, "This is a default msg if not found in MessageSource.", Locale.US) .equals("This is a test message in the message catalog with no args.")); } - public void testGetMessageWithDefaultPassedInAndNotFoundInMsgCatalog() { + @Test + public void getMessageWithDefaultPassedInAndNotFoundInMsgCatalog() { // Try with Locale.US assertTrue("bogus msg from staticMsgSource with default msg passed in returned default msg for Locale.US", sac.getMessage("bogus.message", null, "This is a default msg if not found in MessageSource.", Locale.US) @@ -82,7 +96,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { * make sure the cache is being used properly. * @see org.springframework.context.support.AbstractMessageSource for more details. */ - public void testGetMessageWithMessageAlreadyLookedFor() { + @Test + public void getMessageWithMessageAlreadyLookedFor() { Object[] arguments = { new Integer(7), new Date(System.currentTimeMillis()), "a disturbance in the Force" @@ -111,7 +126,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { /** * Example taken from the javadocs for the java.text.MessageFormat class */ - public void testGetMessageWithNoDefaultPassedInAndFoundInMsgCatalog() { + @Test + public void getMessageWithNoDefaultPassedInAndFoundInMsgCatalog() { Object[] arguments = { new Integer(7), new Date(System.currentTimeMillis()), "a disturbance in the Force" @@ -140,63 +156,37 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { .equals("This is a test message in the message catalog with no args.")); } - public void testGetMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() { - // Expecting an exception - try { - // Try with Locale.US - sac.getMessage("bogus.message", null, Locale.US); - - fail("bogus msg from staticMsgSource for Locale.US without default msg should have thrown exception"); - } - catch (NoSuchMessageException tExcept) { - assertTrue("bogus msg from staticMsgSource for Locale.US without default msg threw expected exception", true); - } + @Test(expected = NoSuchMessageException.class) + public void getMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() { + // Try with Locale.US + sac.getMessage("bogus.message", null, Locale.US); } - public void testMessageSourceResolvable() { + @Test + public void messageSourceResolvable() { // first code valid String[] codes1 = new String[] {"message.format.example3", "message.format.example2"}; MessageSourceResolvable resolvable1 = new DefaultMessageSourceResolvable(codes1, null, "default"); - try { - assertTrue("correct message retrieved", MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US))); - } - catch (NoSuchMessageException ex) { - fail("Should not throw NoSuchMessageException"); - } + assertTrue("correct message retrieved", MSG_TXT3_US.equals(sac.getMessage(resolvable1, Locale.US))); // only second code valid String[] codes2 = new String[] {"message.format.example99", "message.format.example2"}; MessageSourceResolvable resolvable2 = new DefaultMessageSourceResolvable(codes2, null, "default"); - try { - assertTrue("correct message retrieved", MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US))); - } - catch (NoSuchMessageException ex) { - fail("Should not throw NoSuchMessageException"); - } + assertTrue("correct message retrieved", MSG_TXT2_US.equals(sac.getMessage(resolvable2, Locale.US))); // no code valid, but default given String[] codes3 = new String[] {"message.format.example99", "message.format.example98"}; MessageSourceResolvable resolvable3 = new DefaultMessageSourceResolvable(codes3, null, "default"); - try { - assertTrue("correct message retrieved", "default".equals(sac.getMessage(resolvable3, Locale.US))); - } - catch (NoSuchMessageException ex) { - fail("Should not throw NoSuchMessageException"); - } + assertTrue("correct message retrieved", "default".equals(sac.getMessage(resolvable3, Locale.US))); // no code valid, no default String[] codes4 = new String[] {"message.format.example99", "message.format.example98"}; MessageSourceResolvable resolvable4 = new DefaultMessageSourceResolvable(codes4); - try { - sac.getMessage(resolvable4, Locale.US); - fail("Should have thrown NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // expected - } + + exception.expect(NoSuchMessageException.class); + sac.getMessage(resolvable4, Locale.US); } - /** Run for each test */ @Override protected ConfigurableApplicationContext createContext() throws Exception { StaticApplicationContext parent = new StaticApplicationContext(); @@ -234,7 +224,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { return sac; } - public void testNestedMessageSourceWithParamInChild() { + @Test + public void nestedMessageSourceWithParamInChild() { StaticMessageSource source = new StaticMessageSource(); StaticMessageSource parent = new StaticMessageSource(); source.setParentMessageSource(parent); @@ -248,7 +239,8 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { assertEquals("put value here", source.getMessage(resolvable, Locale.ENGLISH)); } - public void testNestedMessageSourceWithParamInParent() { + @Test + public void nestedMessageSourceWithParamInParent() { StaticMessageSource source = new StaticMessageSource(); StaticMessageSource parent = new StaticMessageSource(); source.setParentMessageSource(parent); diff --git a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java index d4ddfe45c9..d34d620419 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java @@ -26,6 +26,8 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; +import org.junit.After; + import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import org.springframework.util.SocketUtils; @@ -78,6 +80,7 @@ public class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTes return this.connector.getMBeanServerConnection(); } + @After @Override public void tearDown() throws Exception { if (this.connector != null) { diff --git a/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java index 9410c609b0..9914be229c 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/LazyInitMBeanTests.java @@ -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. You may obtain a copy of @@ -19,24 +19,22 @@ package org.springframework.jmx.export; import javax.management.MBeanServer; import javax.management.ObjectName; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jmx.support.ObjectNameManager; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller */ -public class LazyInitMBeanTests extends TestCase { +public class LazyInitMBeanTests { - public void testLazyInit() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getApplicationContextPath()); - ctx.close(); - } - - public void testInvokeOnLazyInitBean() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getApplicationContextPath()); + @Test + public void invokeOnLazyInitBean() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/lazyInit.xml"); assertFalse(ctx.getBeanFactory().containsSingleton("testBean")); assertFalse(ctx.getBeanFactory().containsSingleton("testBean2")); try { @@ -50,8 +48,4 @@ public class LazyInitMBeanTests extends TestCase { } } - private String getApplicationContextPath() { - return "org/springframework/jmx/export/lazyInit.xml"; - } - } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java index 0083c77aa1..93f54eadf4 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationLazyInitMBeanTests.java @@ -16,10 +16,12 @@ package org.springframework.jmx.export.annotation; +import org.junit.Test; + import javax.management.MBeanServer; import javax.management.ObjectName; -import junit.framework.TestCase; +import static org.junit.Assert.*; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -29,9 +31,10 @@ import org.springframework.jmx.support.ObjectNameManager; * @author Rob Harrop * @author Juergen Hoeller */ -public class AnnotationLazyInitMBeanTests extends TestCase { +public class AnnotationLazyInitMBeanTests { - public void testLazyNaming() throws Exception { + @Test + public void lazyNaming() throws Exception { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyNaming.xml"); try { @@ -46,7 +49,8 @@ public class AnnotationLazyInitMBeanTests extends TestCase { } } - public void testLazyAssembling() throws Exception { + @Test + public void lazyAssembling() throws Exception { System.setProperty("domain", "bean"); ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/lazyAssembling.xml"); @@ -79,7 +83,8 @@ public class AnnotationLazyInitMBeanTests extends TestCase { } } - public void testComponentScan() throws Exception { + @Test + public void componentScan() throws Exception { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/annotation/componentScan.xml"); try { diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java index 1afd2eafe3..a5234fd0a1 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java @@ -16,16 +16,19 @@ package org.springframework.jmx.export.assembler; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; import org.springframework.jmx.JmxTestBean; /** * @author Rob Harrop */ -public abstract class AbstractAutodetectTests extends TestCase { +public abstract class AbstractAutodetectTests { - public void testAutodetect() throws Exception { + @Test + public void autodetect() throws Exception { JmxTestBean bean = new JmxTestBean(); AutodetectCapableMBeanInfoAssembler assembler = getAssembler(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java b/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java index 94e361edf0..3be1715b4e 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java @@ -16,16 +16,19 @@ package org.springframework.jmx.export.naming; +import org.junit.Test; + import javax.management.ObjectName; -import junit.framework.TestCase; +import static org.junit.Assert.*; /** * @author Rob Harrop */ -public abstract class AbstractNamingStrategyTests extends TestCase { +public abstract class AbstractNamingStrategyTests { - public void testNaming() throws Exception { + @Test + public void naming() throws Exception { ObjectNamingStrategy strat = getStrategy(); ObjectName objectName = strat.getObjectName(getManagedResource(), getKey()); assertEquals(objectName.getCanonicalName(), getCorrectObjectName()); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java b/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java index a62755bd0f..eb32025b85 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/naming/IdentityNamingStrategyTests.java @@ -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. @@ -19,18 +19,21 @@ package org.springframework.jmx.export.naming; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.jmx.JmxTestBean; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; +import static org.junit.Assert.*; + /** * @author Rob Harrop */ -public class IdentityNamingStrategyTests extends TestCase { +public class IdentityNamingStrategyTests { - public void testNaming() throws MalformedObjectNameException { + @Test + public void naming() throws MalformedObjectNameException { JmxTestBean bean = new JmxTestBean(); IdentityNamingStrategy strategy = new IdentityNamingStrategy(); ObjectName objectName = strategy.getObjectName(bean, "null"); diff --git a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java index 3e3f094322..754e4d2238 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java @@ -18,6 +18,7 @@ package org.springframework.jmx.support; import java.io.IOException; import java.net.MalformedURLException; + import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.MBeanServerConnection; @@ -27,6 +28,7 @@ import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; +import org.junit.After; import org.junit.Test; import org.springframework.jmx.AbstractMBeanServerTests; @@ -41,27 +43,25 @@ import static org.junit.Assert.*; * * @author Rob Harrop * @author Chris Beams + * @author Sam Brannen */ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { private static final String OBJECT_NAME = "spring:type=connector,name=test"; - private boolean runTests = false; @Override protected void onSetUp() throws Exception { Assume.group(TestGroup.JMXMP); - runTests = true; } + @After @Override public void tearDown() throws Exception { - if (runTests) { - super.tearDown(); - } + Assume.group(TestGroup.JMXMP, () -> super.tearDown()); } @Test - public void testStartupWithLocatedServer() throws Exception { + public void startupWithLocatedServer() throws Exception { ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean(); bean.afterPropertiesSet(); @@ -73,7 +73,7 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { } @Test - public void testStartupWithSuppliedServer() throws Exception { + public void startupWithSuppliedServer() throws Exception { //Added a brief snooze here - seems to fix occasional //java.net.BindException: Address already in use errors Thread.sleep(1); @@ -90,7 +90,7 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { } @Test - public void testRegisterWithMBeanServer() throws Exception { + public void registerWithMBeanServer() throws Exception { //Added a brief snooze here - seems to fix occasional //java.net.BindException: Address already in use errors Thread.sleep(1); @@ -108,7 +108,7 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { } @Test - public void testNoRegisterWithMBeanServer() throws Exception { + public void noRegisterWithMBeanServer() throws Exception { ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean(); bean.afterPropertiesSet(); diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java index 8d3cf156e1..f8d0bf740c 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 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. You may obtain a copy of @@ -18,31 +18,39 @@ package org.springframework.jmx.support; import java.lang.management.ManagementFactory; import java.util.List; + import javax.management.MBeanServer; import javax.management.MBeanServerFactory; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.util.MBeanTestUtils; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller * @author Phillip Webb */ -public class MBeanServerFactoryBeanTests extends TestCase { +public class MBeanServerFactoryBeanTests { - @Override - protected void setUp() throws Exception { + + @Before + public void setUp() throws Exception { MBeanTestUtils.resetMBeanServers(); } - @Override - protected void tearDown() throws Exception { + + @After + public void tearDown() throws Exception { MBeanTestUtils.resetMBeanServers(); } - public void testGetObject() throws Exception { + @Test + public void getObject() throws Exception { MBeanServerFactoryBean bean = new MBeanServerFactoryBean(); bean.afterPropertiesSet(); try { @@ -54,7 +62,8 @@ public class MBeanServerFactoryBeanTests extends TestCase { } } - public void testDefaultDomain() throws Exception { + @Test + public void defaultDomain() throws Exception { MBeanServerFactoryBean bean = new MBeanServerFactoryBean(); bean.setDefaultDomain("foo"); bean.afterPropertiesSet(); @@ -67,7 +76,8 @@ public class MBeanServerFactoryBeanTests extends TestCase { } } - public void testWithLocateExistingAndExistingServer() { + @Test + public void withLocateExistingAndExistingServer() { MBeanServer server = MBeanServerFactory.createMBeanServer(); try { MBeanServerFactoryBean bean = new MBeanServerFactoryBean(); @@ -86,7 +96,8 @@ public class MBeanServerFactoryBeanTests extends TestCase { } } - public void testWithLocateExistingAndFallbackToPlatformServer() { + @Test + public void withLocateExistingAndFallbackToPlatformServer() { MBeanServerFactoryBean bean = new MBeanServerFactoryBean(); bean.setLocateExistingServerIfPossible(true); bean.afterPropertiesSet(); @@ -98,7 +109,8 @@ public class MBeanServerFactoryBeanTests extends TestCase { } } - public void testWithEmptyAgentIdAndFallbackToPlatformServer() { + @Test + public void withEmptyAgentIdAndFallbackToPlatformServer() { MBeanServerFactoryBean bean = new MBeanServerFactoryBean(); bean.setAgentId(""); bean.afterPropertiesSet(); @@ -110,11 +122,13 @@ public class MBeanServerFactoryBeanTests extends TestCase { } } - public void testCreateMBeanServer() throws Exception { + @Test + public void createMBeanServer() throws Exception { testCreation(true, "The server should be available in the list"); } - public void testNewMBeanServer() throws Exception { + @Test + public void newMBeanServer() throws Exception { testCreation(false, "The server should not be available in the list"); } diff --git a/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java b/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java index d4e98e01da..6debb825a5 100644 --- a/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java +++ b/spring-context/src/test/java/org/springframework/remoting/rmi/RmiSupportTests.java @@ -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. @@ -29,21 +29,25 @@ import java.rmi.StubNotFoundException; import java.rmi.UnknownHostException; import java.rmi.UnmarshalException; -import junit.framework.TestCase; import org.aopalliance.intercept.MethodInvocation; +import org.junit.Test; + import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.RemoteConnectFailureException; import org.springframework.remoting.RemoteProxyFailureException; import org.springframework.remoting.support.RemoteInvocation; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @since 16.05.2003 */ -public class RmiSupportTests extends TestCase { +public class RmiSupportTests { - public void testRmiProxyFactoryBean() throws Exception { + @Test + public void rmiProxyFactoryBean() throws Exception { CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean(); factory.setServiceInterface(IRemoteBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); @@ -56,35 +60,43 @@ public class RmiSupportTests extends TestCase { assertEquals(1, factory.counter); } - public void testRmiProxyFactoryBeanWithRemoteException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithRemoteException() throws Exception { doTestRmiProxyFactoryBeanWithException(RemoteException.class); } - public void testRmiProxyFactoryBeanWithConnectException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithConnectException() throws Exception { doTestRmiProxyFactoryBeanWithException(ConnectException.class); } - public void testRmiProxyFactoryBeanWithConnectIOException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithConnectIOException() throws Exception { doTestRmiProxyFactoryBeanWithException(ConnectIOException.class); } - public void testRmiProxyFactoryBeanWithUnknownHostException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithUnknownHostException() throws Exception { doTestRmiProxyFactoryBeanWithException(UnknownHostException.class); } - public void testRmiProxyFactoryBeanWithNoSuchObjectException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithNoSuchObjectException() throws Exception { doTestRmiProxyFactoryBeanWithException(NoSuchObjectException.class); } - public void testRmiProxyFactoryBeanWithStubNotFoundException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithStubNotFoundException() throws Exception { doTestRmiProxyFactoryBeanWithException(StubNotFoundException.class); } - public void testRmiProxyFactoryBeanWithMarshalException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithMarshalException() throws Exception { doTestRmiProxyFactoryBeanWithException(MarshalException.class); } - public void testRmiProxyFactoryBeanWithUnmarshalException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithUnmarshalException() throws Exception { doTestRmiProxyFactoryBeanWithException(UnmarshalException.class); } @@ -110,23 +122,28 @@ public class RmiSupportTests extends TestCase { assertEquals(1, factory.counter); } - public void testRmiProxyFactoryBeanWithConnectExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithConnectExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithExceptionAndRefresh(ConnectException.class); } - public void testRmiProxyFactoryBeanWithConnectIOExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithConnectIOExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithExceptionAndRefresh(ConnectIOException.class); } - public void testRmiProxyFactoryBeanWithUnknownHostExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithUnknownHostExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithExceptionAndRefresh(UnknownHostException.class); } - public void testRmiProxyFactoryBeanWithNoSuchObjectExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithNoSuchObjectExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithExceptionAndRefresh(NoSuchObjectException.class); } - public void testRmiProxyFactoryBeanWithStubNotFoundExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithStubNotFoundExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithExceptionAndRefresh(StubNotFoundException.class); } @@ -153,7 +170,8 @@ public class RmiSupportTests extends TestCase { assertEquals(2, factory.counter); } - public void testRmiProxyFactoryBeanWithBusinessInterface() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterface() throws Exception { CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean(); factory.setServiceInterface(IBusinessBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); @@ -166,7 +184,8 @@ public class RmiSupportTests extends TestCase { assertEquals(1, factory.counter); } - public void testRmiProxyFactoryBeanWithWrongBusinessInterface() throws Exception { + @Test + public void rmiProxyFactoryBeanWithWrongBusinessInterface() throws Exception { CountingRmiProxyFactoryBean factory = new CountingRmiProxyFactoryBean(); factory.setServiceInterface(IWrongBusinessBean.class); factory.setServiceUrl("rmi://localhost:1090/test"); @@ -186,32 +205,38 @@ public class RmiSupportTests extends TestCase { assertEquals(1, factory.counter); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndRemoteException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndRemoteException() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException( RemoteException.class, RemoteAccessException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndConnectException() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException( ConnectException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectIOException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndConnectIOException() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException( ConnectIOException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndUnknownHostException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndUnknownHostException() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException( UnknownHostException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndNoSuchObjectExceptionException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndNoSuchObjectExceptionException() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException( NoSuchObjectException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndStubNotFoundException() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndStubNotFoundException() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndException( StubNotFoundException.class, RemoteConnectFailureException.class); } @@ -241,32 +266,38 @@ public class RmiSupportTests extends TestCase { assertEquals(1, factory.counter); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndRemoteExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndRemoteExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh( RemoteException.class, RemoteAccessException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndConnectExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh( ConnectException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndConnectIOExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndConnectIOExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh( ConnectIOException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndUnknownHostExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndUnknownHostExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh( UnknownHostException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndNoSuchObjectExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndNoSuchObjectExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh( NoSuchObjectException.class, RemoteConnectFailureException.class); } - public void testRmiProxyFactoryBeanWithBusinessInterfaceAndStubNotFoundExceptionAndRefresh() throws Exception { + @Test + public void rmiProxyFactoryBeanWithBusinessInterfaceAndStubNotFoundExceptionAndRefresh() throws Exception { doTestRmiProxyFactoryBeanWithBusinessInterfaceAndExceptionAndRefresh( StubNotFoundException.class, RemoteConnectFailureException.class); } @@ -302,7 +333,8 @@ public class RmiSupportTests extends TestCase { } } - public void testRmiClientInterceptorRequiresUrl() throws Exception{ + @Test + public void rmiClientInterceptorRequiresUrl() throws Exception{ RmiClientInterceptor client = new RmiClientInterceptor(); client.setServiceInterface(IRemoteBean.class); @@ -315,7 +347,8 @@ public class RmiSupportTests extends TestCase { } } - public void testRemoteInvocation() throws NoSuchMethodException { + @Test + public void remoteInvocation() throws NoSuchMethodException { // let's see if the remote invocation object works final RemoteBean rb = new RemoteBean(); @@ -365,7 +398,8 @@ public class RmiSupportTests extends TestCase { assertEquals(String.class, inv.getParameterTypes()[0]); } - public void testRmiInvokerWithSpecialLocalMethods() throws Exception { + @Test + public void rmiInvokerWithSpecialLocalMethods() throws Exception { String serviceUrl = "rmi://localhost:1090/test"; RmiProxyFactoryBean factory = new RmiProxyFactoryBean() { @Override diff --git a/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java b/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java index 57d532d3e9..01e5be7041 100644 --- a/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java +++ b/spring-context/src/test/java/org/springframework/remoting/support/RemoteInvocationUtilsTests.java @@ -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. @@ -16,14 +16,17 @@ package org.springframework.remoting.support; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rick Evans */ -public class RemoteInvocationUtilsTests extends TestCase { +public class RemoteInvocationUtilsTests { - public void testFillInClientStackTraceIfPossibleSunnyDay() throws Exception { + @Test + public void fillInClientStackTraceIfPossibleSunnyDay() throws Exception { try { throw new IllegalStateException("Mmm"); } @@ -35,7 +38,8 @@ public class RemoteInvocationUtilsTests extends TestCase { } } - public void testFillInClientStackTraceIfPossibleWithNullThrowable() throws Exception { + @Test + public void fillInClientStackTraceIfPossibleWithNullThrowable() throws Exception { // just want to ensure that it doesn't bomb RemoteInvocationUtils.fillInClientStackTraceIfPossible(null); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java index 022a1cd468..39d4d36e07 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java @@ -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. @@ -16,28 +16,31 @@ package org.springframework.scheduling.concurrent; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.core.task.NoOpRunnable; /** * @author Rick Evans */ -public class ConcurrentTaskExecutorTests extends TestCase { +public class ConcurrentTaskExecutorTests { - public void testZeroArgCtorResultsInDefaultTaskExecutorBeingUsed() throws Exception { + @Test + public void zeroArgCtorResultsInDefaultTaskExecutorBeingUsed() throws Exception { ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor(); // must not throw a NullPointerException executor.execute(new NoOpRunnable()); } - public void testPassingNullExecutorToCtorResultsInDefaultTaskExecutorBeingUsed() throws Exception { + @Test + public void passingNullExecutorToCtorResultsInDefaultTaskExecutorBeingUsed() throws Exception { ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor(null); // must not throw a NullPointerException executor.execute(new NoOpRunnable()); } - public void testPassingNullExecutorToSetterResultsInDefaultTaskExecutorBeingUsed() throws Exception { + @Test + public void passingNullExecutorToSetterResultsInDefaultTaskExecutorBeingUsed() throws Exception { ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor(); executor.setConcurrentExecutor(null); // must not throw a NullPointerException diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java index b2469698f1..1d3ba17d96 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java @@ -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,7 +19,7 @@ package org.springframework.scripting.bsh; import java.util.Arrays; import java.util.Collection; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.Refreshable; @@ -36,6 +36,7 @@ import org.springframework.scripting.TestBeanAwareMessenger; import org.springframework.scripting.support.ScriptFactoryPostProcessor; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** @@ -43,9 +44,10 @@ import static org.mockito.BDDMockito.*; * @author Rick Evans * @author Juergen Hoeller */ -public class BshScriptFactoryTests extends TestCase { +public class BshScriptFactoryTests { - public void testStaticScript() throws Exception { + @Test + public void staticScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Calculator.class)).contains("calculator")); @@ -72,7 +74,8 @@ public class BshScriptFactoryTests extends TestCase { assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); } - public void testStaticScriptWithNullReturnValue() throws Exception { + @Test + public void staticScriptWithNullReturnValue() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfig")); @@ -82,7 +85,8 @@ public class BshScriptFactoryTests extends TestCase { assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger)); } - public void testStaticScriptWithTwoInterfacesSpecified() throws Exception { + @Test + public void staticScriptWithTwoInterfacesSpecified() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerWithConfigExtra")); @@ -95,7 +99,8 @@ public class BshScriptFactoryTests extends TestCase { assertNull(messenger.getMessage()); } - public void testStaticWithScriptReturningInstance() throws Exception { + @Test + public void staticWithScriptReturningInstance() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerInstance")); @@ -108,7 +113,8 @@ public class BshScriptFactoryTests extends TestCase { assertNull(messenger.getMessage()); } - public void testStaticScriptImplementingInterface() throws Exception { + @Test + public void staticScriptImplementingInterface() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("messengerImpl")); @@ -121,7 +127,8 @@ public class BshScriptFactoryTests extends TestCase { assertNull(messenger.getMessage()); } - public void testStaticPrototypeScript() throws Exception { + @Test + public void staticPrototypeScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass()); ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); @@ -139,7 +146,8 @@ public class BshScriptFactoryTests extends TestCase { assertEquals("Byebye World!", messenger2.getMessage()); } - public void testNonStaticScript() throws Exception { + @Test + public void nonStaticScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshRefreshableContext.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("messenger"); @@ -156,7 +164,8 @@ public class BshScriptFactoryTests extends TestCase { assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount()); } - public void testNonStaticPrototypeScript() throws Exception { + @Test + public void nonStaticPrototypeScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bshRefreshableContext.xml", getClass()); ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); @@ -179,7 +188,8 @@ public class BshScriptFactoryTests extends TestCase { assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount()); } - public void testScriptCompilationException() throws Exception { + @Test + public void scriptCompilationException() throws Exception { try { new ClassPathXmlApplicationContext("org/springframework/scripting/bsh/bshBrokenContext.xml"); fail("Must throw exception for broken script file"); @@ -189,7 +199,8 @@ public class BshScriptFactoryTests extends TestCase { } } - public void testScriptThatCompilesButIsJustPlainBad() throws Exception { + @Test + public void scriptThatCompilesButIsJustPlainBad() throws Exception { ScriptSource script = mock(ScriptSource.class); final String badScript = "String getMessage() { throw new IllegalArgumentException(); }"; given(script.getScriptAsString()).willReturn(badScript); @@ -205,7 +216,8 @@ public class BshScriptFactoryTests extends TestCase { } } - public void testCtorWithNullScriptSourceLocator() throws Exception { + @Test + public void ctorWithNullScriptSourceLocator() throws Exception { try { new BshScriptFactory(null, Messenger.class); fail("Must have thrown exception by this point."); @@ -214,7 +226,8 @@ public class BshScriptFactoryTests extends TestCase { } } - public void testCtorWithEmptyScriptSourceLocator() throws Exception { + @Test + public void ctorWithEmptyScriptSourceLocator() throws Exception { try { new BshScriptFactory("", new Class[] {Messenger.class}); fail("Must have thrown exception by this point."); @@ -223,7 +236,8 @@ public class BshScriptFactoryTests extends TestCase { } } - public void testCtorWithWhitespacedScriptSourceLocator() throws Exception { + @Test + public void ctorWithWhitespacedScriptSourceLocator() throws Exception { try { new BshScriptFactory("\n ", new Class[] {Messenger.class}); fail("Must have thrown exception by this point."); @@ -232,7 +246,8 @@ public class BshScriptFactoryTests extends TestCase { } } - public void testResourceScriptFromTag() throws Exception { + @Test + public void resourceScriptFromTag() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); TestBean testBean = (TestBean) ctx.getBean("testBean"); @@ -270,7 +285,8 @@ public class BshScriptFactoryTests extends TestCase { assertNull(messengerInstance.getMessage()); } - public void testPrototypeScriptFromTag() throws Exception { + @Test + public void prototypeScriptFromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype"); @@ -285,21 +301,24 @@ public class BshScriptFactoryTests extends TestCase { assertEquals("Byebye World!", messenger2.getMessage()); } - public void testInlineScriptFromTag() throws Exception { + @Test + public void inlineScriptFromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); Calculator calculator = (Calculator) ctx.getBean("calculator"); assertNotNull(calculator); assertFalse(calculator instanceof Refreshable); } - public void testRefreshableFromTag() throws Exception { + @Test + public void refreshableFromTag() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger"); assertEquals("Hello World!", messenger.getMessage()); assertTrue("Messenger should be Refreshable", messenger instanceof Refreshable); } - public void testApplicationEventListener() throws Exception { + @Test + public void applicationEventListener() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("bsh-with-xsd.xml", getClass()); Messenger eventListener = (Messenger) ctx.getBean("eventListener"); ctx.publishEvent(new MyEvent(ctx)); diff --git a/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java b/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java index 5e85cc6424..0e9c9058cb 100644 --- a/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/config/ScriptingDefaultsTests.java @@ -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,7 @@ package org.springframework.scripting.config; import java.lang.reflect.Field; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; @@ -26,11 +26,14 @@ import org.springframework.aop.target.dynamic.AbstractRefreshableTargetSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher * @author Dave Syer */ -public class ScriptingDefaultsTests extends TestCase { +@SuppressWarnings("resource") +public class ScriptingDefaultsTests { private static final String CONFIG = "org/springframework/scripting/config/scriptingDefaultsTests.xml"; @@ -39,7 +42,8 @@ public class ScriptingDefaultsTests extends TestCase { "org/springframework/scripting/config/scriptingDefaultsProxyTargetClassTests.xml"; - public void testDefaultRefreshCheckDelay() throws Exception { + @Test + public void defaultRefreshCheckDelay() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); Advised advised = (Advised) context.getBean("testBean"); AbstractRefreshableTargetSource targetSource = @@ -50,19 +54,22 @@ public class ScriptingDefaultsTests extends TestCase { assertEquals(5000L, delay); } - public void testDefaultInitMethod() { + @Test + public void defaultInitMethod() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("testBean"); assertTrue(testBean.isInitialized()); } - public void testNameAsAlias() { + @Test + public void nameAsAlias() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("/url"); assertTrue(testBean.isInitialized()); } - public void testDefaultDestroyMethod() { + @Test + public void defaultDestroyMethod() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("nonRefreshableTestBean"); assertFalse(testBean.isDestroyed()); @@ -70,14 +77,16 @@ public class ScriptingDefaultsTests extends TestCase { assertTrue(testBean.isDestroyed()); } - public void testDefaultAutowire() { + @Test + public void defaultAutowire() { ApplicationContext context = new ClassPathXmlApplicationContext(CONFIG); ITestBean testBean = (ITestBean) context.getBean("testBean"); ITestBean otherBean = (ITestBean) context.getBean("otherBean"); assertEquals(otherBean, testBean.getOtherBean()); } - public void testDefaultProxyTargetClass() { + @Test + public void defaultProxyTargetClass() { ApplicationContext context = new ClassPathXmlApplicationContext(PROXY_CONFIG); Object testBean = context.getBean("testBean"); assertTrue(AopUtils.isCglibProxy(testBean)); diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java index 8f5e2d00f3..c12a482783 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java @@ -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. @@ -30,14 +30,17 @@ import static org.junit.Assert.*; /** * @author Dave Syer + * @author Sam Brannen */ public class GroovyAspectTests { - @Test - public void testManualGroovyBeanWithUnconditionalPointcut() throws Exception { - LogUserAdvice logAdvice = new LogUserAdvice(); + private final LogUserAdvice logAdvice = new LogUserAdvice(); - GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + private final GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + + + @Test + public void manualGroovyBeanWithUnconditionalPointcut() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); @@ -45,10 +48,7 @@ public class GroovyAspectTests { } @Test - public void testManualGroovyBeanWithStaticPointcut() throws Exception { - LogUserAdvice logAdvice = new LogUserAdvice(); - - GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + public void manualGroovyBeanWithStaticPointcut() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); @@ -58,31 +58,23 @@ public class GroovyAspectTests { } @Test - public void testManualGroovyBeanWithDynamicPointcut() throws Exception { - LogUserAdvice logAdvice = new LogUserAdvice(); - - GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + public void manualGroovyBeanWithDynamicPointcut() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(String.format("@within(%s.Log)", ClassUtils.getPackageName(getClass()))); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", false); - } @Test - public void testManualGroovyBeanWithDynamicPointcutProxyTargetClass() throws Exception { - LogUserAdvice logAdvice = new LogUserAdvice(); - - GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + public void manualGroovyBeanWithDynamicPointcutProxyTargetClass() throws Exception { TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( new ClassPathResource("GroovyServiceImpl.grv", getClass()))); AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(String.format("@within(%s.Log)", ClassUtils.getPackageName(getClass()))); testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", true); - } private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message) diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java index 78e61a0607..df9cdc10c1 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyClassLoadingTests.java @@ -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,21 +16,25 @@ package org.springframework.scripting.groovy; +import groovy.lang.GroovyClassLoader; + import java.lang.reflect.Method; -import groovy.lang.GroovyClassLoader; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.StaticApplicationContext; import org.springframework.util.ReflectionUtils; +import static org.junit.Assert.*; + /** * @author Mark Fisher */ -public class GroovyClassLoadingTests extends TestCase { +public class GroovyClassLoadingTests { - public void testClassLoading() throws Exception { + @Test + @SuppressWarnings("resource") + public void classLoading() throws Exception { StaticApplicationContext context = new StaticApplicationContext(); GroovyClassLoader gcl = new GroovyClassLoader(); @@ -41,16 +45,14 @@ public class GroovyClassLoadingTests extends TestCase { Object testBean1 = context.getBean("testBean"); Method method1 = class1.getDeclaredMethod("myMethod", new Class[0]); Object result1 = ReflectionUtils.invokeMethod(method1, testBean1); - assertEquals("foo", (String) result1); - - // ### uncommenting the next line causes the test to pass for Spring > 2.0.2 ### - //context.removeBeanDefinition("testBean"); + assertEquals("foo", result1); + context.removeBeanDefinition("testBean"); context.registerBeanDefinition("testBean", new RootBeanDefinition(class2)); Object testBean2 = context.getBean("testBean"); Method method2 = class2.getDeclaredMethod("myMethod", new Class[0]); Object result2 = ReflectionUtils.invokeMethod(method2, testBean2); - assertEquals("bar", (String) result2); + assertEquals("bar", result2); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/LogUserAdvice.java b/spring-context/src/test/java/org/springframework/scripting/groovy/LogUserAdvice.java index 28330777f3..f7b774a8bc 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/LogUserAdvice.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/LogUserAdvice.java @@ -1,3 +1,19 @@ +/* + * 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. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.scripting.groovy; import java.lang.reflect.Method; @@ -14,15 +30,15 @@ public class LogUserAdvice implements MethodBeforeAdvice, ThrowsAdvice { @Override public void before(Method method, Object[] objects, Object o) throws Throwable { countBefore++; - System.out.println("Method:"+method.getName()); + // System.out.println("Method:" + method.getName()); } public void afterThrowing(Exception e) throws Throwable { countThrows++; - System.out.println("***********************************************************************************"); - System.out.println("Exception caught:"); - System.out.println("***********************************************************************************"); - e.printStackTrace(); + // System.out.println("***********************************************************************************"); + // System.out.println("Exception caught:"); + // System.out.println("***********************************************************************************"); + // e.printStackTrace(); throw e; } diff --git a/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java index a443bee0bb..91c38fc79c 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/RefreshableScriptTargetSourceTests.java @@ -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,24 +16,20 @@ package org.springframework.scripting.support; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.factory.BeanFactory; -import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.*; /** * @author Rick Evans */ -public class RefreshableScriptTargetSourceTests extends TestCase { +public class RefreshableScriptTargetSourceTests { - public void testCreateWithNullScriptSource() throws Exception { - try { - new RefreshableScriptTargetSource(mock(BeanFactory.class), "a.bean", null, null, false); - fail("Must have failed when passed a null ScriptSource."); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void createWithNullScriptSource() throws Exception { + new RefreshableScriptTargetSource(mock(BeanFactory.class), "a.bean", null, null, false); } } diff --git a/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java index 367bbfc48f..df7ea2a03e 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/ResourceScriptSourceTests.java @@ -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,20 +19,22 @@ package org.springframework.scripting.support; import java.io.ByteArrayInputStream; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Rick Evans * @author Juergen Hoeller */ -public class ResourceScriptSourceTests extends TestCase { +public class ResourceScriptSourceTests { - public void testDoesNotPropagateFatalExceptionOnResourceThatCannotBeResolvedToAFile() throws Exception { + @Test + public void doesNotPropagateFatalExceptionOnResourceThatCannotBeResolvedToAFile() throws Exception { Resource resource = mock(Resource.class); given(resource.lastModified()).willThrow(new IOException()); @@ -41,13 +43,15 @@ public class ResourceScriptSourceTests extends TestCase { assertEquals(0, lastModified); } - public void testBeginsInModifiedState() throws Exception { + @Test + public void beginsInModifiedState() throws Exception { Resource resource = mock(Resource.class); ResourceScriptSource scriptSource = new ResourceScriptSource(resource); assertTrue(scriptSource.isModified()); } - public void testLastModifiedWorksWithResourceThatDoesNotSupportFileBasedReading() throws Exception { + @Test + public void lastModifiedWorksWithResourceThatDoesNotSupportFileBasedReading() throws Exception { Resource resource = mock(Resource.class); // underlying File is asked for so that the last modified time can be checked... // And then mock the file changing; i.e. the File says it has been modified @@ -65,7 +69,8 @@ public class ResourceScriptSourceTests extends TestCase { assertTrue("ResourceScriptSource must report back as being modified if the underlying File resource is reporting a changed lastModified time.", scriptSource.isModified()); } - public void testLastModifiedWorksWithResourceThatDoesNotSupportFileBasedAccessAtAll() throws Exception { + @Test + public void lastModifiedWorksWithResourceThatDoesNotSupportFileBasedAccessAtAll() throws Exception { Resource resource = new ByteArrayResource(new byte[0]); ResourceScriptSource scriptSource = new ResourceScriptSource(resource); assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified()); diff --git a/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java b/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java index c9e6babddc..12c4e8182d 100644 --- a/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/support/StaticScriptSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 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,71 +16,64 @@ package org.springframework.scripting.support; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Unit tests for the StaticScriptSource class. * * @author Rick Evans + * @author Sam Brannen */ -public final class StaticScriptSourceTests extends TestCase { +public final class StaticScriptSourceTests { private static final String SCRIPT_TEXT = "print($hello) if $true;"; + private final StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT); - public void testCreateWithNullScript() throws Exception { - try { - new StaticScriptSource(null); - fail("Must have failed when passed a null script string."); - } - catch (IllegalArgumentException expected) { - } + + @Test(expected = IllegalArgumentException.class) + public void createWithNullScript() throws Exception { + new StaticScriptSource(null); } - public void testCreateWithEmptyScript() throws Exception { - try { - new StaticScriptSource(""); - fail("Must have failed when passed an empty script string."); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void createWithEmptyScript() throws Exception { + new StaticScriptSource(""); } - public void testCreateWithWhitespaceOnlyScript() throws Exception { - try { - new StaticScriptSource(" \n\n\t \t\n"); - fail("Must have failed when passed a whitespace-only script string."); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void createWithWhitespaceOnlyScript() throws Exception { + new StaticScriptSource(" \n\n\t \t\n"); } - public void testIsModifiedIsTrueByDefault() throws Exception { - StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT); + @Test + public void isModifiedIsTrueByDefault() throws Exception { assertTrue("Script must be flagged as 'modified' when first created.", source.isModified()); } - public void testGettingScriptTogglesIsModified() throws Exception { - StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT); + @Test + public void gettingScriptTogglesIsModified() throws Exception { source.getScriptAsString(); assertFalse("Script must be flagged as 'not modified' after script is read.", source.isModified()); } - public void testGettingScriptViaToStringDoesNotToggleIsModified() throws Exception { - StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT); + @Test + public void gettingScriptViaToStringDoesNotToggleIsModified() throws Exception { boolean isModifiedState = source.isModified(); source.toString(); assertEquals("Script's 'modified' flag must not change after script is read via toString().", isModifiedState, source.isModified()); } - public void testIsModifiedToggledWhenDifferentScriptIsSet() throws Exception { - StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT); + @Test + public void isModifiedToggledWhenDifferentScriptIsSet() throws Exception { source.setScript("use warnings;"); assertTrue("Script must be flagged as 'modified' when different script is passed in.", source.isModified()); } - public void testIsModifiedNotToggledWhenSameScriptIsSet() throws Exception { - StaticScriptSource source = new StaticScriptSource(SCRIPT_TEXT); + @Test + public void isModifiedNotToggledWhenSameScriptIsSet() throws Exception { source.setScript(SCRIPT_TEXT); assertFalse("Script must not be flagged as 'modified' when same script is passed in.", source.isModified()); } diff --git a/spring-core/src/main/java/org/springframework/util/StopWatch.java b/spring-core/src/main/java/org/springframework/util/StopWatch.java index 13f2b626a2..1ba3988003 100644 --- a/spring-core/src/main/java/org/springframework/util/StopWatch.java +++ b/spring-core/src/main/java/org/springframework/util/StopWatch.java @@ -72,7 +72,7 @@ public class StopWatch { * Construct a new stop watch. Does not start any task. */ public StopWatch() { - this.id = ""; + this(""); } /** diff --git a/spring-core/src/test/java/org/springframework/core/ConstantsTests.java b/spring-core/src/test/java/org/springframework/core/ConstantsTests.java index 2dc85aae31..d0cd4dee4f 100644 --- a/spring-core/src/test/java/org/springframework/core/ConstantsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConstantsTests.java @@ -16,10 +16,12 @@ package org.springframework.core; +import org.junit.Test; + import java.util.Locale; import java.util.Set; -import junit.framework.TestCase; +import static org.junit.Assert.*; /** * @author Rod Johnson @@ -27,9 +29,10 @@ import junit.framework.TestCase; * @author Rick Evans * @since 28.04.2003 */ -public class ConstantsTests extends TestCase { +public class ConstantsTests { - public void testConstants() { + @Test + public void constants() { Constants c = new Constants(A.class); assertEquals(A.class.getName(), c.getClassName()); assertEquals(9, c.getSize()); @@ -54,7 +57,8 @@ public class ConstantsTests extends TestCase { } } - public void testGetNames() { + @Test + public void getNames() { Constants c = new Constants(A.class); Set names = c.getNames(""); @@ -72,7 +76,8 @@ public class ConstantsTests extends TestCase { assertTrue(names.contains("DOG")); } - public void testGetValues() { + @Test + public void getValues() { Constants c = new Constants(A.class); Set values = c.getValues(""); @@ -96,7 +101,8 @@ public class ConstantsTests extends TestCase { assertTrue(values.contains(new Integer(2))); } - public void testGetValuesInTurkey() { + @Test + public void getValuesInTurkey() { Locale oldLocale = Locale.getDefault(); Locale.setDefault(new Locale("tr", "")); try { @@ -127,7 +133,8 @@ public class ConstantsTests extends TestCase { } } - public void testSuffixAccess() { + @Test + public void suffixAccess() { Constants c = new Constants(A.class); Set names = c.getNamesForSuffix("_PROPERTY"); @@ -141,7 +148,8 @@ public class ConstantsTests extends TestCase { assertTrue(values.contains(new Integer(4))); } - public void testToCode() { + @Test + public void toCode() { Constants c = new Constants(A.class); assertEquals(c.toCode(new Integer(0), ""), "DOG"); @@ -208,25 +216,29 @@ public class ConstantsTests extends TestCase { } } - public void testGetValuesWithNullPrefix() throws Exception { + @Test + public void getValuesWithNullPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(null); assertEquals("Must have returned *all* public static final values", 7, values.size()); } - public void testGetValuesWithEmptyStringPrefix() throws Exception { + @Test + public void getValuesWithEmptyStringPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(""); assertEquals("Must have returned *all* public static final values", 7, values.size()); } - public void testGetValuesWithWhitespacedStringPrefix() throws Exception { + @Test + public void getValuesWithWhitespacedStringPrefix() throws Exception { Constants c = new Constants(A.class); Set values = c.getValues(" "); assertEquals("Must have returned *all* public static final values", 7, values.size()); } - public void testWithClassThatExposesNoConstants() throws Exception { + @Test + public void withClassThatExposesNoConstants() throws Exception { Constants c = new Constants(NoConstants.class); assertEquals(0, c.getSize()); final Set values = c.getValues(""); @@ -234,7 +246,8 @@ public class ConstantsTests extends TestCase { assertEquals(0, values.size()); } - public void testCtorWithNullClass() throws Exception { + @Test + public void ctorWithNullClass() throws Exception { try { new Constants(null); fail("Must have thrown IllegalArgumentException"); diff --git a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java index cdc94380d0..74d28bb737 100644 --- a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java @@ -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,58 +17,68 @@ package org.springframework.core; import java.util.ArrayList; -import java.util.HashSet; +import java.util.Arrays; +import java.util.Collections; import java.util.List; -import java.util.Set; -import junit.framework.TestCase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.tests.sample.objects.TestObject; +import static org.junit.Assert.*; + /** * @author Rob Harrop + * @author Sam Brannen */ -public class ConventionsTests extends TestCase { +public class ConventionsTests { - public void testSimpleObject() { - TestObject testObject = new TestObject(); - assertEquals("Incorrect singular variable name", "testObject", Conventions.getVariableName(testObject)); + @Rule + public final ExpectedException exception = ExpectedException.none(); + + + @Test + public void simpleObject() { + assertEquals("Incorrect singular variable name", "testObject", Conventions.getVariableName(new TestObject())); } - public void testArray() { - TestObject[] testObjects = new TestObject[0]; - assertEquals("Incorrect plural array form", "testObjectList", Conventions.getVariableName(testObjects)); + @Test + public void array() { + assertEquals("Incorrect plural array form", "testObjectList", Conventions.getVariableName(new TestObject[0])); } - public void testCollections() { - List list = new ArrayList(); - list.add(new TestObject()); + @Test + public void list() { + List list = Arrays.asList(new TestObject()); assertEquals("Incorrect plural List form", "testObjectList", Conventions.getVariableName(list)); - - Set set = new HashSet(); - set.add(new TestObject()); - assertEquals("Incorrect plural Set form", "testObjectList", Conventions.getVariableName(set)); - - List emptyList = new ArrayList(); - try { - Conventions.getVariableName(emptyList); - fail("Should not be able to generate name for empty collection"); - } - catch(IllegalArgumentException ex) { - // success - } } - public void testAttributeNameToPropertyName() throws Exception { + @Test + public void emptyList() { + exception.expect(IllegalArgumentException.class); + Conventions.getVariableName(new ArrayList<>()); + } + + @Test + public void set() { + assertEquals("Incorrect plural Set form", "testObjectList", Conventions.getVariableName(Collections.singleton(new TestObject()))); + } + + @Test + public void attributeNameToPropertyName() throws Exception { assertEquals("transactionManager", Conventions.attributeNameToPropertyName("transaction-manager")); assertEquals("pointcutRef", Conventions.attributeNameToPropertyName("pointcut-ref")); assertEquals("lookupOnStartup", Conventions.attributeNameToPropertyName("lookup-on-startup")); } - public void testGetQualifiedAttributeName() throws Exception { + @Test + public void getQualifiedAttributeName() throws Exception { String baseName = "foo"; Class cls = String.class; String desiredResult = "java.lang.String.foo"; assertEquals(desiredResult, Conventions.getQualifiedAttributeName(cls, baseName)); } + } diff --git a/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java b/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java index dff4290936..c0e60ad1b2 100644 --- a/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java +++ b/spring-core/src/test/java/org/springframework/core/NestedExceptionTests.java @@ -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,16 +19,19 @@ package org.springframework.core; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rod Johnson * @author Juergen Hoeller */ -public class NestedExceptionTests extends TestCase { +@SuppressWarnings("serial") +public class NestedExceptionTests { - @SuppressWarnings("serial") - public void testNestedRuntimeExceptionWithNoRootCause() { + @Test + public void nestedRuntimeExceptionWithNoRootCause() { String mesg = "mesg of mine"; // Making a class abstract doesn't _really_ prevent instantiation :-) NestedRuntimeException nex = new NestedRuntimeException(mesg) {}; @@ -44,8 +47,8 @@ public class NestedExceptionTests extends TestCase { assertFalse(stackTrace.indexOf(mesg) == -1); } - @SuppressWarnings("serial") - public void testNestedRuntimeExceptionWithRootCause() { + @Test + public void nestedRuntimeExceptionWithRootCause() { String myMessage = "mesg for this exception"; String rootCauseMesg = "this is the obscure message of the root cause"; Exception rootCause = new Exception(rootCauseMesg); @@ -65,8 +68,8 @@ public class NestedExceptionTests extends TestCase { assertFalse(stackTrace.indexOf(rootCauseMesg) == -1); } - @SuppressWarnings("serial") - public void testNestedCheckedExceptionWithNoRootCause() { + @Test + public void nestedCheckedExceptionWithNoRootCause() { String mesg = "mesg of mine"; // Making a class abstract doesn't _really_ prevent instantiation :-) NestedCheckedException nex = new NestedCheckedException(mesg) {}; @@ -82,8 +85,8 @@ public class NestedExceptionTests extends TestCase { assertFalse(stackTrace.indexOf(mesg) == -1); } - @SuppressWarnings("serial") - public void testNestedCheckedExceptionWithRootCause() { + @Test + public void nestedCheckedExceptionWithRootCause() { String myMessage = "mesg for this exception"; String rootCauseMesg = "this is the obscure message of the root cause"; Exception rootCause = new Exception(rootCauseMesg); diff --git a/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java b/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java index 710f521ae7..dbafa1bbf7 100644 --- a/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java +++ b/spring-core/src/test/java/org/springframework/core/style/ToStringCreatorTests.java @@ -23,20 +23,24 @@ import java.util.List; import java.util.Map; import java.util.Set; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.util.ObjectUtils; +import static org.junit.Assert.*; + /** * @author Keith Donald */ @SuppressWarnings({ "rawtypes", "unchecked" }) -public class ToStringCreatorTests extends TestCase { +public class ToStringCreatorTests { private SomeObject s1, s2, s3; - @Override - protected void setUp() throws Exception { + + @Before + public void setUp() throws Exception { s1 = new SomeObject() { @Override public String toString() { @@ -57,7 +61,8 @@ public class ToStringCreatorTests extends TestCase { }; } - public void testDefaultStyleMap() { + @Test + public void defaultStyleMap() { final Map map = getMap(); Object stringy = new Object() { @Override @@ -78,20 +83,23 @@ public class ToStringCreatorTests extends TestCase { return map; } - public void testDefaultStyleArray() { + @Test + public void defaultStyleArray() { SomeObject[] array = new SomeObject[] { s1, s2, s3 }; String str = new ToStringCreator(array).toString(); assertEquals("[@" + ObjectUtils.getIdentityHexString(array) + " array[A, B, C]]", str); } - public void testPrimitiveArrays() { + @Test + public void primitiveArrays() { int[] integers = new int[] { 0, 1, 2, 3, 4 }; String str = new ToStringCreator(integers).toString(); assertEquals("[@" + ObjectUtils.getIdentityHexString(integers) + " array[0, 1, 2, 3, 4]]", str); } - public void testList() { + @Test + public void appendList() { List list = new ArrayList(); list.add(s1); list.add(s2); @@ -101,7 +109,8 @@ public class ToStringCreatorTests extends TestCase { str); } - public void testSet() { + @Test + public void appendSet() { Set set = new LinkedHashSet<>(3); set.add(s1); set.add(s2); @@ -111,22 +120,23 @@ public class ToStringCreatorTests extends TestCase { str); } - public void testClass() { + @Test + public void appendClass() { String str = new ToStringCreator(this).append("myClass", this.getClass()).toString(); assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) + " myClass = ToStringCreatorTests]", str); } - public void testMethod() throws Exception { - String str = new ToStringCreator(this).append("myMethod", this.getClass().getMethod("testMethod")) + @Test + public void appendMethod() throws Exception { + String str = new ToStringCreator(this).append("myMethod", this.getClass().getMethod("appendMethod")) .toString(); assertEquals("[ToStringCreatorTests@" + ObjectUtils.getIdentityHexString(this) - + " myMethod = testMethod@ToStringCreatorTests]", str); + + " myMethod = appendMethod@ToStringCreatorTests]", str); } public static class SomeObject { - } } diff --git a/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java b/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java index 57560a2566..9a6bb5edfc 100644 --- a/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java +++ b/spring-core/src/test/java/org/springframework/core/task/SimpleAsyncTaskExecutorTests.java @@ -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,42 +18,56 @@ package org.springframework.core.task; import java.util.concurrent.ThreadFactory; -import junit.framework.TestCase; - +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.util.ConcurrencyThrottleSupport; +import static org.hamcrest.CoreMatchers.*; + +import static org.junit.Assert.*; + /** * @author Rick Evans * @author Juergen Hoeller + * @author Sam Brannen */ -public final class SimpleAsyncTaskExecutorTests extends TestCase { +public final class SimpleAsyncTaskExecutorTests { - public void testCannotExecuteWhenConcurrencyIsSwitchedOff() throws Exception { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + + // TODO Determine why task is executed when concurrency is switched off. + @Ignore("Disabled because task is still executed when concurrency is switched off") + @Test + public void cannotExecuteWhenConcurrencyIsSwitchedOff() throws Exception { SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(); executor.setConcurrencyLimit(ConcurrencyThrottleSupport.NO_CONCURRENCY); assertFalse(executor.isThrottleActive()); - try { - executor.execute(new NoOpRunnable()); - } - catch (IllegalStateException expected) { - } + exception.expect(IllegalStateException.class); + executor.execute(new NoOpRunnable()); } - public void testThrottleIsNotActiveByDefault() throws Exception { + @Test + public void throttleIsNotActiveByDefault() throws Exception { SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(); assertFalse("Concurrency throttle must not default to being active (on)", executor.isThrottleActive()); } - public void testThreadNameGetsSetCorrectly() throws Exception { + @Test + public void threadNameGetsSetCorrectly() throws Exception { final String customPrefix = "chankPop#"; final Object monitor = new Object(); SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(customPrefix); ThreadNameHarvester task = new ThreadNameHarvester(monitor); executeAndWait(executor, task, monitor); - assertTrue(task.getThreadName().startsWith(customPrefix)); + assertThat(task.getThreadName(), startsWith(customPrefix)); } - public void testThreadFactoryOverridesDefaults() throws Exception { + @Test + public void threadFactoryOverridesDefaults() throws Exception { final Object monitor = new Object(); SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(new ThreadFactory() { @Override @@ -63,16 +77,13 @@ public final class SimpleAsyncTaskExecutorTests extends TestCase { }); ThreadNameHarvester task = new ThreadNameHarvester(monitor); executeAndWait(executor, task, monitor); - assertTrue(task.getThreadName().equals("test")); + assertEquals("test", task.getThreadName()); } - public void testThrowsExceptionWhenSuppliedWithNullRunnable() throws Exception { - try { - new SimpleAsyncTaskExecutor().execute(null); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException expected) { - } + @Test + public void throwsExceptionWhenSuppliedWithNullRunnable() throws Exception { + exception.expect(IllegalArgumentException.class); + new SimpleAsyncTaskExecutor().execute(null); } private void executeAndWait(SimpleAsyncTaskExecutor executor, Runnable task, Object monitor) { diff --git a/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java b/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java index 58d19b2ed0..66b64e0e3f 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AspectJTypeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 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,7 @@ package org.springframework.core.type; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; @@ -24,12 +24,15 @@ import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import org.springframework.core.type.filter.AspectJTypeFilter; import org.springframework.stereotype.Component; +import static org.junit.Assert.*; + /** * @author Ramnivas Laddad */ -public class AspectJTypeFilterTests extends TestCase { +public class AspectJTypeFilterTests { - public void testNamePatternMatches() throws Exception { + @Test + public void namePatternMatches() throws Exception { assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClass", "org.springframework.core.type.AspectJTypeFilterTests.SomeClass"); assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClass", @@ -40,12 +43,14 @@ public class AspectJTypeFilterTests extends TestCase { "org..SomeClass"); } - public void testNamePatternNoMatches() throws Exception { + @Test + public void namePatternNoMatches() throws Exception { assertNoMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClass", "org.springframework.core.type.AspectJTypeFilterTests.SomeClassX"); } - public void testSubclassPatternMatches() throws Exception { + @Test + public void subclassPatternMatches() throws Exception { assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClassExtendingSomeClass", "org.springframework.core.type.AspectJTypeFilterTests.SomeClass+"); assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClassExtendingSomeClass", @@ -72,12 +77,14 @@ public class AspectJTypeFilterTests extends TestCase { "java.lang.Object+"); } - public void testSubclassPatternNoMatches() throws Exception { + @Test + public void subclassPatternNoMatches() throws Exception { assertNoMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClassExtendingSomeClass", "java.lang.String+"); } - public void testAnnotationPatternMatches() throws Exception { + @Test + public void annotationPatternMatches() throws Exception { assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClassAnnotatedWithComponent", "@org.springframework.stereotype.Component *..*"); assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClassAnnotatedWithComponent", @@ -92,12 +99,14 @@ public class AspectJTypeFilterTests extends TestCase { "@org.springframework.stereotype.Component *"); } - public void testAnnotationPatternNoMathces() throws Exception { + @Test + public void annotationPatternNoMathces() throws Exception { assertNoMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClassAnnotatedWithComponent", "@org.springframework.stereotype.Repository *..*"); } - public void testCompositionPatternMatches() throws Exception { + @Test + public void compositionPatternMatches() throws Exception { assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClass", "!*..SomeOtherClass"); assertMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClassExtendingSomeClassExtendingSomeClassAndImplemnentingSomeInterface", @@ -110,7 +119,8 @@ public class AspectJTypeFilterTests extends TestCase { "|| org.springframework.core.type.AspectJTypeFilterTests.SomeClassExtendingSomeClass+"); } - public void testCompositionPatternNoMatches() throws Exception { + @Test + public void compositionPatternNoMatches() throws Exception { assertNoMatch("org.springframework.core.type.AspectJTypeFilterTests$SomeClass", "*..Bogus && org.springframework.core.type.AspectJTypeFilterTests.SomeClass"); } @@ -136,27 +146,22 @@ public class AspectJTypeFilterTests extends TestCase { // We must use a standalone set of types to ensure that no one else is loading them // and interfering with ClassloadingAssertions.assertClassNotLoaded() - static interface SomeInterface { + interface SomeInterface { } - static class SomeClass { } - static class SomeClassExtendingSomeClass extends SomeClass { } - static class SomeClassImplementingSomeInterface implements SomeInterface { } - static class SomeClassExtendingSomeClassExtendingSomeClassAndImplemnentingSomeInterface extends SomeClassExtendingSomeClass implements SomeInterface { } - @Component static class SomeClassAnnotatedWithComponent { } diff --git a/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java b/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java index 6b0fb640cf..019d508c9a 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java @@ -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,20 +16,23 @@ package org.springframework.core.type; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.classreading.SimpleMetadataReaderFactory; import org.springframework.core.type.filter.AssignableTypeFilter; +import static org.junit.Assert.*; + /** * @author Ramnivas Laddad * @author Juergen Hoeller */ -public class AssignableTypeFilterTests extends TestCase { +public class AssignableTypeFilterTests { - public void testDirectMatch() throws Exception { + @Test + public void directMatch() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$TestNonInheritingClass"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); @@ -40,7 +43,8 @@ public class AssignableTypeFilterTests extends TestCase { assertTrue(matchingFilter.match(metadataReader, metadataReaderFactory)); } - public void testInterfaceMatch() throws Exception { + @Test + public void interfaceMatch() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$TestInterfaceImpl"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); @@ -50,7 +54,8 @@ public class AssignableTypeFilterTests extends TestCase { ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } - public void testSuperClassMatch() throws Exception { + @Test + public void superClassMatch() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$SomeDaoLikeImpl"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); @@ -60,7 +65,8 @@ public class AssignableTypeFilterTests extends TestCase { ClassloadingAssertions.assertClassNotLoaded(classUnderTest); } - public void testInterfaceThroughSuperClassMatch() throws Exception { + @Test + public void interfaceThroughSuperClassMatch() throws Exception { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); String classUnderTest = "org.springframework.core.type.AssignableTypeFilterTests$SomeDaoLikeImpl"; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(classUnderTest); @@ -76,30 +82,24 @@ public class AssignableTypeFilterTests extends TestCase { private static class TestNonInheritingClass { } - - private static interface TestInterface { + private interface TestInterface { } - @SuppressWarnings("unused") private static class TestInterfaceImpl implements TestInterface { } - - private static interface SomeDaoLikeInterface { + private interface SomeDaoLikeInterface { } - @SuppressWarnings("unused") private static class SomeDaoLikeImpl extends SimpleJdbcDaoSupport implements SomeDaoLikeInterface { } - private static interface JdbcDaoSupport { - + private interface JdbcDaoSupport { } private static class SimpleJdbcDaoSupport implements JdbcDaoSupport { - } } diff --git a/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java b/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java index 6848c4d197..5db3daf2fc 100644 --- a/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/FileCopyUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 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,7 +23,9 @@ import java.io.StringReader; import java.io.StringWriter; import java.util.Arrays; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Unit tests for the FileCopyUtils class. @@ -31,9 +33,10 @@ import junit.framework.TestCase; * @author Juergen Hoeller * @since 12.03.2005 */ -public class FileCopyUtilsTests extends TestCase { +public class FileCopyUtilsTests { - public void testCopyFromInputStream() throws IOException { + @Test + public void copyFromInputStream() throws IOException { byte[] content = "content".getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(content); ByteArrayOutputStream out = new ByteArrayOutputStream(content.length); @@ -42,21 +45,24 @@ public class FileCopyUtilsTests extends TestCase { assertTrue(Arrays.equals(content, out.toByteArray())); } - public void testCopyFromByteArray() throws IOException { + @Test + public void copyFromByteArray() throws IOException { byte[] content = "content".getBytes(); ByteArrayOutputStream out = new ByteArrayOutputStream(content.length); FileCopyUtils.copy(content, out); assertTrue(Arrays.equals(content, out.toByteArray())); } - public void testCopyToByteArray() throws IOException { + @Test + public void copyToByteArray() throws IOException { byte[] content = "content".getBytes(); ByteArrayInputStream in = new ByteArrayInputStream(content); byte[] result = FileCopyUtils.copyToByteArray(in); assertTrue(Arrays.equals(content, result)); } - public void testCopyFromReader() throws IOException { + @Test + public void copyFromReader() throws IOException { String content = "content"; StringReader in = new StringReader(content); StringWriter out = new StringWriter(); @@ -65,14 +71,16 @@ public class FileCopyUtilsTests extends TestCase { assertEquals(content, out.toString()); } - public void testCopyFromString() throws IOException { + @Test + public void copyFromString() throws IOException { String content = "content"; StringWriter out = new StringWriter(); FileCopyUtils.copy(content, out); assertEquals(content, out.toString()); } - public void testCopyToString() throws IOException { + @Test + public void copyToString() throws IOException { String content = "content"; StringReader in = new StringReader(content); String result = FileCopyUtils.copyToString(in); diff --git a/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java b/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java index d87212c1ce..e9819aa170 100644 --- a/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/FileSystemUtilsTests.java @@ -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,14 +18,18 @@ package org.springframework.util; import java.io.File; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rob Harrop */ -public class FileSystemUtilsTests extends TestCase { +public class FileSystemUtilsTests { - public void testDeleteRecursively() throws Exception { + @Test + public void deleteRecursively() throws Exception { File root = new File("./tmp/root"); File child = new File(root, "child"); File grandchild = new File(child, "grandchild"); @@ -48,7 +52,8 @@ public class FileSystemUtilsTests extends TestCase { assertFalse(bar.exists()); } - public void testCopyRecursively() throws Exception { + @Test + public void copyRecursively() throws Exception { File src = new File("./tmp/src"); File child = new File(src, "child"); File grandchild = new File(child, "grandchild"); @@ -70,11 +75,12 @@ public class FileSystemUtilsTests extends TestCase { assertTrue(new File(dest, child.getName()).exists()); FileSystemUtils.deleteRecursively(src); - assertTrue(!src.exists()); + assertFalse(src.exists()); } - @Override - protected void tearDown() throws Exception { + + @After + public void tearDown() throws Exception { File tmp = new File("./tmp"); if (tmp.exists()) { FileSystemUtils.deleteRecursively(tmp); @@ -83,7 +89,6 @@ public class FileSystemUtilsTests extends TestCase { if (dest.exists()) { FileSystemUtils.deleteRecursively(dest); } - super.tearDown(); } } diff --git a/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java b/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java index 679ab9566e..4800142dfa 100644 --- a/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java +++ b/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java @@ -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,16 +20,26 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import junit.framework.TestCase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.junit.Assert.*; /** * @author Colin Sampaleanu * @author Juergen Hoeller + * @author Sam Brannen * @since 21.11.2003 */ -public class MethodInvokerTests extends TestCase { +public class MethodInvokerTests { - public void testPlainMethodInvoker() throws Exception { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + + @Test + public void plainMethodInvoker() throws Exception { // sanity check: singleton, non-static should work TestClass1 tc1 = new TestClass1(); MethodInvoker mi = new MethodInvoker(); @@ -59,30 +69,24 @@ public class MethodInvokerTests extends TestCase { mi.setTargetClass(TestClass1.class); mi.setTargetMethod("supertypes2"); mi.setArguments(new Object[] {new ArrayList<>(), new ArrayList<>(), "hello", Boolean.TRUE}); - try { - mi.prepare(); - fail("Shouldn't have matched without argument conversion"); - } - catch (NoSuchMethodException ex) { - // expected - } + + exception.expect(NoSuchMethodException.class); + mi.prepare(); } - public void testStringWithMethodInvoker() throws Exception { - try { - MethodInvoker methodInvoker = new MethodInvoker(); - methodInvoker.setTargetObject(new Greeter()); - methodInvoker.setTargetMethod("greet"); - methodInvoker.setArguments(new Object[] {new String("no match")}); - methodInvoker.prepare(); - fail("Should have thrown a NoSuchMethodException"); - } - catch (NoSuchMethodException e) { - // expected - } + @Test + public void stringWithMethodInvoker() throws Exception { + MethodInvoker methodInvoker = new MethodInvoker(); + methodInvoker.setTargetObject(new Greeter()); + methodInvoker.setTargetMethod("greet"); + methodInvoker.setArguments(new Object[] { new String("no match") }); + + exception.expect(NoSuchMethodException.class); + methodInvoker.prepare(); } - public void testPurchaserWithMethodInvoker() throws Exception { + @Test + public void purchaserWithMethodInvoker() throws Exception { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(new Greeter()); methodInvoker.setTargetMethod("greet"); @@ -92,7 +96,8 @@ public class MethodInvokerTests extends TestCase { assertEquals("purchaser: hello", greeting); } - public void testShopperWithMethodInvoker() throws Exception { + @Test + public void shopperWithMethodInvoker() throws Exception { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(new Greeter()); methodInvoker.setTargetMethod("greet"); @@ -102,7 +107,8 @@ public class MethodInvokerTests extends TestCase { assertEquals("purchaser: may I help you?", greeting); } - public void testSalesmanWithMethodInvoker() throws Exception { + @Test + public void salesmanWithMethodInvoker() throws Exception { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(new Greeter()); methodInvoker.setTargetMethod("greet"); @@ -112,7 +118,8 @@ public class MethodInvokerTests extends TestCase { assertEquals("greetable: how are sales?", greeting); } - public void testCustomerWithMethodInvoker() throws Exception { + @Test + public void customerWithMethodInvoker() throws Exception { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(new Greeter()); methodInvoker.setTargetMethod("greet"); @@ -122,7 +129,8 @@ public class MethodInvokerTests extends TestCase { assertEquals("customer: good day", greeting); } - public void testRegularWithMethodInvoker() throws Exception { + @Test + public void regularWithMethodInvoker() throws Exception { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(new Greeter()); methodInvoker.setTargetMethod("greet"); @@ -132,7 +140,8 @@ public class MethodInvokerTests extends TestCase { assertEquals("regular: welcome back Kotter", greeting); } - public void testVIPWithMethodInvoker() throws Exception { + @Test + public void vipWithMethodInvoker() throws Exception { MethodInvoker methodInvoker = new MethodInvoker(); methodInvoker.setTargetObject(new Greeter()); methodInvoker.setTargetMethod("greet"); @@ -190,7 +199,6 @@ public class MethodInvokerTests extends TestCase { } } - @SuppressWarnings("unused") public static class Greeter { @@ -215,17 +223,13 @@ public class MethodInvokerTests extends TestCase { } } - - private static interface Greetable { - + private interface Greetable { String getGreeting(); } - - private static interface Person extends Greetable { + private interface Person extends Greetable { } - private static class Purchaser implements Greetable { @Override @@ -234,7 +238,6 @@ public class MethodInvokerTests extends TestCase { } } - private static class Shopper extends Purchaser implements Person { @Override @@ -243,7 +246,6 @@ public class MethodInvokerTests extends TestCase { } } - private static class Salesman implements Person { @Override @@ -252,7 +254,6 @@ public class MethodInvokerTests extends TestCase { } } - private static class Customer extends Shopper { @Override @@ -261,7 +262,6 @@ public class MethodInvokerTests extends TestCase { } } - private static class Regular extends Customer { private String name; @@ -276,7 +276,6 @@ public class MethodInvokerTests extends TestCase { } } - private static class VIP extends Regular { public VIP(String name) { diff --git a/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java b/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java index 0fcc4238ae..823241d6a9 100644 --- a/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java +++ b/spring-core/src/test/java/org/springframework/util/PropertiesPersisterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2005 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,64 +23,74 @@ import java.io.StringReader; import java.io.StringWriter; import java.util.Properties; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Juergen Hoeller * @since 11.01.2005 */ -public class PropertiesPersisterTests extends TestCase { +public class PropertiesPersisterTests { - public void testPropertiesPersister() throws IOException { + @Test + public void propertiesPersister() throws IOException { String propString = "code1=message1\ncode2:message2"; Properties props = loadProperties(propString, false); String propCopy = storeProperties(props, null, false); loadProperties(propCopy, false); } - public void testPropertiesPersisterWithWhitespace() throws IOException { + @Test + public void propertiesPersisterWithWhitespace() throws IOException { String propString = " code1\t= \tmessage1\n code2 \t :\t mess\\\n \t age2"; Properties props = loadProperties(propString, false); String propCopy = storeProperties(props, null, false); loadProperties(propCopy, false); } - public void testPropertiesPersisterWithHeader() throws IOException { + @Test + public void propertiesPersisterWithHeader() throws IOException { String propString = "code1=message1\ncode2:message2"; Properties props = loadProperties(propString, false); String propCopy = storeProperties(props, "myHeader", false); loadProperties(propCopy, false); } - public void testPropertiesPersisterWithEmptyValue() throws IOException { + @Test + public void propertiesPersisterWithEmptyValue() throws IOException { String propString = "code1=message1\ncode2:message2\ncode3="; Properties props = loadProperties(propString, false); String propCopy = storeProperties(props, null, false); loadProperties(propCopy, false); } - public void testPropertiesPersisterWithReader() throws IOException { + @Test + public void propertiesPersisterWithReader() throws IOException { String propString = "code1=message1\ncode2:message2"; Properties props = loadProperties(propString, true); String propCopy = storeProperties(props, null, true); loadProperties(propCopy, false); } - public void testPropertiesPersisterWithReaderAndWhitespace() throws IOException { + @Test + public void propertiesPersisterWithReaderAndWhitespace() throws IOException { String propString = " code1\t= \tmessage1\n code2 \t :\t mess\\\n \t age2"; Properties props = loadProperties(propString, true); String propCopy = storeProperties(props, null, true); loadProperties(propCopy, false); } - public void testPropertiesPersisterWithReaderAndHeader() throws IOException { + @Test + public void propertiesPersisterWithReaderAndHeader() throws IOException { String propString = "code1\t=\tmessage1\n code2 \t : \t message2"; Properties props = loadProperties(propString, true); String propCopy = storeProperties(props, "myHeader", true); loadProperties(propCopy, false); } - public void testPropertiesPersisterWithReaderAndEmptyValue() throws IOException { + @Test + public void propertiesPersisterWithReaderAndEmptyValue() throws IOException { String propString = "code1=message1\ncode2:message2\ncode3="; Properties props = loadProperties(propString, true); String propCopy = storeProperties(props, null, true); diff --git a/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java index 7129e8d23c..cd8343f43c 100644 --- a/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ResourceUtilsTests.java @@ -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. @@ -21,14 +21,17 @@ import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Juergen Hoeller */ -public class ResourceUtilsTests extends TestCase { +public class ResourceUtilsTests { - public void testIsJarURL() throws Exception { + @Test + public void isJarURL() throws Exception { assertTrue(ResourceUtils.isJarURL(new URL("jar:file:myjar.jar!/mypath"))); assertTrue(ResourceUtils.isJarURL(new URL(null, "zip:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); assertTrue(ResourceUtils.isJarURL(new URL(null, "wsjar:file:myjar.jar!/mypath", new DummyURLStreamHandler()))); @@ -36,7 +39,8 @@ public class ResourceUtilsTests extends TestCase { assertFalse(ResourceUtils.isJarURL(new URL("http:myserver/myjar.jar"))); } - public void testExtractJarFileURL() throws Exception { + @Test + public void extractJarFileURL() throws Exception { assertEquals(new URL("file:myjar.jar"), ResourceUtils.extractJarFileURL(new URL("jar:file:myjar.jar!/mypath"))); assertEquals(new URL("file:/myjar.jar"), diff --git a/spring-core/src/test/java/org/springframework/util/StopWatchTests.java b/spring-core/src/test/java/org/springframework/util/StopWatchTests.java index e039b2555e..23273068c2 100644 --- a/spring-core/src/test/java/org/springframework/util/StopWatchTests.java +++ b/spring-core/src/test/java/org/springframework/util/StopWatchTests.java @@ -16,18 +16,26 @@ package org.springframework.util; -import junit.framework.TestCase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import static org.junit.Assert.*; /** * @author Rod Johnson * @author Juergen Hoeller + * @author Sam Brannen */ -public class StopWatchTests extends TestCase { +public class StopWatchTests { - /** - * Are timings off in JUnit? - */ - public void testValidUsage() throws Exception { + private final StopWatch sw = new StopWatch(); + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + @Test + public void validUsage() throws Exception { String id = "myId"; StopWatch sw = new StopWatch(id); long int1 = 166L; @@ -45,14 +53,18 @@ public class StopWatchTests extends TestCase { // TODO are timings off in JUnit? Why do these assertions sometimes fail // under both Ant and Eclipse? - //long fudgeFactor = 5L; - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1); - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + fudgeFactor); + // long fudgeFactor = 5L; + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= + // int1); + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + // + fudgeFactor); sw.start(name2); Thread.sleep(int2); sw.stop(); - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1 + int2); - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + int2 + fudgeFactor); + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1 + // + int2); + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + // + int2 + fudgeFactor); assertTrue(sw.getTaskCount() == 2); String pp = sw.prettyPrint(); @@ -72,8 +84,8 @@ public class StopWatchTests extends TestCase { assertEquals(id, sw.getId()); } - public void testValidUsageNotKeepingTaskList() throws Exception { - StopWatch sw = new StopWatch(); + @Test + public void validUsageNotKeepingTaskList() throws Exception { sw.setKeepTaskList(false); long int1 = 166L; long int2 = 45L; @@ -89,14 +101,18 @@ public class StopWatchTests extends TestCase { // TODO are timings off in JUnit? Why do these assertions sometimes fail // under both Ant and Eclipse? - //long fudgeFactor = 5L; - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1); - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + fudgeFactor); + // long fudgeFactor = 5L; + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= + // int1); + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + // + fudgeFactor); sw.start(name2); Thread.sleep(int2); sw.stop(); - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1 + int2); - //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + int2 + fudgeFactor); + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1 + // + int2); + // assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + // + int2 + fudgeFactor); assertTrue(sw.getTaskCount() == 2); String pp = sw.prettyPrint(); @@ -106,50 +122,30 @@ public class StopWatchTests extends TestCase { assertFalse(toString.contains(name1)); assertFalse(toString.contains(name2)); - try { - sw.getTaskInfo(); - fail(); - } - catch (UnsupportedOperationException ex) { - // Ok - } + exception.expect(UnsupportedOperationException.class); + sw.getTaskInfo(); } - public void testFailureToStartBeforeGettingTimings() { - StopWatch sw = new StopWatch(); - try { - sw.getLastTaskTimeMillis(); - fail("Can't get last interval if no tests run"); - } - catch (IllegalStateException ex) { - // Ok - } + @Test + public void failureToStartBeforeGettingTimings() { + exception.expect(IllegalStateException.class); + sw.getLastTaskTimeMillis(); } - public void testFailureToStartBeforeStop() { - StopWatch sw = new StopWatch(); - try { - sw.stop(); - fail("Can't stop without starting"); - } - catch (IllegalStateException ex) { - // Ok - } + @Test + public void failureToStartBeforeStop() { + exception.expect(IllegalStateException.class); + sw.stop(); } - public void testRejectsStartTwice() { - StopWatch sw = new StopWatch(); - try { - sw.start(""); - sw.stop(); - sw.start(""); - assertTrue(sw.isRunning()); - sw.start(""); - fail("Can't start twice"); - } - catch (IllegalStateException ex) { - // Ok - } + @Test + public void rejectsStartTwice() { + sw.start(""); + sw.stop(); + sw.start(""); + assertTrue(sw.isRunning()); + exception.expect(IllegalStateException.class); + sw.start(""); } } diff --git a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java index b0edb06f55..9dec693d61 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java +++ b/spring-core/src/test/java/org/springframework/util/xml/AbstractStaxXMLReaderTestCase.java @@ -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. @@ -18,6 +18,7 @@ package org.springframework.util.xml; import java.io.ByteArrayInputStream; import java.io.InputStream; + import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.transform.Transformer; @@ -27,8 +28,15 @@ import javax.xml.transform.sax.SAXSource; import org.junit.Before; import org.junit.Test; + import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.tests.MockitoUtils; +import org.springframework.tests.MockitoUtils.InvocationArgumentsAdapter; + import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; @@ -39,11 +47,6 @@ import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLReaderFactory; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.tests.MockitoUtils; -import org.springframework.tests.MockitoUtils.InvocationArgumentsAdapter; - import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java index e3a1927e84..7db65b8ae4 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxEventXMLReaderTests.java @@ -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,19 @@ package org.springframework.util.xml; import java.io.InputStream; import java.io.StringReader; + import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; +import org.junit.Test; + +import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; -import org.xml.sax.helpers.AttributesImpl; -import static org.mockito.BDDMockito.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; public class StaxEventXMLReaderTests extends AbstractStaxXMLReaderTestCase { @@ -37,7 +41,8 @@ public class StaxEventXMLReaderTests extends AbstractStaxXMLReaderTestCase { return new StaxEventXMLReader(inputFactory.createXMLEventReader(inputStream)); } - public void testPartial() throws Exception { + @Test + public void partial() throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLEventReader eventReader = inputFactory.createXMLEventReader(new StringReader(CONTENT)); eventReader.nextTag(); // skip to root @@ -46,7 +51,7 @@ public class StaxEventXMLReaderTests extends AbstractStaxXMLReaderTestCase { xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource()); verify(contentHandler).startDocument(); - verify(contentHandler).startElement("http://springframework.org/spring-ws", "child", "child", new AttributesImpl()); + verify(contentHandler).startElement(eq("http://springframework.org/spring-ws"), eq("child"), eq("child"), any(Attributes.class)); verify(contentHandler).endElement("http://springframework.org/spring-ws", "child", "child"); verify(contentHandler).endDocument(); } diff --git a/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java b/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java index 49488f0b83..b276a0eb6d 100644 --- a/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java +++ b/spring-core/src/test/java/org/springframework/util/xml/StaxStreamXMLReaderTests.java @@ -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,19 +18,22 @@ package org.springframework.util.xml; import java.io.InputStream; import java.io.StringReader; + import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.junit.Test; + import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import static org.junit.Assert.*; -import static org.mockito.BDDMockito.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; public class StaxStreamXMLReaderTests extends AbstractStaxXMLReaderTestCase { @@ -42,7 +45,7 @@ public class StaxStreamXMLReaderTests extends AbstractStaxXMLReaderTestCase { } @Test - public void testPartial() throws Exception { + public void partial() throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(CONTENT)); streamReader.nextTag(); // skip to root diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java index 9c3faf6dea..53117a6027 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/RowMapperTests.java @@ -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,7 +24,6 @@ import java.sql.Statement; import java.sql.Types; import java.util.List; -import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -33,30 +32,33 @@ import org.springframework.jdbc.datasource.SingleConnectionDataSource; import org.springframework.jdbc.support.SQLStateSQLExceptionTranslator; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Juergen Hoeller + * @author Sam Brannen * @since 02.08.2004 */ -public class RowMapperTests extends TestCase { +public class RowMapperTests { - private Connection connection; - private Statement statement; - private PreparedStatement preparedStatement; - private ResultSet resultSet; + private final Connection connection = mock(Connection.class); - private JdbcTemplate template; + private final Statement statement = mock(Statement.class); + + private final PreparedStatement preparedStatement = mock(PreparedStatement.class); + + private final ResultSet resultSet = mock(ResultSet.class); + + private final JdbcTemplate template = new JdbcTemplate(); + + private final RowMapper testRowMapper = + (rs, rowNum) -> new TestBean(rs.getString(1), rs.getInt(2)); private List result; - @Override @Before public void setUp() throws SQLException { - connection = mock(Connection.class); - statement = mock(Statement.class); - preparedStatement = mock(PreparedStatement.class); - resultSet = mock(ResultSet.class); given(connection.createStatement()).willReturn(statement); given(connection.prepareStatement(anyString())).willReturn(preparedStatement); given(statement.executeQuery(anyString())).willReturn(resultSet); @@ -64,7 +66,7 @@ public class RowMapperTests extends TestCase { given(resultSet.next()).willReturn(true, true, false); given(resultSet.getString(1)).willReturn("tb1", "tb2"); given(resultSet.getInt(2)).willReturn(1, 2); - template = new JdbcTemplate(); + template.setDataSource(new SingleConnectionDataSource(connection, false)); template.setExceptionTranslator(new SQLStateSQLExceptionTranslator()); template.afterPropertiesSet(); @@ -73,75 +75,57 @@ public class RowMapperTests extends TestCase { @After public void verifyClosed() throws Exception { verify(resultSet).close(); - verify(connection).close(); + // verify(connection).close(); } @After public void verifyResults() { - assertTrue(result != null); + assertNotNull(result); assertEquals(2, result.size()); - assertEquals("tb1", result.get(0).getName()); - assertEquals("tb2", result.get(1).getName()); - assertEquals(1, result.get(0).getAge()); - assertEquals(2, result.get(1).getAge()); + TestBean testBean1 = result.get(0); + TestBean testBean2 = result.get(1); + assertEquals("tb1", testBean1.getName()); + assertEquals("tb2", testBean2.getName()); + assertEquals(1, testBean1.getAge()); + assertEquals(2, testBean2.getAge()); } @Test - public void testStaticQueryWithRowMapper() throws SQLException { - result = template.query("some SQL", new TestRowMapper()); + public void staticQueryWithRowMapper() throws SQLException { + result = template.query("some SQL", testRowMapper); verify(statement).close(); } @Test - public void testPreparedStatementCreatorWithRowMapper() throws SQLException { - result = template.query(new PreparedStatementCreator() { - @Override - public PreparedStatement createPreparedStatement(Connection con) - throws SQLException { - return preparedStatement; - } - }, new TestRowMapper()); + public void preparedStatementCreatorWithRowMapper() throws SQLException { + result = template.query(con -> preparedStatement, testRowMapper); verify(preparedStatement).close(); } @Test - public void testPreparedStatementSetterWithRowMapper() throws SQLException { - result = template.query("some SQL", new PreparedStatementSetter() { - @Override - public void setValues(PreparedStatement ps) throws SQLException { - ps.setString(1, "test"); - } - }, new TestRowMapper()); + public void preparedStatementSetterWithRowMapper() throws SQLException { + result = template.query("some SQL", ps -> ps.setString(1, "test"), testRowMapper); verify(preparedStatement).setString(1, "test"); verify(preparedStatement).close(); } @Test - public void testQueryWithArgsAndRowMapper() throws SQLException { - result = template.query("some SQL", - new Object[] { "test1", "test2" }, - new TestRowMapper()); + public void queryWithArgsAndRowMapper() throws SQLException { + result = template.query("some SQL", new Object[] { "test1", "test2" }, testRowMapper); preparedStatement.setString(1, "test1"); preparedStatement.setString(2, "test2"); preparedStatement.close(); } @Test - public void testQueryWithArgsAndTypesAndRowMapper() throws SQLException { + public void queryWithArgsAndTypesAndRowMapper() throws SQLException { result = template.query("some SQL", new Object[] { "test1", "test2" }, new int[] { Types.VARCHAR, Types.VARCHAR }, - new TestRowMapper()); + testRowMapper); verify(preparedStatement).setString(1, "test1"); verify(preparedStatement).setString(2, "test2"); verify(preparedStatement).close(); } - private static class TestRowMapper implements RowMapper { - @Override - public TestBean mapRow(ResultSet rs, int rowNum) throws SQLException { - return new TestBean(rs.getString(1), rs.getInt(2)); - } - } - } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java index d0ff6c19df..9a0307d525 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/object/RdbmsOperationTests.java @@ -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. @@ -19,9 +19,12 @@ package org.springframework.jdbc.object; import java.sql.Types; import java.util.HashMap; import java.util.Map; + import javax.sql.DataSource; -import junit.framework.TestCase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.jdbc.core.JdbcTemplate; @@ -30,119 +33,90 @@ import org.springframework.jdbc.core.SqlOutParameter; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import static org.hamcrest.CoreMatchers.*; + +import static org.junit.Assert.*; + /** * @author Trevor Cook * @author Juergen Hoeller + * @author Sam Brannen */ -public class RdbmsOperationTests extends TestCase { +public class RdbmsOperationTests { - public void testEmptySql() { - TestRdbmsOperation operation = new TestRdbmsOperation(); - try { - operation.compile(); - fail("Shouldn't allow compiling without sql statement"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + private final TestRdbmsOperation operation = new TestRdbmsOperation(); + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + + @Test + public void emptySql() { + exception.expect(InvalidDataAccessApiUsageException.class); + operation.compile(); } - public void testSetTypeAfterCompile() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void setTypeAfterCompile() { operation.setDataSource(new DriverManagerDataSource()); operation.setSql("select * from mytable"); operation.compile(); - try { - operation.setTypes(new int[] {Types.INTEGER }); - fail("Shouldn't allow setting parameters after compile"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + exception.expect(InvalidDataAccessApiUsageException.class); + operation.setTypes(new int[] { Types.INTEGER }); } - public void testDeclareParameterAfterCompile() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void declareParameterAfterCompile() { operation.setDataSource(new DriverManagerDataSource()); operation.setSql("select * from mytable"); operation.compile(); - try { - operation.declareParameter(new SqlParameter(Types.INTEGER)); - fail("Shouldn't allow setting parameters after compile"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + exception.expect(InvalidDataAccessApiUsageException.class); + operation.declareParameter(new SqlParameter(Types.INTEGER)); } - public void testTooFewParameters() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void tooFewParameters() { operation.setSql("select * from mytable"); operation.setTypes(new int[] { Types.INTEGER }); - try { - operation.validateParameters((Object[]) null); - fail("Shouldn't validate without enough parameters"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + exception.expect(InvalidDataAccessApiUsageException.class); + operation.validateParameters((Object[]) null); } - public void testTooFewMapParameters() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void tooFewMapParameters() { operation.setSql("select * from mytable"); operation.setTypes(new int[] { Types.INTEGER }); - try { - operation.validateNamedParameters((Map) null); - fail("Shouldn't validate without enough parameters"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + exception.expect(InvalidDataAccessApiUsageException.class); + operation.validateNamedParameters((Map) null); } - public void testOperationConfiguredViaJdbcTemplateMustGetDataSource() throws Exception { - try { - TestRdbmsOperation operation = new TestRdbmsOperation(); - operation.setSql("foo"); - operation.compile(); - fail("Can't compile without providing a DataSource for the JdbcTemplate"); - } - catch (InvalidDataAccessApiUsageException ex) { - // Check for helpful error message. Omit leading character - // so as not to be fussy about case - assertTrue(ex.getMessage().indexOf("ataSource") != -1); - } + @Test + public void operationConfiguredViaJdbcTemplateMustGetDataSource() throws Exception { + operation.setSql("foo"); + + exception.expect(InvalidDataAccessApiUsageException.class); + exception.expectMessage(containsString("ataSource")); + operation.compile(); } - public void testTooManyParameters() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void tooManyParameters() { operation.setSql("select * from mytable"); - try { - operation.validateParameters(new Object[] {1, 2}); - fail("Shouldn't validate with too many parameters"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + exception.expect(InvalidDataAccessApiUsageException.class); + operation.validateParameters(new Object[] { 1, 2 }); } - public void testUnspecifiedMapParameters() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void unspecifiedMapParameters() { operation.setSql("select * from mytable"); - try { - Map params = new HashMap(); - params.put("col1", "value"); - operation.validateNamedParameters(params); - fail("Shouldn't validate with unspecified parameters"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + Map params = new HashMap(); + params.put("col1", "value"); + exception.expect(InvalidDataAccessApiUsageException.class); + operation.validateNamedParameters(params); } - public void testCompileTwice() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void compileTwice() { operation.setDataSource(new DriverManagerDataSource()); operation.setSql("select * from mytable"); operation.setTypes(null); @@ -150,22 +124,17 @@ public class RdbmsOperationTests extends TestCase { operation.compile(); } - public void testEmptyDataSource() { - SqlOperation operation = new SqlOperation() { - }; + @Test + public void emptyDataSource() { + SqlOperation operation = new SqlOperation() {}; operation.setSql("select * from mytable"); - try { - operation.compile(); - fail("Shouldn't allow compiling without data source"); - } - catch (InvalidDataAccessApiUsageException idaauex) { - // OK - } + exception.expect(InvalidDataAccessApiUsageException.class); + operation.compile(); } - public void testParameterPropagation() { - SqlOperation operation = new SqlOperation() { - }; + @Test + public void parameterPropagation() { + SqlOperation operation = new SqlOperation() {}; DataSource ds = new DriverManagerDataSource(); operation.setDataSource(ds); operation.setFetchSize(10); @@ -176,8 +145,8 @@ public class RdbmsOperationTests extends TestCase { assertEquals(20, jt.getMaxRows()); } - public void testValidateInOutParameter() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void validateInOutParameter() { operation.setDataSource(new DriverManagerDataSource()); operation.setSql("DUMMY_PROC"); operation.declareParameter(new SqlOutParameter("DUMMY_OUT_PARAM", Types.VARCHAR)); @@ -185,8 +154,8 @@ public class RdbmsOperationTests extends TestCase { operation.validateParameters(new Object[] {"DUMMY_VALUE1", "DUMMY_VALUE2"}); } - public void testParametersSetWithList() { - TestRdbmsOperation operation = new TestRdbmsOperation(); + @Test + public void parametersSetWithList() { DataSource ds = new DriverManagerDataSource(); operation.setDataSource(ds); operation.setSql("select * from mytable where one = ? and two = ?"); @@ -194,14 +163,8 @@ public class RdbmsOperationTests extends TestCase { new SqlParameter("one", Types.NUMERIC), new SqlParameter("two", Types.NUMERIC)}); operation.afterPropertiesSet(); - try { - operation.validateParameters(new Object[] {1, "2"}); - assertEquals(2, operation.getDeclaredParameters().size()); - // OK - } - catch (InvalidDataAccessApiUsageException idaauex) { - fail("Should have validated with parameters set using List: " + idaauex.getMessage()); - } + operation.validateParameters(new Object[] { 1, "2" }); + assertEquals(2, operation.getDeclaredParameters().size()); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java index 637032c695..8a2878425a 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/JdbcUtilsTests.java @@ -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. @@ -16,28 +16,32 @@ package org.springframework.jdbc.support; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** - * Unit tests for JdbcUtils. + * Unit tests for {@link JdbcUtils}. * * @author Thomas Risberg */ -public class JdbcUtilsTests extends TestCase { +public class JdbcUtilsTests { - public void testCommonDatabaseName() { - assertEquals("Wrong db name", "Oracle", JdbcUtils.commonDatabaseName("Oracle")); - assertEquals("Wrong db name", "DB2", JdbcUtils.commonDatabaseName("DB2-for-Spring")); - assertEquals("Wrong db name", "Sybase", JdbcUtils.commonDatabaseName("Sybase SQL Server")); - assertEquals("Wrong db name", "Sybase", JdbcUtils.commonDatabaseName("Adaptive Server Enterprise")); - assertEquals("Wrong db name", "MySQL", JdbcUtils.commonDatabaseName("MySQL")); + @Test + public void commonDatabaseName() { + assertEquals("Oracle", JdbcUtils.commonDatabaseName("Oracle")); + assertEquals("DB2", JdbcUtils.commonDatabaseName("DB2-for-Spring")); + assertEquals("Sybase", JdbcUtils.commonDatabaseName("Sybase SQL Server")); + assertEquals("Sybase", JdbcUtils.commonDatabaseName("Adaptive Server Enterprise")); + assertEquals("MySQL", JdbcUtils.commonDatabaseName("MySQL")); } - public void testConvertUnderscoreNameToPropertyName() { - assertEquals("Wrong property name", "myName", JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME")); - assertEquals("Wrong property name", "yourName", JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME")); - assertEquals("Wrong property name", "AName", JdbcUtils.convertUnderscoreNameToPropertyName("a_name")); - assertEquals("Wrong property name", "someoneElsesName", JdbcUtils.convertUnderscoreNameToPropertyName("someone_elses_name")); + @Test + public void convertUnderscoreNameToPropertyName() { + assertEquals("myName", JdbcUtils.convertUnderscoreNameToPropertyName("MY_NAME")); + assertEquals("yourName", JdbcUtils.convertUnderscoreNameToPropertyName("yOUR_nAME")); + assertEquals("AName", JdbcUtils.convertUnderscoreNameToPropertyName("a_name")); + assertEquals("someoneElsesName", JdbcUtils.convertUnderscoreNameToPropertyName("someone_elses_name")); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java index 480b8696d8..7bc9e0e65c 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/KeyHolderTests.java @@ -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. @@ -17,98 +17,87 @@ package org.springframework.jdbc.support; import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.dao.InvalidDataAccessApiUsageException; +import static java.util.Arrays.asList; +import static java.util.Collections.*; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + /** - * Tests for the KeyHolder and GeneratedKeyHolder - * and it appears that JdbcUtils doesn't work exactly as documented. + * Tests for {@link KeyHolder} and {@link GeneratedKeyHolder}. * - * @author trisberg - * @since Jul 18, 2004 + * @author Thomas Risberg + * @author Sam Brannen + * @since July 18, 2004 */ -public class KeyHolderTests extends TestCase { - private KeyHolder kh; +@SuppressWarnings("serial") +public class KeyHolderTests { - @Override - public void setUp() { - kh = new GeneratedKeyHolder(); - } + private final KeyHolder kh = new GeneratedKeyHolder(); + + @Rule + public final ExpectedException exception = ExpectedException.none(); + + + @Test + public void singleKey() { + kh.getKeyList().addAll(singletonList(singletonMap("key", 1))); - public void testSingleKey(){ - List> l = new LinkedList>(); - Map m = new HashMap(1); - m.put("key", 1); - l.add(m); - kh.getKeyList().addAll(l); assertEquals("single key should be returned", 1, kh.getKey().intValue()); } - public void testSingleKeyNonNumeric(){ - List> l = new LinkedList>(); - Map m = new HashMap(1); - m.put("key", "1"); - l.add(m); - kh.getKeyList().addAll(l); - try { - kh.getKey().intValue(); - } - catch (DataRetrievalFailureException e) { - assertTrue(e.getMessage().startsWith("The generated key is not of a supported numeric type.")); - } + @Test + public void singleKeyNonNumeric() { + kh.getKeyList().addAll(singletonList(singletonMap("key", "1"))); + + exception.expect(DataRetrievalFailureException.class); + exception.expectMessage(startsWith("The generated key is not of a supported numeric type.")); + kh.getKey().intValue(); } - public void testNoKeyReturnedInMap(){ - List> l = new LinkedList>(); - Map m = new HashMap(); - l.add(m); - kh.getKeyList().addAll(l); - try { - kh.getKey(); - } - catch (DataRetrievalFailureException e) { - assertTrue(e.getMessage().startsWith("Unable to retrieve the generated key.")); - } + @Test + public void noKeyReturnedInMap() { + kh.getKeyList().addAll(singletonList(emptyMap())); + + exception.expect(DataRetrievalFailureException.class); + exception.expectMessage(startsWith("Unable to retrieve the generated key.")); + kh.getKey(); } - public void testMultipleKeys(){ - List> l = new LinkedList>(); - Map m = new HashMap(2); - m.put("key", 1); - m.put("seq", 2); - l.add(m); - kh.getKeyList().addAll(l); - Map keyMap = kh.getKeys(); - assertEquals("two keys should be in the map", 2, keyMap.size()); - try { - kh.getKey(); - } - catch (InvalidDataAccessApiUsageException e) { - assertTrue(e.getMessage().startsWith("The getKey method should only be used when a single key is returned.")); - } + @Test + public void multipleKeys() { + Map m = new HashMap() {{ + put("key", 1); + put("seq", 2); + }}; + kh.getKeyList().addAll(singletonList(m)); + + assertEquals("two keys should be in the map", 2, kh.getKeys().size()); + exception.expect(InvalidDataAccessApiUsageException.class); + exception.expectMessage(startsWith("The getKey method should only be used when a single key is returned.")); + kh.getKey(); } - public void testMultipleKeyRows(){ - List> l = new LinkedList>(); - Map m = new HashMap(2); - m.put("key", 1); - m.put("seq", 2); - l.add(m); - l.add(m); - kh.getKeyList().addAll(l); + @Test + public void multipleKeyRows() { + Map m = new HashMap() {{ + put("key", 1); + put("seq", 2); + }}; + kh.getKeyList().addAll(asList(m, m)); assertEquals("two rows should be in the list", 2, kh.getKeyList().size()); - try { - kh.getKeys(); - } - catch (InvalidDataAccessApiUsageException e) { - assertTrue(e.getMessage().startsWith("The getKeys method should only be used when keys for a single row are returned.")); - } + exception.expect(InvalidDataAccessApiUsageException.class); + exception.expectMessage(startsWith("The getKeys method should only be used when keys for a single row are returned.")); + kh.getKeys(); } + } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java index 2c9b0902ff..20993a141f 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java @@ -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,7 +20,9 @@ import java.sql.BatchUpdateException; import java.sql.DataTruncation; import java.sql.SQLException; -import junit.framework.TestCase; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.dao.CannotAcquireLockException; import org.springframework.dao.CannotSerializeTransactionException; @@ -32,11 +34,14 @@ import org.springframework.dao.DuplicateKeyException; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.InvalidResultSetAccessException; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller + * @author Sam Brannen */ -public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { +public class SQLErrorCodeSQLExceptionTranslatorTests { private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes(); static { @@ -50,7 +55,12 @@ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { ERROR_CODES.setCannotSerializeTransactionCodes(new String[] { "9" }); } - public void testErrorCodeTranslation() { + @Rule + public final ExpectedException exception = ExpectedException.none(); + + + @Test + public void errorCodeTranslation() { SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); SQLException badSqlEx = new SQLException("", "", 1); @@ -90,7 +100,8 @@ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { assertTrue(ex.getCause() == sex); } - public void testBatchExceptionTranslation() { + @Test + public void batchExceptionTranslation() { SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); SQLException badSqlEx = new SQLException("", "", 1); @@ -101,7 +112,8 @@ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { assertEquals(badSqlEx, bsgex.getSQLException()); } - public void testDataTruncationTranslation() { + @Test + public void dataTruncationTranslation() { SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); SQLException dataAccessEx = new SQLException("", "", 5); @@ -111,7 +123,8 @@ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { } @SuppressWarnings("serial") - public void testCustomTranslateMethodTranslation() { + @Test + public void customTranslateMethodTranslation() { final String TASK = "TASK"; final String SQL = "SQL SELECT *"; final DataAccessException customDex = new DataAccessException("") {}; @@ -135,7 +148,8 @@ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { assertEquals(intVioEx, diex.getCause()); } - public void testCustomExceptionTranslation() { + @Test + public void customExceptionTranslation() { final String TASK = "TASK"; final String SQL = "SQL SELECT *"; final SQLErrorCodes customErrorCodes = new SQLErrorCodes(); @@ -161,13 +175,8 @@ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { assertEquals(invResEx, diex.getCause()); // Shouldn't custom translate this - invalid class - try { - customTranslation.setExceptionClass(String.class); - fail("Should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + exception.expect(IllegalArgumentException.class); + customTranslation.setExceptionClass(String.class); } } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java index dc90f75b4f..596b075ddb 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionCustomTranslatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 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,22 +18,22 @@ package org.springframework.jdbc.support; import java.sql.SQLException; -import junit.framework.TestCase; import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import org.springframework.dao.DataAccessException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + /** - * Class to test custom SQLException translation. + * Unit tests for custom SQLException translation. * * @author Thomas Risberg + * @author Sam Brannen */ -@RunWith(JUnit4.class) -public class SQLExceptionCustomTranslatorTests extends TestCase { +public class SQLExceptionCustomTranslatorTests { private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes(); @@ -43,22 +43,23 @@ public class SQLExceptionCustomTranslatorTests extends TestCase { ERROR_CODES.setCustomSqlExceptionTranslatorClass(CustomSqlExceptionTranslator.class); } + private final SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); + @Test - public void testCustomErrorCodeTranslation() { - - SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); - - SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1); - DataAccessException daeex = sext.translate("task", "SQL", dataIntegrityViolationEx); - assertEquals(dataIntegrityViolationEx, daeex.getCause()); - assertTrue(daeex instanceof BadSqlGrammarException); - - SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2); - DataAccessException darex = sext.translate("task", "SQL", dataAccessResourceEx); - assertEquals(dataIntegrityViolationEx, daeex.getCause()); - assertTrue(darex instanceof TransientDataAccessResourceException); - + public void badSqlGrammarException() { + SQLException badSqlGrammarExceptionEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1); + DataAccessException dae = sext.translate("task", "SQL", badSqlGrammarExceptionEx); + assertEquals(badSqlGrammarExceptionEx, dae.getCause()); + assertThat(dae, instanceOf(BadSqlGrammarException.class)); } -} \ No newline at end of file + @Test + public void dataAccessResourceException() { + SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2); + DataAccessException dae = sext.translate("task", "SQL", dataAccessResourceEx); + assertEquals(dataAccessResourceEx, dae.getCause()); + assertThat(dae, instanceOf(TransientDataAccessResourceException.class)); + } + +} diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java index 39f8f68a41..00f91f821e 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLExceptionSubclassTranslatorTests.java @@ -18,7 +18,7 @@ package org.springframework.jdbc.support; import java.sql.SQLException; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.dao.DataAccessResourceFailureException; @@ -30,10 +30,12 @@ import org.springframework.dao.RecoverableDataAccessException; import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.jdbc.BadSqlGrammarException; +import static org.junit.Assert.*; + /** * @author Thomas Risberg */ -public class SQLExceptionSubclassTranslatorTests extends TestCase { +public class SQLExceptionSubclassTranslatorTests { private static SQLErrorCodes ERROR_CODES = new SQLErrorCodes(); @@ -42,7 +44,8 @@ public class SQLExceptionSubclassTranslatorTests extends TestCase { } - public void testErrorCodeTranslation() { + @Test + public void errorCodeTranslation() { SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 0); diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java index 0aad57f96d..937e280f65 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java @@ -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,25 +18,27 @@ package org.springframework.jdbc.support; import java.sql.SQLException; -import junit.framework.TestCase; - +import org.junit.Test; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.UncategorizedSQLException; +import static org.junit.Assert.*; + /** - * * @author Rod Johnson * @since 13-Jan-03 */ -public class SQLStateExceptionTranslatorTests extends TestCase { +public class SQLStateExceptionTranslatorTests { - private SQLStateSQLExceptionTranslator trans = new SQLStateSQLExceptionTranslator(); + private static final String sql = "SELECT FOO FROM BAR"; + + private final SQLStateSQLExceptionTranslator trans = new SQLStateSQLExceptionTranslator(); // ALSO CHECK CHAIN of SQLExceptions!? // also allow chain of translators? default if can't do specific? - public void testBadSqlGrammar() { - String sql = "SELECT FOO FROM BAR"; + @Test + public void badSqlGrammar() { SQLException sex = new SQLException("Message", "42001", 1); try { throw this.trans.translate("task", sql, sex); @@ -48,8 +50,8 @@ public class SQLStateExceptionTranslatorTests extends TestCase { } } - public void testInvalidSqlStateCode() { - String sql = "SELECT FOO FROM BAR"; + @Test + public void invalidSqlStateCode() { SQLException sex = new SQLException("Message", "NO SUCH CODE", 1); try { throw this.trans.translate("task", sql, sex); @@ -62,11 +64,12 @@ public class SQLStateExceptionTranslatorTests extends TestCase { } /** - * PostgreSQL can return null - * SAP DB can apparently return empty SQL code + * PostgreSQL can return null. + * SAP DB can apparently return empty SQL code. * Bug 729170 */ - public void testMalformedSqlStateCodes() { + @Test + public void malformedSqlStateCodes() { SQLException sex = new SQLException("Message", null, 1); testMalformedSqlStateCode(sex); @@ -80,7 +83,6 @@ public class SQLStateExceptionTranslatorTests extends TestCase { private void testMalformedSqlStateCode(SQLException sex) { - String sql = "SELECT FOO FROM BAR"; try { throw this.trans.translate("task", sql, sex); } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java index 40fdaee4b7..cdc4f8bed7 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java @@ -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. @@ -19,35 +19,34 @@ package org.springframework.jms.listener.endpoint; import javax.jms.Destination; import javax.jms.Session; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.jca.StubResourceAdapter; import org.springframework.jms.StubQueue; import org.springframework.jms.support.destination.DestinationResolver; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Agim Emruli * @author Juergen Hoeller */ -public class DefaultJmsActivationSpecFactoryTests extends TestCase { +public class DefaultJmsActivationSpecFactoryTests { - private JmsActivationSpecConfig activationSpecConfig; + private final JmsActivationSpecConfig activationSpecConfig = new JmsActivationSpecConfig() {{ + setMaxConcurrency(5); + setPrefetchSize(3); + setAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); + setClientId("clientid"); + setDestinationName("destinationname"); + setDurableSubscriptionName("durableSubscriptionName"); + setMessageSelector("selector"); + }}; - @Override - protected void setUp() throws Exception { - activationSpecConfig = new JmsActivationSpecConfig(); - activationSpecConfig.setMaxConcurrency(5); - activationSpecConfig.setPrefetchSize(3); - activationSpecConfig.setAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - activationSpecConfig.setClientId("clientid"); - activationSpecConfig.setDestinationName("destinationname"); - activationSpecConfig.setDurableSubscriptionName("durableSubscriptionName"); - activationSpecConfig.setMessageSelector("selector"); - } - public void testActiveMQResourceAdapterSetup() { + @Test + public void activeMQResourceAdapterSetup() { activationSpecConfig.setAcknowledgeMode(Session.SESSION_TRANSACTED); JmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory(); StubActiveMQActivationSpec spec = (StubActiveMQActivationSpec) activationSpecFactory.createActivationSpec( @@ -58,7 +57,8 @@ public class DefaultJmsActivationSpecFactoryTests extends TestCase { assertTrue(spec.isUseRAManagedTransaction()); } - public void testWebSphereResourceAdapterSetup() throws Exception { + @Test + public void webSphereResourceAdapterSetup() throws Exception { Destination destination = new StubQueue(); DestinationResolver destinationResolver = mock(DestinationResolver.class); diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java index aba6c9dee7..07e1359097 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java @@ -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,43 +24,48 @@ import javax.jms.Session; import javax.jms.Topic; import javax.jms.TopicSession; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.jms.StubQueue; import org.springframework.jms.StubTopic; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Rick Evans */ -public class DynamicDestinationResolverTests extends TestCase { +public class DynamicDestinationResolverTests { private static final String DESTINATION_NAME = "foo"; - public void testResolveWithPubSubTopicSession() throws Exception { + @Test + public void resolveWithPubSubTopicSession() throws Exception { Topic expectedDestination = new StubTopic(); TopicSession session = mock(TopicSession.class); given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, true); } - public void testResolveWithPubSubVanillaSession() throws Exception { + @Test + public void resolveWithPubSubVanillaSession() throws Exception { Topic expectedDestination = new StubTopic(); Session session = mock(Session.class); given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, true); } - public void testResolveWithPointToPointQueueSession() throws Exception { + @Test + public void resolveWithPointToPointQueueSession() throws Exception { Queue expectedDestination = new StubQueue(); Session session = mock(QueueSession.class); given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, false); } - public void testResolveWithPointToPointVanillaSession() throws Exception { + @Test + public void resolveWithPointToPointVanillaSession() throws Exception { Queue expectedDestination = new StubQueue(); Session session = mock(Session.class); given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/ScopedBeanInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/ScopedBeanInterceptorTests.java index 0c1a0ed1cd..8e901ad911 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/ScopedBeanInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/ScopedBeanInterceptorTests.java @@ -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,18 +16,24 @@ package org.springframework.orm.hibernate3.support; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.scope.ScopedObject; +import static org.junit.Assert.*; + /** + * Unit tests for {@link ScopedBeanInterceptor}. + * * @author Costin Leau */ -public class ScopedBeanInterceptorTests extends TestCase { +public class ScopedBeanInterceptorTests { - public void testInterceptorWithPlainObject() throws Exception { - ScopedBeanInterceptor interceptor = new ScopedBeanInterceptor(); + private final ScopedBeanInterceptor interceptor = new ScopedBeanInterceptor(); + + @Test + public void interceptorWithPlainObject() throws Exception { final Object realObject = new Object(); ScopedObject scoped = new ScopedObject() { @@ -42,12 +48,12 @@ public class ScopedBeanInterceptorTests extends TestCase { }; // default contract is to return null for default behavior - assertEquals(null, interceptor.getEntityName(realObject)); + assertNull(interceptor.getEntityName(realObject)); assertEquals(realObject.getClass().getName(), interceptor.getEntityName(scoped)); } - public void testInterceptorWithCglibProxy() throws Exception { - ScopedBeanInterceptor interceptor = new ScopedBeanInterceptor(); + @Test + public void interceptorWithCglibProxy() throws Exception { final Object realObject = new Object(); ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(realObject); diff --git a/spring-orm/src/test/java/org/springframework/test/annotation/AbstractAnnotationAwareTransactionalTests.java b/spring-orm/src/test/java/org/springframework/test/AbstractAnnotationAwareTransactionalTests.java similarity index 97% rename from spring-orm/src/test/java/org/springframework/test/annotation/AbstractAnnotationAwareTransactionalTests.java rename to spring-orm/src/test/java/org/springframework/test/AbstractAnnotationAwareTransactionalTests.java index 4824c5136d..836106a7e2 100644 --- a/spring-orm/src/test/java/org/springframework/test/annotation/AbstractAnnotationAwareTransactionalTests.java +++ b/spring-orm/src/test/java/org/springframework/test/AbstractAnnotationAwareTransactionalTests.java @@ -14,12 +14,11 @@ * limitations under the License. */ -package org.springframework.test.annotation; +package org.springframework.test; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionAttributeSource; diff --git a/spring-orm/src/test/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java b/spring-orm/src/test/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java index 5137c64b42..818d91bd6b 100644 --- a/spring-orm/src/test/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java +++ b/spring-orm/src/test/java/org/springframework/test/AbstractDependencyInjectionSpringContextTests.java @@ -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. @@ -212,8 +212,8 @@ public abstract class AbstractDependencyInjectionSpringContextTests extends Abst } private void initManagedVariableNames() throws IllegalAccessException { - List managedVarNames = new LinkedList(); - Class clazz = getClass(); + List managedVarNames = new LinkedList<>(); + Class clazz = getClass(); do { Field[] fields = clazz.getDeclaredFields(); if (this.logger.isDebugEnabled()) { @@ -243,7 +243,7 @@ public abstract class AbstractDependencyInjectionSpringContextTests extends Abst clazz = clazz.getSuperclass(); } while (!clazz.equals(AbstractDependencyInjectionSpringContextTests.class)); - this.managedVariableNames = (String[]) managedVarNames.toArray(new String[managedVarNames.size()]); + this.managedVariableNames = managedVarNames.toArray(new String[managedVarNames.size()]); } private boolean isProtectedInstanceField(Field field) { @@ -277,12 +277,12 @@ public abstract class AbstractDependencyInjectionSpringContextTests extends Abst } } - private Field findField(Class clazz, String name) throws NoSuchFieldException { + private Field findField(Class clazz, String name) throws NoSuchFieldException { try { return clazz.getDeclaredField(name); } catch (NoSuchFieldException ex) { - Class superclass = clazz.getSuperclass(); + Class superclass = clazz.getSuperclass(); if (superclass != AbstractSpringContextTests.class) { return findField(superclass, name); } diff --git a/spring-orm/src/test/java/org/springframework/test/AbstractSingleSpringContextTests.java b/spring-orm/src/test/java/org/springframework/test/AbstractSingleSpringContextTests.java index 4c3ea02e11..2e584ad486 100644 --- a/spring-orm/src/test/java/org/springframework/test/AbstractSingleSpringContextTests.java +++ b/spring-orm/src/test/java/org/springframework/test/AbstractSingleSpringContextTests.java @@ -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. @@ -71,7 +71,7 @@ import org.springframework.util.StringUtils; * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ @Deprecated -public abstract class AbstractSingleSpringContextTests extends AbstractSpringContextTests { +abstract class AbstractSingleSpringContextTests extends AbstractSpringContextTests { /** Application context this test will run against */ protected ConfigurableApplicationContext applicationContext; diff --git a/spring-orm/src/test/java/org/springframework/test/AbstractSpringContextTests.java b/spring-orm/src/test/java/org/springframework/test/AbstractSpringContextTests.java index bbb0dd2693..c05abf6a7c 100644 --- a/spring-orm/src/test/java/org/springframework/test/AbstractSpringContextTests.java +++ b/spring-orm/src/test/java/org/springframework/test/AbstractSpringContextTests.java @@ -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. @@ -19,6 +19,11 @@ package org.springframework.test; import java.util.HashMap; import java.util.Map; +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + import org.springframework.context.ConfigurableApplicationContext; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; @@ -54,6 +59,7 @@ import org.springframework.util.StringUtils; * @author Juergen Hoeller * @author Sam Brannen * @since 1.1.1 + * @see #isDisabledInThisEnvironment * @see AbstractSingleSpringContextTests * @see AbstractDependencyInjectionSpringContextTests * @see AbstractTransactionalSpringContextTests @@ -62,7 +68,10 @@ import org.springframework.util.StringUtils; * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ @Deprecated -public abstract class AbstractSpringContextTests extends ConditionalTestCase { +abstract class AbstractSpringContextTests extends TestCase { + + /** Logger available to subclasses */ + protected final Log logger = LogFactory.getLog(getClass()); /** * Map of context keys returned by subclasses of this class, to Spring @@ -72,6 +81,14 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { private static Map contextKeyToContextMap = new HashMap(); + private static int disabledTestCount; + + /** + * Return the number of tests disabled in this environment. + */ + public static int getDisabledTestCount() { + return disabledTestCount; + } /** * Default constructor for AbstractSpringContextTests. @@ -86,6 +103,39 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase { super(name); } + @Override + public void runBare() throws Throwable { + // getName will return the name of the method being run + if (isDisabledInThisEnvironment(getName())) { + recordDisabled(); + this.logger.info("**** " + getClass().getName() + "." + getName() + + " is disabled in this environment: " + "Total disabled tests = " + + getDisabledTestCount()); + return; + } + + // Let JUnit handle execution + super.runBare(); + } + + /** + * Should this test run? + * + * @param testMethodName name of the test method + * @return whether the test should execute in the current environment + */ + protected boolean isDisabledInThisEnvironment(String testMethodName) { + return false; + } + + /** + * Record a disabled test. + * + * @return the current disabled test count + */ + protected int recordDisabled() { + return ++disabledTestCount; + } /** * Explicitly add an ApplicationContext instance under a given key. diff --git a/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java b/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java index e0eb638ec1..0fa933178c 100644 --- a/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java +++ b/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalDataSourceSpringContextTests.java @@ -43,7 +43,7 @@ import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ @Deprecated -public abstract class AbstractTransactionalDataSourceSpringContextTests extends AbstractTransactionalSpringContextTests { +abstract class AbstractTransactionalDataSourceSpringContextTests extends AbstractTransactionalSpringContextTests { protected JdbcTemplate jdbcTemplate; diff --git a/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalSpringContextTests.java b/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalSpringContextTests.java index 9759601d88..d8862aa697 100644 --- a/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalSpringContextTests.java +++ b/spring-orm/src/test/java/org/springframework/test/AbstractTransactionalSpringContextTests.java @@ -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. @@ -83,7 +83,7 @@ import org.springframework.transaction.support.DefaultTransactionDefinition; * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) */ @Deprecated -public abstract class AbstractTransactionalSpringContextTests extends AbstractDependencyInjectionSpringContextTests { +abstract class AbstractTransactionalSpringContextTests extends AbstractDependencyInjectionSpringContextTests { /** The transaction manager to use */ protected PlatformTransactionManager transactionManager; diff --git a/spring-orm/src/test/java/org/springframework/test/ConditionalTestCase.java b/spring-orm/src/test/java/org/springframework/test/ConditionalTestCase.java deleted file mode 100644 index 50e6553d4a..0000000000 --- a/spring-orm/src/test/java/org/springframework/test/ConditionalTestCase.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2002-2014 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. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.test; - -import junit.framework.TestCase; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * This class is only used within tests in the spring-orm module. - * - *

Superclass for JUnit 3.8 based tests that allows conditional test execution - * at the individual test method level. The - * {@link #isDisabledInThisEnvironment(String) isDisabledInThisEnvironment()} - * method is invoked before the execution of each test method. Subclasses can - * override that method to return whether or not the given test should be - * executed. Note that the tests will still appear to have executed and passed; - * however, log output will show that the test was not executed. - * - * @author Rod Johnson - * @since 2.0 - * @see #isDisabledInThisEnvironment - * @deprecated as of Spring 3.0, in favor of using the listener-based test context framework - * ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests}) - */ -@Deprecated -public abstract class ConditionalTestCase extends TestCase { - - private static int disabledTestCount; - - - /** - * Return the number of tests disabled in this environment. - */ - public static int getDisabledTestCount() { - return disabledTestCount; - } - - - /** Logger available to subclasses */ - protected final Log logger = LogFactory.getLog(getClass()); - - - /** - * Default constructor for ConditionalTestCase. - */ - public ConditionalTestCase() { - } - - /** - * Constructor for ConditionalTestCase with a JUnit name. - */ - public ConditionalTestCase(String name) { - super(name); - } - - @Override - public void runBare() throws Throwable { - // getName will return the name of the method being run - if (isDisabledInThisEnvironment(getName())) { - recordDisabled(); - this.logger.info("**** " + getClass().getName() + "." + getName() + " is disabled in this environment: " - + "Total disabled tests = " + getDisabledTestCount()); - return; - } - - // Let JUnit handle execution - super.runBare(); - } - - /** - * Should this test run? - * @param testMethodName name of the test method - * @return whether the test should execute in the current environment - */ - protected boolean isDisabledInThisEnvironment(String testMethodName) { - return false; - } - - /** - * Record a disabled test. - * @return the current disabled test count - */ - protected int recordDisabled() { - return ++disabledTestCount; - } - -} diff --git a/spring-orm/src/test/java/org/springframework/test/jpa/AbstractJpaTests.java b/spring-orm/src/test/java/org/springframework/test/jpa/AbstractJpaTests.java index 17b57cce86..a8a6375b10 100644 --- a/spring-orm/src/test/java/org/springframework/test/jpa/AbstractJpaTests.java +++ b/spring-orm/src/test/java/org/springframework/test/jpa/AbstractJpaTests.java @@ -23,6 +23,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -45,7 +46,8 @@ import org.springframework.orm.jpa.ExtendedEntityManagerCreator; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.SharedEntityManagerCreator; import org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager; -import org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests; +import org.springframework.test.AbstractAnnotationAwareTransactionalTests; +import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; /** @@ -261,6 +263,7 @@ public abstract class AbstractJpaTests extends AbstractAnnotationAwareTransactio /* AbstractSpringContextTests.addContext(Object, ApplicationContext) */ Class applicationContextClass = shadowingClassLoader.loadClass(ConfigurableApplicationContext.class.getName()); Method addContextMethod = shadowedTestClass.getMethod("addContext", Object.class, applicationContextClass); + ReflectionUtils.makeAccessible(addContextMethod); addContextMethod.invoke(shadowedTestCase, configLocations, cachedContext); // Invoke tests on shadowed test case diff --git a/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java index 3923771080..9a01163f82 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/AbstractMarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 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,6 +18,7 @@ package org.springframework.oxm; import java.io.ByteArrayOutputStream; import java.io.StringWriter; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLEventWriter; @@ -29,8 +30,10 @@ import javax.xml.transform.stax.StAXResult; import javax.xml.transform.stream.StreamResult; import org.custommonkey.xmlunit.XMLUnit; + import org.junit.Before; import org.junit.Test; + import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -43,17 +46,18 @@ import static org.junit.Assert.assertTrue; /** * @author Arjen Poutsma + * @author Sam Brannen */ -public abstract class AbstractMarshallerTests { - - protected Marshaller marshaller; - - protected Object flights; +public abstract class AbstractMarshallerTests { protected static final String EXPECTED_STRING = "" + "42"; + protected M marshaller; + + protected Object flights; + @Before public final void setUp() throws Exception { marshaller = createMarshaller(); @@ -61,7 +65,7 @@ public abstract class AbstractMarshallerTests { XMLUnit.setIgnoreWhitespace(true); } - protected abstract Marshaller createMarshaller() throws Exception; + protected abstract M createMarshaller() throws Exception; protected abstract Object createFlights(); @@ -168,4 +172,5 @@ public abstract class AbstractMarshallerTests { marshaller.marshal(flights, result); assertXMLEqual("Marshaller writes invalid StreamResult", EXPECTED_STRING, writer.toString()); } + } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java index 759a58ce9f..1bafa7984d 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/AbstractUnmarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 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. @@ -45,10 +45,11 @@ import static org.junit.Assert.*; /** * @author Arjen Poutsma + * @author Sam Brannen */ -public abstract class AbstractUnmarshallerTests { +public abstract class AbstractUnmarshallerTests { - protected Unmarshaller unmarshaller; + protected U unmarshaller; protected static final String INPUT_STRING = "" + @@ -59,7 +60,7 @@ public abstract class AbstractUnmarshallerTests { unmarshaller = createUnmarshaller(); } - protected abstract Unmarshaller createUnmarshaller() throws Exception; + protected abstract U createUnmarshaller() throws Exception; protected abstract void testFlights(Object o); @@ -154,4 +155,5 @@ public abstract class AbstractUnmarshallerTests { Object flight = unmarshaller.unmarshal(source); testFlight(flight); } + } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java index 322e1ed488..423fec4de6 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorMarshallerTests.java @@ -20,6 +20,7 @@ import java.io.StringWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; + import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamResult; @@ -27,16 +28,19 @@ import org.custommonkey.xmlunit.NamespaceContext; import org.custommonkey.xmlunit.SimpleNamespaceContext; import org.custommonkey.xmlunit.XMLUnit; import org.custommonkey.xmlunit.XpathEngine; + import org.junit.Test; + import org.mockito.InOrder; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; import org.springframework.core.io.ClassPathResource; import org.springframework.oxm.AbstractMarshallerTests; -import org.springframework.oxm.Marshaller; + +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; + +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; import static org.custommonkey.xmlunit.XMLAssert.*; import static org.junit.Assert.assertEquals; @@ -49,8 +53,9 @@ import static org.mockito.Mockito.*; * * @author Arjen Poutsma * @author Jakub Narloch + * @author Sam Brannen */ -public class CastorMarshallerTests extends AbstractMarshallerTests { +public class CastorMarshallerTests extends AbstractMarshallerTests { /** * Represents the expected result that doesn't contain the xml declaration. @@ -108,7 +113,7 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { @Override - protected Marshaller createMarshaller() throws Exception { + protected CastorMarshaller createMarshaller() throws Exception { CastorMarshaller marshaller = new CastorMarshaller(); ClassPathResource mappingLocation = new ClassPathResource("mapping.xml", CastorMarshaller.class); marshaller.setMappingLocation(mappingLocation); @@ -155,40 +160,40 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { } @Test - public void testSuppressNamespacesTrue() throws Exception { - getCastorMarshaller().setSuppressNamespaces(true); + public void suppressNamespacesTrue() throws Exception { + marshaller.setSuppressNamespaces(true); String result = marshalFlights(); assertXMLEqual("Marshaller wrote invalid result", SUPPRESSED_NAMESPACE_EXPECTED_STRING, result); } @Test - public void testSuppressNamespacesFalse() throws Exception { - getCastorMarshaller().setSuppressNamespaces(false); + public void suppressNamespacesFalse() throws Exception { + marshaller.setSuppressNamespaces(false); String result = marshalFlights(); assertXMLEqual("Marshaller wrote invalid result", EXPECTED_STRING, result); } @Test - public void testSuppressXsiTypeTrue() throws Exception { + public void suppressXsiTypeTrue() throws Exception { CastorObject castorObject = createCastorObject(); - getCastorMarshaller().setSuppressXsiType(true); - getCastorMarshaller().setRootElement("objects"); + marshaller.setSuppressXsiType(true); + marshaller.setRootElement("objects"); String result = marshal(Arrays.asList(castorObject)); assertXMLEqual("Marshaller wrote invalid result", SUPPRESSED_XSI_EXPECTED_STRING, result); } @Test - public void testSuppressXsiTypeFalse() throws Exception { + public void suppressXsiTypeFalse() throws Exception { CastorObject castorObject = createCastorObject(); - getCastorMarshaller().setSuppressXsiType(false); - getCastorMarshaller().setRootElement("objects"); + marshaller.setSuppressXsiType(false); + marshaller.setRootElement("objects"); String result = marshal(Arrays.asList(castorObject)); assertXMLEqual("Marshaller wrote invalid result", XSI_EXPECTED_STRING, result); } @Test - public void testMarshalAsDocumentTrue() throws Exception { - getCastorMarshaller().setMarshalAsDocument(true); + public void marshalAsDocumentTrue() throws Exception { + marshaller.setMarshalAsDocument(true); String result = marshalFlights(); assertXMLEqual("Marshaller wrote invalid result", DOCUMENT_EXPECTED_STRING, result); assertTrue("Result doesn't contain xml declaration.", @@ -196,24 +201,24 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { } @Test - public void testMarshalAsDocumentFalse() throws Exception { - getCastorMarshaller().setMarshalAsDocument(true); + public void marshalAsDocumentFalse() throws Exception { + marshaller.setMarshalAsDocument(true); String result = marshalFlights(); assertXMLEqual("Marshaller wrote invalid result", EXPECTED_STRING, result); assertFalse("Result contains xml declaration.", result.matches("<\\?\\s*xml")); } @Test - public void testRootElement() throws Exception { - getCastorMarshaller().setRootElement("canceledFlights"); + public void rootElement() throws Exception { + marshaller.setRootElement("canceledFlights"); String result = marshalFlights(); assertXMLEqual("Marshaller wrote invalid result", ROOT_ELEMENT_EXPECTED_STRING, result); } @Test - public void testNoNamespaceSchemaLocation() throws Exception { + public void noNamespaceSchemaLocation() throws Exception { String noNamespaceSchemaLocation = "flights.xsd"; - getCastorMarshaller().setNoNamespaceSchemaLocation(noNamespaceSchemaLocation); + marshaller.setNoNamespaceSchemaLocation(noNamespaceSchemaLocation); String result = marshalFlights(); assertXpathEvaluatesTo("The xsi:noNamespaceSchemaLocation hasn't been written or has invalid value.", noNamespaceSchemaLocation, "/tns:flights/@xsi:noNamespaceSchemaLocation", result); @@ -221,9 +226,9 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { } @Test - public void testSchemaLocation() throws Exception { + public void schemaLocation() throws Exception { String schemaLocation = "flights.xsd"; - getCastorMarshaller().setSchemaLocation(schemaLocation); + marshaller.setSchemaLocation(schemaLocation); String result = marshalFlights(); assertXpathEvaluatesTo("The xsi:noNamespaceSchemaLocation hasn't been written or has invalid value.", schemaLocation, "/tns:flights/@xsi:schemaLocation", result); @@ -231,34 +236,30 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { } @Test - public void testUseXsiTypeAsRootTrue() throws Exception { + public void useXsiTypeAsRootTrue() throws Exception { CastorObject castorObject = createCastorObject(); - getCastorMarshaller().setSuppressXsiType(false); - getCastorMarshaller().setUseXSITypeAtRoot(true); - getCastorMarshaller().setRootElement("objects"); + marshaller.setSuppressXsiType(false); + marshaller.setUseXSITypeAtRoot(true); + marshaller.setRootElement("objects"); String result = marshal(Arrays.asList(castorObject)); assertXMLEqual("Marshaller wrote invalid result", ROOT_WITH_XSI_EXPECTED_STRING, result); } @Test - public void testUseXsiTypeAsRootFalse() throws Exception { + public void useXsiTypeAsRootFalse() throws Exception { CastorObject castorObject = createCastorObject(); - getCastorMarshaller().setSuppressXsiType(false); - getCastorMarshaller().setUseXSITypeAtRoot(false); - getCastorMarshaller().setRootElement("objects"); + marshaller.setSuppressXsiType(false); + marshaller.setUseXSITypeAtRoot(false); + marshaller.setRootElement("objects"); String result = marshal(Arrays.asList(castorObject)); assertXMLEqual("Marshaller wrote invalid result", ROOT_WITHOUT_XSI_EXPECTED_STRING, result); } - private CastorMarshaller getCastorMarshaller() { - return (CastorMarshaller) marshaller; - } - private String marshal(Object object) throws Exception { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); - getCastorMarshaller().marshal(object, result); + marshaller.marshal(object, result); return writer.toString(); } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java index 21af88849b..f3b2a0f5d6 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java @@ -25,13 +25,13 @@ import javax.xml.transform.stream.StreamSource; import org.junit.Ignore; import org.junit.Test; -import org.xml.sax.InputSource; -import org.xml.sax.XMLReader; import org.springframework.core.io.ClassPathResource; import org.springframework.oxm.AbstractUnmarshallerTests; import org.springframework.oxm.MarshallingException; -import org.springframework.oxm.Unmarshaller; + +import org.xml.sax.InputSource; +import org.xml.sax.XMLReader; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; @@ -39,8 +39,9 @@ import static org.junit.Assert.*; /** * @author Arjen Poutsma * @author Jakub Narloch + * @author Sam Brannen */ -public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { +public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { /** * Represents the xml with additional attribute that is not mapped in Castor config. @@ -58,6 +59,15 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { ""; + @Override + protected CastorMarshaller createUnmarshaller() throws Exception { + CastorMarshaller marshaller = new CastorMarshaller(); + ClassPathResource mappingLocation = new ClassPathResource("mapping.xml", CastorMarshaller.class); + marshaller.setMappingLocation(mappingLocation); + marshaller.afterPropertiesSet(); + return marshaller; + } + @Override protected void testFlights(Object o) { Flights flights = (Flights) o; @@ -73,15 +83,6 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { assertThat("Number is invalid", flight.getNumber(), equalTo(42L)); } - @Override - protected Unmarshaller createUnmarshaller() throws Exception { - CastorMarshaller marshaller = new CastorMarshaller(); - ClassPathResource mappingLocation = new ClassPathResource("mapping.xml", CastorMarshaller.class); - marshaller.setMappingLocation(mappingLocation); - marshaller.afterPropertiesSet(); - return marshaller; - } - @Test public void unmarshalTargetClass() throws Exception { @@ -94,7 +95,7 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { } @Test - public void testSetBothTargetClassesAndMapping() throws IOException { + public void setBothTargetClassesAndMapping() throws IOException { CastorMarshaller unmarshaller = new CastorMarshaller(); unmarshaller.setMappingLocation(new ClassPathResource("order-mapping.xml", CastorMarshaller.class)); unmarshaller.setTargetClasses(new Class[] {Order.class}); @@ -116,62 +117,62 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { } @Test - public void testWhitespacePreserveTrue() throws Exception { - getCastorUnmarshaller().setWhitespacePreserve(true); + public void whitespacePreserveTrue() throws Exception { + unmarshaller.setWhitespacePreserve(true); Object result = unmarshalFlights(); testFlights(result); } @Test - public void testWhitespacePreserveFalse() throws Exception { - getCastorUnmarshaller().setWhitespacePreserve(false); + public void whitespacePreserveFalse() throws Exception { + unmarshaller.setWhitespacePreserve(false); Object result = unmarshalFlights(); testFlights(result); } @Test - public void testIgnoreExtraAttributesTrue() throws Exception { - getCastorUnmarshaller().setIgnoreExtraAttributes(true); + public void ignoreExtraAttributesTrue() throws Exception { + unmarshaller.setIgnoreExtraAttributes(true); Object result = unmarshal(EXTRA_ATTRIBUTES_STRING); testFlights(result); } @Test(expected = MarshallingException.class) - public void testIgnoreExtraAttributesFalse() throws Exception { - getCastorUnmarshaller().setIgnoreExtraAttributes(false); + public void ignoreExtraAttributesFalse() throws Exception { + unmarshaller.setIgnoreExtraAttributes(false); unmarshal(EXTRA_ATTRIBUTES_STRING); } @Test @Ignore("Not working yet") - public void testIgnoreExtraElementsTrue() throws Exception { - getCastorUnmarshaller().setIgnoreExtraElements(true); - getCastorUnmarshaller().setValidating(false); + public void ignoreExtraElementsTrue() throws Exception { + unmarshaller.setIgnoreExtraElements(true); + unmarshaller.setValidating(false); Object result = unmarshal(EXTRA_ELEMENTS_STRING); testFlights(result); } @Test(expected = MarshallingException.class) - public void testIgnoreExtraElementsFalse() throws Exception { - getCastorUnmarshaller().setIgnoreExtraElements(false); + public void ignoreExtraElementsFalse() throws Exception { + unmarshaller.setIgnoreExtraElements(false); unmarshal(EXTRA_ELEMENTS_STRING); } @Test - public void testRootObject() throws Exception { + public void rootObject() throws Exception { Flights flights = new Flights(); - getCastorUnmarshaller().setRootObject(flights); + unmarshaller.setRootObject(flights); Object result = unmarshalFlights(); testFlights(result); assertSame("Result Flights is different object.", flights, result); } @Test - public void testClearCollectionsTrue() throws Exception { + public void clearCollectionsTrue() throws Exception { Flights flights = new Flights(); flights.setFlight(new Flight[]{new Flight()}); - getCastorUnmarshaller().setRootObject(flights); - getCastorUnmarshaller().setClearCollections(true); + unmarshaller.setRootObject(flights); + unmarshaller.setClearCollections(true); Object result = unmarshalFlights(); assertSame("Result Flights is different object.", flights, result); @@ -181,11 +182,11 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { @Test @Ignore("Fails on the build server for some reason") - public void testClearCollectionsFalse() throws Exception { + public void clearCollectionsFalse() throws Exception { Flights flights = new Flights(); flights.setFlight(new Flight[] {new Flight(), null}); - getCastorUnmarshaller().setRootObject(flights); - getCastorUnmarshaller().setClearCollections(false); + unmarshaller.setRootObject(flights); + unmarshaller.setClearCollections(false); Object result = unmarshalFlights(); assertSame("Result Flights is different object.", flights, result); @@ -249,11 +250,6 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { assertEquals(true, result.get().getFeature("http://xml.org/sax/features/external-general-entities")); } - - private CastorMarshaller getCastorUnmarshaller() { - return (CastorMarshaller) unmarshaller; - } - private Object unmarshalFlights() throws Exception { return unmarshal(INPUT_STRING); } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java index 38f0387679..9595d8087e 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/config/OxmNamespaceHandlerTests.java @@ -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. @@ -17,14 +17,13 @@ package org.springframework.oxm.config; import org.apache.xmlbeans.XmlOptions; -import org.junit.Before; + import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.oxm.castor.CastorMarshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; -import org.springframework.oxm.xmlbeans.XmlBeansMarshaller; import static org.junit.Assert.*; @@ -33,19 +32,18 @@ import static org.junit.Assert.*; * * @author Arjen Poustma * @author Jakub Narloch + * @author Sam Brannen */ +@SuppressWarnings("deprecation") public class OxmNamespaceHandlerTests { - private ApplicationContext applicationContext; - - @Before - public void createAppContext() throws Exception { - applicationContext = new ClassPathXmlApplicationContext("oxmNamespaceHandlerTest.xml", getClass()); - } + private final ApplicationContext applicationContext = new ClassPathXmlApplicationContext( + "oxmNamespaceHandlerTest.xml", getClass()); @Test public void xmlBeansMarshaller() throws Exception { - XmlBeansMarshaller marshaller = applicationContext.getBean("xmlBeansMarshaller", XmlBeansMarshaller.class); + org.springframework.oxm.xmlbeans.XmlBeansMarshaller marshaller = applicationContext.getBean( + org.springframework.oxm.xmlbeans.XmlBeansMarshaller.class); XmlOptions options = marshaller.getXmlOptions(); assertNotNull("Options not set", options); assertTrue("option not set", options.hasOption("SAVE_PRETTY_PRINT")); diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java index 8ccf65b910..68f2978956 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java @@ -35,8 +35,10 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.junit.Test; + import org.mockito.ArgumentCaptor; import org.mockito.InOrder; + import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; @@ -45,7 +47,6 @@ import org.xml.sax.Locator; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.oxm.AbstractMarshallerTests; -import org.springframework.oxm.Marshaller; import org.springframework.oxm.UncategorizedMappingException; import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.jaxb.test.FlightType; @@ -65,19 +66,18 @@ import static org.mockito.BDDMockito.*; /** * @author Arjen Poutsma * @author Biju Kunjummen + * @author Sam Brannen */ -public class Jaxb2MarshallerTests extends AbstractMarshallerTests { +public class Jaxb2MarshallerTests extends AbstractMarshallerTests { private static final String CONTEXT_PATH = "org.springframework.oxm.jaxb.test"; - private Jaxb2Marshaller marshaller; - private Flights flights; @Override - public Marshaller createMarshaller() throws Exception { - marshaller = new Jaxb2Marshaller(); + protected Jaxb2Marshaller createMarshaller() throws Exception { + Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath(CONTEXT_PATH); marshaller.afterPropertiesSet(); return marshaller; @@ -389,7 +389,6 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests { public static class DummyRootElement { private DummyType t = new DummyType(); - } @XmlType @@ -397,7 +396,6 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests { public static class DummyType { private String s = "Hello"; - } @SuppressWarnings("unused") diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java index ed7e8725e4..c65b622bdc 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2UnmarshallerTests.java @@ -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,6 +19,7 @@ package org.springframework.oxm.jaxb; import java.io.File; import java.io.IOException; import java.io.StringReader; + import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.xml.bind.JAXBElement; @@ -32,7 +33,6 @@ import org.junit.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.oxm.AbstractUnmarshallerTests; -import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.jaxb.test.FlightType; import org.springframework.oxm.jaxb.test.Flights; import org.springframework.oxm.mime.MimeContainer; @@ -44,23 +44,37 @@ import static org.mockito.BDDMockito.*; /** * @author Arjen Poutsma * @author Biju Kunjummen + * @author Sam Brannen */ -public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests { +public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests { private static final String INPUT_STRING = "" + "42"; - private Jaxb2Marshaller unmarshaller; - @Override - public Unmarshaller createUnmarshaller() throws Exception { - unmarshaller = new Jaxb2Marshaller(); + protected Jaxb2Marshaller createUnmarshaller() throws Exception { + Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller(); unmarshaller.setContextPath("org.springframework.oxm.jaxb.test"); unmarshaller.setSchema(new ClassPathResource("org/springframework/oxm/flight.xsd")); unmarshaller.afterPropertiesSet(); return unmarshaller; } + @Override + protected void testFlights(Object o) { + Flights flights = (Flights) o; + assertNotNull("Flights is null", flights); + assertEquals("Invalid amount of flight elements", 1, flights.getFlight().size()); + testFlight(flights.getFlight().get(0)); + } + + @Override + protected void testFlight(Object o) { + FlightType flight = (FlightType) o; + assertNotNull("Flight is null", flight); + assertEquals("Number is invalid", 42L, flight.getNumber()); + } + @Test public void marshalAttachments() throws Exception { unmarshaller = new Jaxb2Marshaller(); @@ -93,21 +107,6 @@ public class Jaxb2UnmarshallerTests extends AbstractUnmarshallerTests { assertNotNull("datahandler property not set", object.getSwaDataHandler()); } - @Override - protected void testFlights(Object o) { - Flights flights = (Flights) o; - assertNotNull("Flights is null", flights); - assertEquals("Invalid amount of flight elements", 1, flights.getFlight().size()); - testFlight(flights.getFlight().get(0)); - } - - @Override - protected void testFlight(Object o) { - FlightType flight = (FlightType) o; - assertNotNull("Flight is null", flight); - assertEquals("Number is invalid", 42L, flight.getNumber()); - } - @Test @Override @SuppressWarnings("unchecked") diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java index 87b5c9914b..3102f11fde 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxMarshallerTests.java @@ -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,11 +20,11 @@ import java.io.StringWriter; import javax.xml.transform.stream.StreamResult; import org.custommonkey.xmlunit.XMLUnit; + import org.junit.BeforeClass; import org.junit.Test; import org.springframework.oxm.AbstractMarshallerTests; -import org.springframework.oxm.Marshaller; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; @@ -33,12 +33,13 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** - * @author Arjen Poutsma + * NOTE: These tests fail under Eclipse/IDEA because JiBX binding does not occur by + * default. The Gradle build should succeed, however. * - * NOTE: These tests fail under Eclipse/IDEA because JiBX binding does - * not occur by default. The Gradle build should succeed, however. + * @author Arjen Poutsma + * @author Sam Brannen */ -public class JibxMarshallerTests extends AbstractMarshallerTests { +public class JibxMarshallerTests extends AbstractMarshallerTests { @BeforeClass public static void compilerAssumptions() { @@ -46,7 +47,7 @@ public class JibxMarshallerTests extends AbstractMarshallerTests { } @Override - protected Marshaller createMarshaller() throws Exception { + protected JibxMarshaller createMarshaller() throws Exception { JibxMarshaller marshaller = new JibxMarshaller(); marshaller.setTargetPackage("org.springframework.oxm.jibx"); marshaller.afterPropertiesSet(); @@ -70,7 +71,7 @@ public class JibxMarshallerTests extends AbstractMarshallerTests { @Test public void indentation() throws Exception { - ((JibxMarshaller) marshaller).setIndent(4); + marshaller.setIndent(4); StringWriter writer = new StringWriter(); marshaller.marshal(flights, new StreamResult(writer)); XMLUnit.setIgnoreWhitespace(false); @@ -82,8 +83,8 @@ public class JibxMarshallerTests extends AbstractMarshallerTests { @Test public void encodingAndStandalone() throws Exception { - ((JibxMarshaller) marshaller).setEncoding("ISO-8859-1"); - ((JibxMarshaller) marshaller).setStandalone(Boolean.TRUE); + marshaller.setEncoding("ISO-8859-1"); + marshaller.setStandalone(Boolean.TRUE); StringWriter writer = new StringWriter(); marshaller.marshal(flights, new StreamResult(writer)); assertTrue("Encoding and standalone not set", @@ -92,8 +93,8 @@ public class JibxMarshallerTests extends AbstractMarshallerTests { @Test public void dtd() throws Exception { - ((JibxMarshaller) marshaller).setDocTypeRootElementName("flights"); - ((JibxMarshaller) marshaller).setDocTypeSystemId("flights.dtd"); + marshaller.setDocTypeRootElementName("flights"); + marshaller.setDocTypeSystemId("flights.dtd"); StringWriter writer = new StringWriter(); marshaller.marshal(flights, new StreamResult(writer)); assertTrue("doc type not written", diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java index 6c80b601d4..c6e8c553d0 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jibx/JibxUnmarshallerTests.java @@ -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,24 +20,22 @@ import java.io.ByteArrayInputStream; import javax.xml.transform.stream.StreamSource; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; import org.springframework.oxm.AbstractUnmarshallerTests; -import org.springframework.oxm.Unmarshaller; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; import static org.junit.Assert.*; - /** - * @author Arjen Poutsma - * * NOTE: These tests fail under Eclipse/IDEA because JiBX binding does * not occur by default. The Gradle build should succeed, however. + * + * @author Arjen Poutsma + * @author Sam Brannen */ -public class JibxUnmarshallerTests extends AbstractUnmarshallerTests { +public class JibxUnmarshallerTests extends AbstractUnmarshallerTests { protected static final String INPUT_STRING_WITH_SPECIAL_CHARACTERS = "" + @@ -48,8 +46,9 @@ public class JibxUnmarshallerTests extends AbstractUnmarshallerTests { Assume.group(TestGroup.CUSTOM_COMPILATION); } + @Override - protected Unmarshaller createUnmarshaller() throws Exception { + protected JibxMarshaller createUnmarshaller() throws Exception { JibxMarshaller unmarshaller = new JibxMarshaller(); unmarshaller.setTargetClass(Flights.class); unmarshaller.afterPropertiesSet(); @@ -71,8 +70,8 @@ public class JibxUnmarshallerTests extends AbstractUnmarshallerTests { assertEquals("Number is invalid", 42L, flight.getNumber()); } + @Test @Override - @Ignore public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception { // JiBX does not support reading XML fragments, hence the override here } @@ -80,7 +79,7 @@ public class JibxUnmarshallerTests extends AbstractUnmarshallerTests { @Test public void unmarshalStreamSourceInputStreamUsingNonDefaultEncoding() throws Exception { String encoding = "ISO-8859-1"; - ((JibxMarshaller)unmarshaller).setEncoding(encoding); + unmarshaller.setEncoding(encoding); StreamSource source = new StreamSource(new ByteArrayInputStream(INPUT_STRING_WITH_SPECIAL_CHARACTERS.getBytes(encoding))); Object flights = unmarshaller.unmarshal(source); diff --git a/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansMarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansMarshallerTests.java index d8be8e4714..4a7507520e 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansMarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansMarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 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,10 +20,10 @@ import java.io.ByteArrayOutputStream; import javax.xml.transform.stream.StreamResult; import org.apache.xmlbeans.XmlObject; + import org.junit.Test; import org.springframework.oxm.AbstractMarshallerTests; -import org.springframework.oxm.Marshaller; import org.springframework.samples.flight.FlightType; import org.springframework.samples.flight.FlightsDocument; @@ -31,11 +31,14 @@ import static org.junit.Assert.*; /** * @author Arjen Poutsma + * @author Sam Brannen */ -public class XmlBeansMarshallerTests extends AbstractMarshallerTests { +@SuppressWarnings("deprecation") +public class XmlBeansMarshallerTests extends + AbstractMarshallerTests { @Override - protected Marshaller createMarshaller() throws Exception { + protected XmlBeansMarshaller createMarshaller() throws Exception { return new XmlBeansMarshaller(); } @@ -49,7 +52,7 @@ public class XmlBeansMarshallerTests extends AbstractMarshallerTests { } @Test(expected = ClassCastException.class) - public void testMarshalNonXmlObject() throws Exception { + public void marshalNonXmlObject() throws Exception { marshaller.marshal(new Object(), new StreamResult(new ByteArrayOutputStream())); } diff --git a/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansUnmarshallerTests.java index 6b2e8d36a6..4a6fe9215f 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/xmlbeans/XmlBeansUnmarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 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,6 +17,7 @@ package org.springframework.oxm.xmlbeans; import java.io.StringReader; + import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; @@ -26,7 +27,6 @@ import javax.xml.transform.stream.StreamSource; import org.junit.Test; import org.springframework.oxm.AbstractUnmarshallerTests; -import org.springframework.oxm.Unmarshaller; import org.springframework.oxm.ValidationFailureException; import org.springframework.samples.flight.FlightDocument; import org.springframework.samples.flight.FlightType; @@ -38,10 +38,12 @@ import static org.junit.Assert.*; /** * @author Arjen Poutsma */ -public class XmlBeansUnmarshallerTests extends AbstractUnmarshallerTests { +@SuppressWarnings("deprecation") +public class XmlBeansUnmarshallerTests extends + AbstractUnmarshallerTests { @Override - protected Unmarshaller createUnmarshaller() throws Exception { + protected XmlBeansMarshaller createUnmarshaller() throws Exception { return new XmlBeansMarshaller(); } @@ -68,6 +70,7 @@ public class XmlBeansUnmarshallerTests extends AbstractUnmarshallerTests { assertEquals("Number is invalid", 42L, flight.getNumber()); } + @Test @Override public void unmarshalPartialStaxSourceXmlStreamReader() throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); @@ -84,8 +87,8 @@ public class XmlBeansUnmarshallerTests extends AbstractUnmarshallerTests { } @Test(expected = ValidationFailureException.class) - public void testValidate() throws Exception { - ((XmlBeansMarshaller) unmarshaller).setValidating(true); + public void validate() throws Exception { + unmarshaller.setValidating(true); String invalidInput = "" + "abc"; unmarshaller.unmarshal(new StreamSource(new StringReader(invalidInput))); diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java index d44642a159..6fff9cd2b3 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockPageContextTests.java @@ -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,20 +18,25 @@ package org.springframework.mock.web; import javax.servlet.jsp.PageContext; -import junit.framework.TestCase; +import org.junit.Test; + +import static org.junit.Assert.*; /** * Unit tests for the {@code MockPageContext} class. * * @author Rick Evans */ -public final class MockPageContextTests extends TestCase { +public class MockPageContextTests { - public void testSetAttributeWithNoScopeUsesPageScope() throws Exception { - String key = "foo"; - String value = "bar"; + private final String key = "foo"; - MockPageContext ctx = new MockPageContext(); + private final String value = "bar"; + + private final MockPageContext ctx = new MockPageContext(); + + @Test + public void setAttributeWithNoScopeUsesPageScope() throws Exception { ctx.setAttribute(key, value); assertEquals(value, ctx.getAttribute(key, PageContext.PAGE_SCOPE)); assertNull(ctx.getAttribute(key, PageContext.APPLICATION_SCOPE)); @@ -39,11 +44,8 @@ public final class MockPageContextTests extends TestCase { assertNull(ctx.getAttribute(key, PageContext.SESSION_SCOPE)); } - public void testRemoveAttributeWithNoScopeSpecifiedRemovesValueFromAllScopes() throws Exception { - String key = "foo"; - String value = "bar"; - - MockPageContext ctx = new MockPageContext(); + @Test + public void removeAttributeWithNoScopeSpecifiedRemovesValueFromAllScopes() throws Exception { ctx.setAttribute(key, value, PageContext.APPLICATION_SCOPE); ctx.removeAttribute(key); diff --git a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java index a8e4fb544e..b383a32faf 100644 --- a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationAdvisorTests.java @@ -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. @@ -22,7 +22,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.persistence.PersistenceException; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.dao.DataAccessException; @@ -31,6 +31,8 @@ import org.springframework.dao.support.DataAccessUtilsTests.MapPersistenceExcept import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.stereotype.Repository; +import static org.junit.Assert.*; + /** * Tests for PersistenceExceptionTranslationAdvisor's exception translation, as applied by * PersistenceExceptionTranslationPostProcessor. @@ -38,7 +40,7 @@ import org.springframework.stereotype.Repository; * @author Rod Johnson * @author Juergen Hoeller */ -public class PersistenceExceptionTranslationAdvisorTests extends TestCase { +public class PersistenceExceptionTranslationAdvisorTests { private RuntimeException doNotTranslate = new RuntimeException(); @@ -57,7 +59,8 @@ public class PersistenceExceptionTranslationAdvisorTests extends TestCase { pf.addAdvisor(new PersistenceExceptionTranslationAdvisor(pet, Repository.class)); } - public void testNoTranslationNeeded() { + @Test + public void noTranslationNeeded() { RepositoryInterfaceImpl target = new RepositoryInterfaceImpl(); RepositoryInterface ri = createProxy(target); @@ -81,7 +84,8 @@ public class PersistenceExceptionTranslationAdvisorTests extends TestCase { } } - public void testTranslationNotNeededForTheseExceptions() { + @Test + public void translationNotNeededForTheseExceptions() { RepositoryInterfaceImpl target = new StereotypedRepositoryInterfaceImpl(); RepositoryInterface ri = createProxy(target); @@ -105,23 +109,28 @@ public class PersistenceExceptionTranslationAdvisorTests extends TestCase { } } - public void testTranslationNeededForTheseExceptions() { + @Test + public void translationNeededForTheseExceptions() { doTestTranslationNeededForTheseExceptions(new StereotypedRepositoryInterfaceImpl()); } - public void testTranslationNeededForTheseExceptionsOnSuperclass() { + @Test + public void translationNeededForTheseExceptionsOnSuperclass() { doTestTranslationNeededForTheseExceptions(new MyStereotypedRepositoryInterfaceImpl()); } - public void testTranslationNeededForTheseExceptionsWithCustomStereotype() { + @Test + public void translationNeededForTheseExceptionsWithCustomStereotype() { doTestTranslationNeededForTheseExceptions(new CustomStereotypedRepositoryInterfaceImpl()); } - public void testTranslationNeededForTheseExceptionsOnInterface() { + @Test + public void translationNeededForTheseExceptionsOnInterface() { doTestTranslationNeededForTheseExceptions(new MyInterfaceStereotypedRepositoryInterfaceImpl()); } - public void testTranslationNeededForTheseExceptionsOnInheritedInterface() { + @Test + public void translationNeededForTheseExceptionsOnInheritedInterface() { doTestTranslationNeededForTheseExceptions(new MyInterfaceInheritedStereotypedRepositoryInterfaceImpl()); } @@ -158,7 +167,6 @@ public class PersistenceExceptionTranslationAdvisorTests extends TestCase { void throwsPersistenceException() throws PersistenceException; } - public static class RepositoryInterfaceImpl implements RepositoryInterface { private RuntimeException runtimeException; @@ -182,52 +190,37 @@ public class PersistenceExceptionTranslationAdvisorTests extends TestCase { } } - @Repository public static class StereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl { // Extends above class just to add repository annotation } - public static class MyStereotypedRepositoryInterfaceImpl extends StereotypedRepositoryInterfaceImpl { - } - @MyRepository public static class CustomStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl { - } - @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Repository public @interface MyRepository { - } - @Repository public interface StereotypedInterface { - } - public static class MyInterfaceStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl implements StereotypedInterface { - } - public interface StereotypedInheritingInterface extends StereotypedInterface { - } - public static class MyInterfaceInheritedStereotypedRepositoryInterfaceImpl extends RepositoryInterfaceImpl implements StereotypedInheritingInterface { - } } diff --git a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java index ef2a0c2236..39c2bf78ea 100644 --- a/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/annotation/PersistenceExceptionTranslationPostProcessorTests.java @@ -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,11 +18,10 @@ package org.springframework.dao.annotation; import javax.persistence.PersistenceException; -import junit.framework.TestCase; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; - +import org.junit.Test; import org.springframework.aop.Advisor; import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator; import org.springframework.aop.framework.Advised; @@ -38,13 +37,17 @@ import org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.stereotype.Repository; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller */ -public class PersistenceExceptionTranslationPostProcessorTests extends TestCase { +public class PersistenceExceptionTranslationPostProcessorTests { - public void testProxiesCorrectly() { + @Test + @SuppressWarnings("resource") + public void proxiesCorrectly() { GenericApplicationContext gac = new GenericApplicationContext(); gac.registerBeanDefinition("translator", new RootBeanDefinition(PersistenceExceptionTranslationPostProcessor.class)); @@ -122,7 +125,6 @@ public class PersistenceExceptionTranslationPostProcessorTests extends TestCase public static class MyPersistenceExceptionTranslator implements PersistenceExceptionTranslator { - @Override public DataAccessException translateExceptionIfPossible(RuntimeException ex) { if (ex instanceof PersistenceException) { @@ -136,7 +138,6 @@ public class PersistenceExceptionTranslationPostProcessorTests extends TestCase @Aspect public static class LogAllAspect { - //@Before("execution(* *())") @Before("execution(void *.additionalMethod())") public void log(JoinPoint jp) { System.out.println("Before " + jp.getSignature().getName()); diff --git a/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java b/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java index 9998d9af65..111f6465ed 100644 --- a/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/support/ChainedPersistenceExceptionTranslatorTests.java @@ -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,26 +16,30 @@ package org.springframework.dao.support; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.dao.support.DataAccessUtilsTests.MapPersistenceExceptionTranslator; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @since 2.0 */ -public class ChainedPersistenceExceptionTranslatorTests extends TestCase { +public class ChainedPersistenceExceptionTranslatorTests { - public void testEmpty() { + @Test + public void empty() { ChainedPersistenceExceptionTranslator pet = new ChainedPersistenceExceptionTranslator(); //MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator(); RuntimeException in = new RuntimeException("in"); assertSame(in, DataAccessUtils.translateIfNecessary(in, pet)); } - public void testExceptionTranslationWithTranslation() { + @Test + public void exceptionTranslationWithTranslation() { MapPersistenceExceptionTranslator mpet1 = new MapPersistenceExceptionTranslator(); RuntimeException in1 = new RuntimeException("in"); InvalidDataAccessApiUsageException out1 = new InvalidDataAccessApiUsageException("out"); diff --git a/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java b/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java index a2e788646b..2b8ad81d69 100644 --- a/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java +++ b/spring-tx/src/test/java/org/springframework/dao/support/DataAccessUtilsTests.java @@ -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. @@ -23,20 +23,23 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.TypeMismatchDataAccessException; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @since 20.10.2004 */ -public class DataAccessUtilsTests extends TestCase { +public class DataAccessUtilsTests { - public void testWithEmptyCollection() { + @Test + public void withEmptyCollection() { Collection col = new HashSet(); assertNull(DataAccessUtils.uniqueResult(col)); @@ -82,7 +85,8 @@ public class DataAccessUtilsTests extends TestCase { } } - public void testWithTooLargeCollection() { + @Test + public void withTooLargeCollection() { Collection col = new HashSet(2); col.add("test1"); col.add("test2"); @@ -138,7 +142,8 @@ public class DataAccessUtilsTests extends TestCase { } } - public void testWithInteger() { + @Test + public void withInteger() { Collection col = new HashSet(1); col.add(5); @@ -150,7 +155,8 @@ public class DataAccessUtilsTests extends TestCase { assertEquals(5, DataAccessUtils.longResult(col)); } - public void testWithSameIntegerInstanceTwice() { + @Test + public void withSameIntegerInstanceTwice() { Integer i = 5; Collection col = new ArrayList(1); col.add(i); @@ -164,7 +170,8 @@ public class DataAccessUtilsTests extends TestCase { assertEquals(5, DataAccessUtils.longResult(col)); } - public void testWithEquivalentIntegerInstanceTwice() { + @Test + public void withEquivalentIntegerInstanceTwice() { Collection col = new ArrayList(2); col.add(new Integer(5)); col.add(new Integer(5)); @@ -180,7 +187,8 @@ public class DataAccessUtilsTests extends TestCase { } } - public void testWithLong() { + @Test + public void withLong() { Collection col = new HashSet(1); col.add(5L); @@ -192,7 +200,8 @@ public class DataAccessUtilsTests extends TestCase { assertEquals(5, DataAccessUtils.longResult(col)); } - public void testWithString() { + @Test + public void withString() { Collection col = new HashSet(1); col.add("test1"); @@ -217,7 +226,8 @@ public class DataAccessUtilsTests extends TestCase { } } - public void testWithDate() { + @Test + public void withDate() { Date date = new Date(); Collection col = new HashSet(1); col.add(date); @@ -244,13 +254,15 @@ public class DataAccessUtilsTests extends TestCase { } } - public void testExceptionTranslationWithNoTranslation() { + @Test + public void exceptionTranslationWithNoTranslation() { MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator(); RuntimeException in = new RuntimeException(); assertSame(in, DataAccessUtils.translateIfNecessary(in, mpet)); } - public void testExceptionTranslationWithTranslation() { + @Test + public void exceptionTranslationWithTranslation() { MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator(); RuntimeException in = new RuntimeException("in"); InvalidDataAccessApiUsageException out = new InvalidDataAccessApiUsageException("out"); diff --git a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java index 510b1ccf47..8b8a5eda4e 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java @@ -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,7 +20,8 @@ import javax.transaction.Status; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Test; import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; import org.springframework.transaction.jta.JtaTransactionManager; @@ -29,27 +30,32 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Juergen Hoeller * @since 05.08.2005 */ -public class JndiJtaTransactionManagerTests extends TestCase { +public class JndiJtaTransactionManagerTests { - public void testJtaTransactionManagerWithDefaultJndiLookups1() throws Exception { + @Test + public void jtaTransactionManagerWithDefaultJndiLookups1() throws Exception { doTestJtaTransactionManagerWithDefaultJndiLookups("java:comp/TransactionManager", true, true); } - public void testJtaTransactionManagerWithDefaultJndiLookups2() throws Exception { + @Test + public void jtaTransactionManagerWithDefaultJndiLookups2() throws Exception { doTestJtaTransactionManagerWithDefaultJndiLookups("java:/TransactionManager", true, true); } - public void testJtaTransactionManagerWithDefaultJndiLookupsAndNoTmFound() throws Exception { + @Test + public void jtaTransactionManagerWithDefaultJndiLookupsAndNoTmFound() throws Exception { doTestJtaTransactionManagerWithDefaultJndiLookups("java:/tm", false, true); } - public void testJtaTransactionManagerWithDefaultJndiLookupsAndNoUtFound() throws Exception { + @Test + public void jtaTransactionManagerWithDefaultJndiLookupsAndNoUtFound() throws Exception { doTestJtaTransactionManagerWithDefaultJndiLookups("java:/TransactionManager", true, false); } @@ -116,7 +122,8 @@ public class JndiJtaTransactionManagerTests extends TestCase { } - public void testJtaTransactionManagerWithCustomJndiLookups() throws Exception { + @Test + public void jtaTransactionManagerWithCustomJndiLookups() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -152,7 +159,8 @@ public class JndiJtaTransactionManagerTests extends TestCase { verify(ut).commit(); } - public void testJtaTransactionManagerWithNotCacheUserTransaction() throws Exception { + @Test + public void jtaTransactionManagerWithNotCacheUserTransaction() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -201,8 +209,8 @@ public class JndiJtaTransactionManagerTests extends TestCase { * Prevent any side-effects due to this test modifying ThreadLocals that might * affect subsequent tests when all tests are run in the same JVM, as with Eclipse. */ - @Override - protected void tearDown() { + @After + public void tearDown() { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); diff --git a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java index 2c5a557905..7d670f3524 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java @@ -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,8 @@ import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Test; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.tests.transaction.MockJtaTransaction; @@ -38,15 +39,17 @@ import org.springframework.transaction.support.TransactionSynchronizationAdapter import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Juergen Hoeller * @since 12.05.2003 */ -public class JtaTransactionManagerTests extends TestCase { +public class JtaTransactionManagerTests { - public void testJtaTransactionManagerWithCommit() throws Exception { + @Test + public void jtaTransactionManagerWithCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -82,7 +85,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_COMMITTED); } - public void testJtaTransactionManagerWithCommitAndSynchronizationOnActual() throws Exception { + @Test + public void jtaTransactionManagerWithCommitAndSynchronizationOnActual() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -110,7 +114,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_COMMITTED); } - public void testJtaTransactionManagerWithCommitAndSynchronizationNever() throws Exception { + @Test + public void jtaTransactionManagerWithCommitAndSynchronizationNever() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn( Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -133,7 +138,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).commit(); } - public void testJtaTransactionManagerWithRollback() throws Exception { + @Test + public void jtaTransactionManagerWithRollback() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); final TransactionSynchronization synch = mock(TransactionSynchronization.class); @@ -167,7 +173,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } - public void testJtaTransactionManagerWithRollbackAndSynchronizationOnActual() throws Exception { + @Test + public void jtaTransactionManagerWithRollbackAndSynchronizationOnActual() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); final TransactionSynchronization synch = mock(TransactionSynchronization.class); @@ -194,7 +201,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } - public void testJtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception { + @Test + public void jtaTransactionManagerWithRollbackAndSynchronizationNever() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); @@ -220,7 +228,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).rollback(); } - public void testJtaTransactionManagerWithExistingTransactionAndRollbackOnly() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndRollbackOnly() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -244,7 +253,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } - public void testJtaTransactionManagerWithExistingTransactionAndException() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndException() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -274,7 +284,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } - public void testJtaTransactionManagerWithExistingTransactionAndCommitException() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndCommitException() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -304,7 +315,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } - public void testJtaTransactionManagerWithExistingTransactionAndRollbackOnlyAndNoGlobalRollback() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndRollbackOnlyAndNoGlobalRollback() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -329,7 +341,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } - public void testJtaTransactionManagerWithExistingTransactionAndExceptionAndNoGlobalRollback() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndExceptionAndNoGlobalRollback() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); final TransactionSynchronization synch = mock(TransactionSynchronization.class); @@ -358,7 +371,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } - public void testJtaTransactionManagerWithExistingTransactionAndJtaSynchronization() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndJtaSynchronization() throws Exception { UserTransaction ut = mock(UserTransaction.class); TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction tx = new MockJtaTransaction(); @@ -389,7 +403,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } - public void testJtaTransactionManagerWithExistingTransactionAndSynchronizationOnActual() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndSynchronizationOnActual() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -414,7 +429,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } - public void testJtaTransactionManagerWithExistingTransactionAndSynchronizationNever() throws Exception { + @Test + public void jtaTransactionManagerWithExistingTransactionAndSynchronizationNever() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -436,7 +452,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).setRollbackOnly(); } - public void testJtaTransactionManagerWithExistingAndPropagationSupports() throws Exception { + @Test + public void jtaTransactionManagerWithExistingAndPropagationSupports() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -461,7 +478,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_UNKNOWN); } - public void testJtaTransactionManagerWithPropagationSupports() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationSupports() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); @@ -485,7 +503,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(synch).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); } - public void testJtaTransactionManagerWithPropagationSupportsAndSynchronizationOnActual() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationOnActual() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); @@ -506,7 +525,8 @@ public class JtaTransactionManagerTests extends TestCase { assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); } - public void testJtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationSupportsAndSynchronizationNever() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); @@ -527,7 +547,8 @@ public class JtaTransactionManagerTests extends TestCase { assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); } - public void testJtaTransactionManagerWithPropagationNotSupported() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationNotSupported() throws Exception { UserTransaction ut = mock(UserTransaction.class); TransactionManager tm = mock(TransactionManager.class); Transaction tx = mock(Transaction.class); @@ -550,7 +571,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(tm).resume(tx); } - public void testJtaTransactionManagerWithPropagationRequiresNew() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationRequiresNew() throws Exception { UserTransaction ut = mock(UserTransaction.class); TransactionManager tm = mock(TransactionManager.class); Transaction tx = mock(Transaction.class); @@ -597,7 +619,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(tm).resume(tx); } - public void testJtaTransactionManagerWithPropagationRequiresNewWithinSupports() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationRequiresNewWithinSupports() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -636,7 +659,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).commit(); } - public void testJtaTransactionManagerWithPropagationRequiresNewAndExisting() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationRequiresNewAndExisting() throws Exception { UserTransaction ut = mock(UserTransaction.class); TransactionManager tm = mock(TransactionManager.class); Transaction tx = mock(Transaction.class); @@ -660,7 +684,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(tm).resume(tx); } - public void testJtaTransactionManagerWithPropagationRequiresNewAndExistingWithSuspendException() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationRequiresNewAndExistingWithSuspendException() throws Exception { UserTransaction ut = mock(UserTransaction.class); TransactionManager tm = mock(TransactionManager.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -685,7 +710,8 @@ public class JtaTransactionManagerTests extends TestCase { assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); } - public void testJtaTransactionManagerWithPropagationRequiresNewAndExistingWithBeginException() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationRequiresNewAndExistingWithBeginException() throws Exception { UserTransaction ut = mock(UserTransaction.class); TransactionManager tm = mock(TransactionManager.class); Transaction tx = mock(Transaction.class); @@ -713,7 +739,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(tm).resume(tx); } - public void testJtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationRequiresNewAndAdapter() throws Exception { TransactionManager tm = mock(TransactionManager.class); Transaction tx = mock(Transaction.class); given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -736,7 +763,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(tm).resume(tx); } - public void testJtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception { + @Test + public void jtaTransactionManagerWithPropagationRequiresNewAndSuspensionNotSupported() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -758,7 +786,8 @@ public class JtaTransactionManagerTests extends TestCase { assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); } - public void testJtaTransactionManagerWithIsolationLevel() throws Exception { + @Test + public void jtaTransactionManagerWithIsolationLevel() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); @@ -779,7 +808,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception { + @Test + public void jtaTransactionManagerWithSystemExceptionOnIsExisting() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willThrow(new SystemException("system exception")); @@ -799,7 +829,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithNestedBegin() throws Exception { + @Test + public void jtaTransactionManagerWithNestedBegin() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); @@ -817,7 +848,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).commit(); } - public void testJtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception { + @Test + public void jtaTransactionManagerWithNotSupportedExceptionOnNestedBegin() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new NotSupportedException("not supported")).given(ut).begin(); @@ -839,7 +871,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithUnsupportedOperationExceptionOnNestedBegin() throws Exception { + @Test + public void jtaTransactionManagerWithUnsupportedOperationExceptionOnNestedBegin() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new UnsupportedOperationException("not supported")).given(ut).begin(); @@ -861,7 +894,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithSystemExceptionOnBegin() throws Exception { + @Test + public void jtaTransactionManagerWithSystemExceptionOnBegin() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); willThrow(new SystemException("system exception")).given(ut).begin(); @@ -882,7 +916,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithRollbackExceptionOnCommit() throws Exception { + @Test + public void jtaTransactionManagerWithRollbackExceptionOnCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -912,11 +947,13 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).begin(); } - public void testJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnly() throws Exception { + @Test + public void jtaTransactionManagerWithNoExceptionOnGlobalRollbackOnly() throws Exception { doTestJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnly(false); } - public void testJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnlyAndFailEarly() throws Exception { + @Test + public void jtaTransactionManagerWithNoExceptionOnGlobalRollbackOnlyAndFailEarly() throws Exception { doTestJtaTransactionManagerWithNoExceptionOnGlobalRollbackOnly(true); } @@ -977,7 +1014,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithHeuristicMixedExceptionOnCommit() throws Exception { + @Test + public void jtaTransactionManagerWithHeuristicMixedExceptionOnCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -1008,7 +1046,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).begin(); } - public void testJtaTransactionManagerWithHeuristicRollbackExceptionOnCommit() throws Exception { + @Test + public void jtaTransactionManagerWithHeuristicRollbackExceptionOnCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -1039,7 +1078,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).begin(); } - public void testJtaTransactionManagerWithSystemExceptionOnCommit() throws Exception { + @Test + public void jtaTransactionManagerWithSystemExceptionOnCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -1069,7 +1109,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).begin(); } - public void testJtaTransactionManagerWithSystemExceptionOnRollback() throws Exception { + @Test + public void jtaTransactionManagerWithSystemExceptionOnRollback() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); willThrow(new SystemException("system exception")).given(ut).rollback(); @@ -1098,7 +1139,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).begin(); } - public void testJtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception { + @Test + public void jtaTransactionManagerWithIllegalStateExceptionOnRollbackOnly() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new IllegalStateException("no existing transaction")).given(ut).setRollbackOnly(); @@ -1119,7 +1161,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithSystemExceptionOnRollbackOnly() throws Exception { + @Test + public void jtaTransactionManagerWithSystemExceptionOnRollbackOnly() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); willThrow(new SystemException("system exception")).given(ut).setRollbackOnly(); @@ -1146,7 +1189,8 @@ public class JtaTransactionManagerTests extends TestCase { } } - public void testJtaTransactionManagerWithDoubleCommit() throws Exception { + @Test + public void jtaTransactionManagerWithDoubleCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -1171,7 +1215,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).commit(); } - public void testJtaTransactionManagerWithDoubleRollback() throws Exception { + @Test + public void jtaTransactionManagerWithDoubleRollback() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); @@ -1195,7 +1240,8 @@ public class JtaTransactionManagerTests extends TestCase { verify(ut).rollback(); } - public void testJtaTransactionManagerWithRollbackAndCommit() throws Exception { + @Test + public void jtaTransactionManagerWithRollbackAndCommit() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); @@ -1237,8 +1283,8 @@ public class JtaTransactionManagerTests extends TestCase { * Prevent any side-effects due to this test modifying ThreadLocals that might * affect subsequent tests when all tests are run in the same JVM, as with Eclipse. */ - @Override - protected void tearDown() { + @After + public void tearDown() { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); assertNull(TransactionSynchronizationManager.getCurrentTransactionName()); diff --git a/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java b/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java index 2e42257b42..871e6b1b6e 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TransactionSupportTests.java @@ -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.transaction; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Test; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.DefaultTransactionStatus; @@ -24,13 +25,16 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @since 29.04.2003 */ -public class TransactionSupportTests extends TestCase { +public class TransactionSupportTests { - public void testNoExistingTransaction() { + @Test + public void noExistingTransaction() { PlatformTransactionManager tm = new TestTransactionManager(false, true); DefaultTransactionStatus status1 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS)); @@ -50,7 +54,8 @@ public class TransactionSupportTests extends TestCase { } } - public void testExistingTransaction() { + @Test + public void existingTransaction() { PlatformTransactionManager tm = new TestTransactionManager(true, true); DefaultTransactionStatus status1 = (DefaultTransactionStatus) tm.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_SUPPORTS)); @@ -73,7 +78,8 @@ public class TransactionSupportTests extends TestCase { } } - public void testCommitWithoutExistingTransaction() { + @Test + public void commitWithoutExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionStatus status = tm.getTransaction(null); tm.commit(status); @@ -83,7 +89,8 @@ public class TransactionSupportTests extends TestCase { assertTrue("no rollbackOnly", !tm.rollbackOnly); } - public void testRollbackWithoutExistingTransaction() { + @Test + public void rollbackWithoutExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionStatus status = tm.getTransaction(null); tm.rollback(status); @@ -93,7 +100,8 @@ public class TransactionSupportTests extends TestCase { assertTrue("no rollbackOnly", !tm.rollbackOnly); } - public void testRollbackOnlyWithoutExistingTransaction() { + @Test + public void rollbackOnlyWithoutExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionStatus status = tm.getTransaction(null); status.setRollbackOnly(); @@ -104,7 +112,8 @@ public class TransactionSupportTests extends TestCase { assertTrue("no rollbackOnly", !tm.rollbackOnly); } - public void testCommitWithExistingTransaction() { + @Test + public void commitWithExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(true, true); TransactionStatus status = tm.getTransaction(null); tm.commit(status); @@ -114,7 +123,8 @@ public class TransactionSupportTests extends TestCase { assertTrue("no rollbackOnly", !tm.rollbackOnly); } - public void testRollbackWithExistingTransaction() { + @Test + public void rollbackWithExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(true, true); TransactionStatus status = tm.getTransaction(null); tm.rollback(status); @@ -124,7 +134,8 @@ public class TransactionSupportTests extends TestCase { assertTrue("triggered rollbackOnly", tm.rollbackOnly); } - public void testRollbackOnlyWithExistingTransaction() { + @Test + public void rollbackOnlyWithExistingTransaction() { TestTransactionManager tm = new TestTransactionManager(true, true); TransactionStatus status = tm.getTransaction(null); status.setRollbackOnly(); @@ -135,7 +146,8 @@ public class TransactionSupportTests extends TestCase { assertTrue("triggered rollbackOnly", tm.rollbackOnly); } - public void testTransactionTemplate() { + @Test + public void transactionTemplate() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); template.execute(new TransactionCallbackWithoutResult() { @@ -149,7 +161,8 @@ public class TransactionSupportTests extends TestCase { assertTrue("no rollbackOnly", !tm.rollbackOnly); } - public void testTransactionTemplateWithCallbackPreference() { + @Test + public void transactionTemplateWithCallbackPreference() { MockCallbackPreferringTransactionManager ptm = new MockCallbackPreferringTransactionManager(); TransactionTemplate template = new TransactionTemplate(ptm); template.execute(new TransactionCallbackWithoutResult() { @@ -161,7 +174,8 @@ public class TransactionSupportTests extends TestCase { assertFalse(ptm.getStatus().isRollbackOnly()); } - public void testTransactionTemplateWithException() { + @Test + public void transactionTemplateWithException() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); final RuntimeException ex = new RuntimeException("Some application exception"); @@ -185,7 +199,8 @@ public class TransactionSupportTests extends TestCase { } @SuppressWarnings("serial") - public void testTransactionTemplateWithRollbackException() { + @Test + public void transactionTemplateWithRollbackException() { final TransactionSystemException tex = new TransactionSystemException("system exception"); TestTransactionManager tm = new TestTransactionManager(false, true) { @Override @@ -215,7 +230,8 @@ public class TransactionSupportTests extends TestCase { } } - public void testTransactionTemplateWithError() { + @Test + public void transactionTemplateWithError() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(tm); try { @@ -236,7 +252,8 @@ public class TransactionSupportTests extends TestCase { } } - public void testTransactionTemplateInitialization() { + @Test + public void transactionTemplateInitialization() { TestTransactionManager tm = new TestTransactionManager(false, true); TransactionTemplate template = new TransactionTemplate(); template.setTransactionManager(tm); @@ -283,8 +300,9 @@ public class TransactionSupportTests extends TestCase { assertTrue("Correct isolation level set", template.getIsolationLevel() == TransactionDefinition.ISOLATION_REPEATABLE_READ); } - @Override - protected void tearDown() { + + @After + public void tearDown() { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java index 3f4286e51b..0950c61813 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java @@ -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,7 +16,8 @@ package org.springframework.transaction; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.parsing.ComponentDefinition; @@ -25,27 +26,31 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; import org.springframework.tests.beans.CollectingReaderEventListener; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + /** * @author Torsten Juergeleit * @author Juergen Hoeller */ -public class TxNamespaceHandlerEventTests extends TestCase { +public class TxNamespaceHandlerEventTests { private DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); private CollectingReaderEventListener eventListener = new CollectingReaderEventListener(); - @Override + @Before public void setUp() throws Exception { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.setEventListener(this.eventListener); reader.loadBeanDefinitions(new ClassPathResource("txNamespaceHandlerTests.xml", getClass())); } - public void testComponentEventReceived() { + @Test + public void componentEventReceived() { ComponentDefinition component = this.eventListener.getComponentDefinition("txAdvice"); - assertTrue(component instanceof BeanComponentDefinition); + assertThat(component, instanceOf(BeanComponentDefinition.class)); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java index 842c05057f..52c41cd924 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java @@ -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,7 +18,8 @@ package org.springframework.transaction; import java.lang.reflect.Method; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.context.ApplicationContext; @@ -29,11 +30,13 @@ import org.springframework.transaction.interceptor.TransactionAttribute; import org.springframework.transaction.interceptor.TransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionInterceptor; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Adrian Colyer */ -public class TxNamespaceHandlerTests extends TestCase { +public class TxNamespaceHandlerTests { private ApplicationContext context; @@ -41,19 +44,22 @@ public class TxNamespaceHandlerTests extends TestCase { private Method setAgeMethod; - @Override + + @Before public void setUp() throws Exception { this.context = new ClassPathXmlApplicationContext("txNamespaceHandlerTests.xml", getClass()); this.getAgeMethod = ITestBean.class.getMethod("getAge", new Class[0]); this.setAgeMethod = ITestBean.class.getMethod("setAge", new Class[] {int.class}); } - public void testIsProxy() throws Exception { + @Test + public void isProxy() throws Exception { ITestBean bean = getTestBean(); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); } - public void testInvokeTransactional() throws Exception { + @Test + public void invokeTransactional() throws Exception { ITestBean testBean = getTestBean(); CallCountingTransactionManager ptm = (CallCountingTransactionManager) context.getBean("transactionManager"); @@ -79,7 +85,8 @@ public class TxNamespaceHandlerTests extends TestCase { } } - public void testRollbackRules() { + @Test + public void rollbackRules() { TransactionInterceptor txInterceptor = (TransactionInterceptor) context.getBean("txRollbackAdvice"); TransactionAttributeSource txAttrSource = txInterceptor.getTransactionAttributeSource(); TransactionAttribute txAttr = txAttrSource.getTransactionAttribute(getAgeMethod,ITestBean.class); diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java index 556cb59965..8cdec71df9 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java @@ -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,35 +16,30 @@ package org.springframework.transaction.annotation; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.transaction.support.TransactionSynchronizationManager; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller */ -public class AnnotationTransactionInterceptorTests extends TestCase { +public class AnnotationTransactionInterceptorTests { - private CallCountingTransactionManager ptm; + private final CallCountingTransactionManager ptm = new CallCountingTransactionManager(); - private AnnotationTransactionAttributeSource source; + private final AnnotationTransactionAttributeSource source = new AnnotationTransactionAttributeSource(); - private TransactionInterceptor ti; + private final TransactionInterceptor ti = new TransactionInterceptor(this.ptm, this.source); - @Override - public void setUp() { - this.ptm = new CallCountingTransactionManager(); - this.source = new AnnotationTransactionAttributeSource(); - this.ti = new TransactionInterceptor(this.ptm, this.source); - } - - - public void testClassLevelOnly() { + @Test + public void classLevelOnly() { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new TestClassLevelOnly()); proxyFactory.addAdvice(this.ti); @@ -64,7 +59,8 @@ public class AnnotationTransactionInterceptorTests extends TestCase { assertGetTransactionAndCommitCount(4); } - public void testWithSingleMethodOverride() { + @Test + public void withSingleMethodOverride() { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new TestWithSingleMethodOverride()); proxyFactory.addAdvice(this.ti); @@ -84,7 +80,8 @@ public class AnnotationTransactionInterceptorTests extends TestCase { assertGetTransactionAndCommitCount(4); } - public void testWithSingleMethodOverrideInverted() { + @Test + public void withSingleMethodOverrideInverted() { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new TestWithSingleMethodOverrideInverted()); proxyFactory.addAdvice(this.ti); @@ -104,7 +101,8 @@ public class AnnotationTransactionInterceptorTests extends TestCase { assertGetTransactionAndCommitCount(4); } - public void testWithMultiMethodOverride() { + @Test + public void withMultiMethodOverride() { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new TestWithMultiMethodOverride()); proxyFactory.addAdvice(this.ti); @@ -124,8 +122,8 @@ public class AnnotationTransactionInterceptorTests extends TestCase { assertGetTransactionAndCommitCount(4); } - - public void testWithRollback() { + @Test + public void withRollback() { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new TestWithRollback()); proxyFactory.addAdvice(this.ti); @@ -149,7 +147,8 @@ public class AnnotationTransactionInterceptorTests extends TestCase { } } - public void testWithInterface() { + @Test + public void withInterface() { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new TestWithInterfaceImpl()); proxyFactory.addInterface(TestWithInterface.class); @@ -170,7 +169,8 @@ public class AnnotationTransactionInterceptorTests extends TestCase { assertGetTransactionAndCommitCount(4); } - public void testCrossClassInterfaceMethodLevelOnJdkProxy() throws Exception { + @Test + public void crossClassInterfaceMethodLevelOnJdkProxy() throws Exception { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new SomeServiceImpl()); proxyFactory.addInterface(SomeService.class); @@ -188,7 +188,8 @@ public class AnnotationTransactionInterceptorTests extends TestCase { assertGetTransactionAndCommitCount(3); } - public void testCrossClassInterfaceOnJdkProxy() throws Exception { + @Test + public void crossClassInterfaceOnJdkProxy() throws Exception { ProxyFactory proxyFactory = new ProxyFactory(); proxyFactory.setTarget(new OtherServiceImpl()); proxyFactory.addInterface(OtherService.class); @@ -364,7 +365,7 @@ public class AnnotationTransactionInterceptorTests extends TestCase { } - public static interface OtherService { + public interface OtherService { void foo(); } diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java index de1dd777f8..c1d8278d03 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java @@ -22,7 +22,8 @@ import java.util.Map; import javax.management.MBeanServer; import javax.management.ObjectName; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.context.ConfigurableApplicationContext; @@ -34,34 +35,33 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.config.TransactionManagementConfigUtils; import org.springframework.transaction.event.TransactionalEventListenerFactory; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller * @author Sam Brannen */ -public class AnnotationTransactionNamespaceHandlerTests extends TestCase { +public class AnnotationTransactionNamespaceHandlerTests { - private ConfigurableApplicationContext context; + private final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( + "org/springframework/transaction/annotation/annotationTransactionNamespaceHandlerTests.xml"); - @Override - public void setUp() { - this.context = new ClassPathXmlApplicationContext( - "org/springframework/transaction/annotation/annotationTransactionNamespaceHandlerTests.xml"); - } - - @Override - protected void tearDown() { + @After + public void tearDown() { this.context.close(); } - public void testIsProxy() throws Exception { + @Test + public void isProxy() throws Exception { TransactionalTestBean bean = getTestBean(); assertTrue("testBean is not a proxy", AopUtils.isAopProxy(bean)); Map services = this.context.getBeansWithAnnotation(Service.class); assertTrue("Stereotype annotation not visible", services.containsKey("testBean")); } - public void testInvokeTransactional() throws Exception { + @Test + public void invokeTransactional() throws Exception { TransactionalTestBean testBean = getTestBean(); CallCountingTransactionManager ptm = (CallCountingTransactionManager) context.getBean("transactionManager"); @@ -83,11 +83,11 @@ public class AnnotationTransactionNamespaceHandlerTests extends TestCase { catch (Throwable throwable) { assertEquals("Should have another started transaction", 2, ptm.begun); assertEquals("Should have 1 rolled back transaction", 1, ptm.rollbacks); - } } - public void testNonPublicMethodsNotAdvised() { + @Test + public void nonPublicMethodsNotAdvised() { TransactionalTestBean testBean = getTestBean(); CallCountingTransactionManager ptm = (CallCountingTransactionManager) context.getBean("transactionManager"); @@ -96,13 +96,15 @@ public class AnnotationTransactionNamespaceHandlerTests extends TestCase { assertEquals("Should not have any started transactions", 0, ptm.begun); } - public void testMBeanExportAlsoWorks() throws Exception { + @Test + public void mBeanExportAlsoWorks() throws Exception { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); assertEquals("done", server.invoke(ObjectName.getInstance("test:type=TestBean"), "doSomething", new Object[0], new String[0])); } - public void testTransactionalEventListenerRegisteredProperly() { + @Test + public void transactionalEventListenerRegisteredProperly() { assertTrue(this.context.containsBean(TransactionManagementConfigUtils .TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME)); assertEquals(1, this.context.getBeansOfType(TransactionalEventListenerFactory.class).size()); diff --git a/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java b/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java index ee458c0cf8..3e561c04e6 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java @@ -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,10 +18,11 @@ package org.springframework.transaction.config; import java.io.Serializable; -import junit.framework.TestCase; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; +import org.junit.Test; + import org.springframework.aop.support.AopUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -30,18 +31,22 @@ import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.SerializationTestUtils; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller */ -public class AnnotationDrivenTests extends TestCase { +public class AnnotationDrivenTests { - public void testWithProxyTargetClass() throws Exception { + @Test + public void withProxyTargetClass() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("annotationDrivenProxyTargetClassTests.xml", getClass()); doTestWithMultipleTransactionManagers(context); } - public void testWithConfigurationClass() throws Exception { + @Test + public void withConfigurationClass() throws Exception { AnnotationConfigApplicationContext parent = new AnnotationConfigApplicationContext(); parent.register(TransactionManagerConfiguration.class); parent.refresh(); @@ -68,7 +73,9 @@ public class AnnotationDrivenTests extends TestCase { assertEquals(2, tm2.commits); } - public void testSerializableWithPreviousUsage() throws Exception { + @Test + @SuppressWarnings("resource") + public void serializableWithPreviousUsage() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("annotationDrivenProxyTargetClassTests.xml", getClass()); TransactionalService service = context.getBean("service", TransactionalService.class); service.setSomething("someName"); @@ -76,7 +83,9 @@ public class AnnotationDrivenTests extends TestCase { service.setSomething("someName"); } - public void testSerializableWithoutPreviousUsage() throws Exception { + @Test + @SuppressWarnings("resource") + public void serializableWithoutPreviousUsage() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("annotationDrivenProxyTargetClassTests.xml", getClass()); TransactionalService service = context.getBean("service", TransactionalService.class); service = (TransactionalService) SerializationTestUtils.serializeAndDeserialize(service); diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java index 9f426f1d99..6b20b4bbbb 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/RollbackRuleTests.java @@ -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. @@ -18,7 +18,7 @@ package org.springframework.transaction.interceptor; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.FatalBeanException; @@ -31,32 +31,38 @@ import static org.junit.Assert.*; * @author Rod Johnson * @author Rick Evans * @author Chris Beams + * @author Sam Brannen * @since 09.04.2003 */ -public class RollbackRuleTests extends TestCase { +public class RollbackRuleTests { - public void testFoundImmediatelyWithString() { + @Test + public void foundImmediatelyWithString() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.lang.Exception.class.getName()); - assertTrue(rr.getDepth(new Exception()) == 0); + assertEquals(0, rr.getDepth(new Exception())); } - public void testFoundImmediatelyWithClass() { + @Test + public void foundImmediatelyWithClass() { RollbackRuleAttribute rr = new RollbackRuleAttribute(Exception.class); - assertTrue(rr.getDepth(new Exception()) == 0); + assertEquals(0, rr.getDepth(new Exception())); } - public void testNotFound() { + @Test + public void notFound() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.io.IOException.class.getName()); - assertTrue(rr.getDepth(new MyRuntimeException("")) == -1); + assertEquals(-1, rr.getDepth(new MyRuntimeException(""))); } - public void testAncestry() { + @Test + public void ancestry() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.lang.Exception.class.getName()); // Exception -> Runtime -> NestedRuntime -> MyRuntimeException assertThat(rr.getDepth(new MyRuntimeException("")), equalTo(3)); } - public void testAlwaysTrueForThrowable() { + @Test + public void alwaysTrueForThrowable() { RollbackRuleAttribute rr = new RollbackRuleAttribute(java.lang.Throwable.class.getName()); assertTrue(rr.getDepth(new MyRuntimeException("")) > 0); assertTrue(rr.getDepth(new IOException()) > 0); @@ -64,31 +70,19 @@ public class RollbackRuleTests extends TestCase { assertTrue(rr.getDepth(new RuntimeException()) > 0); } - public void testCtorArgMustBeAThrowableClassWithNonThrowableType() { - try { - new RollbackRuleAttribute(StringBuffer.class); - fail("Cannot construct a RollbackRuleAttribute with a non-Throwable type"); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorArgMustBeAThrowableClassWithNonThrowableType() { + new RollbackRuleAttribute(StringBuffer.class); } - public void testCtorArgMustBeAThrowableClassWithNullThrowableType() { - try { - new RollbackRuleAttribute((Class) null); - fail("Cannot construct a RollbackRuleAttribute with a null-Throwable type"); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorArgMustBeAThrowableClassWithNullThrowableType() { + new RollbackRuleAttribute((Class) null); } - public void testCtorArgExceptionStringNameVersionWithNull() { - try { - new RollbackRuleAttribute((String) null); - fail("Cannot construct a RollbackRuleAttribute with a null-Throwable type"); - } - catch (IllegalArgumentException expected) { - } + @Test(expected = IllegalArgumentException.class) + public void ctorArgExceptionStringNameVersionWithNull() { + new RollbackRuleAttribute((String) null); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceAdvisorTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceAdvisorTests.java index a47f6c2df3..46079619fe 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceAdvisorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceAdvisorTests.java @@ -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,21 +18,17 @@ package org.springframework.transaction.interceptor; import java.util.Properties; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.util.SerializationTestUtils; /** - * * @author Rod Johnson */ -public class TransactionAttributeSourceAdvisorTests extends TestCase { +public class TransactionAttributeSourceAdvisorTests { - public TransactionAttributeSourceAdvisorTests(String s) { - super(s); - } - - public void testSerializability() throws Exception { + @Test + public void serializability() throws Exception { TransactionInterceptor ti = new TransactionInterceptor(); ti.setTransactionAttributes(new Properties()); TransactionAttributeSourceAdvisor tas = new TransactionAttributeSourceAdvisor(ti); diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java index 5aa4746542..e16c92b6f7 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceEditorTests.java @@ -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,49 +18,49 @@ package org.springframework.transaction.interceptor; import java.lang.reflect.Method; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.transaction.TransactionDefinition; +import static org.junit.Assert.*; + /** - * Format is - * {@code FQN.Method=tx attribute representation} + * Unit tests for {@link TransactionAttributeSourceEditor}. + * + *

Format is: {@code FQN.Method=tx attribute representation} * * @author Rod Johnson + * @author Sam Brannen * @since 26.04.2003 */ -public class TransactionAttributeSourceEditorTests extends TestCase { +public class TransactionAttributeSourceEditorTests { - public void testNull() throws Exception { - TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor(); - pe.setAsText(null); - TransactionAttributeSource tas = (TransactionAttributeSource) pe.getValue(); + private final TransactionAttributeSourceEditor editor = new TransactionAttributeSourceEditor(); + + + @Test + public void nullValue() throws Exception { + editor.setAsText(null); + TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue(); Method m = Object.class.getMethod("hashCode", (Class[]) null); - assertTrue(tas.getTransactionAttribute(m, null) == null); + assertNull(tas.getTransactionAttribute(m, null)); } - public void testInvalid() throws Exception { - TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor(); - try { - pe.setAsText("foo=bar"); - fail(); - } - catch (IllegalArgumentException ex) { - // Ok - } + @Test(expected = IllegalArgumentException.class) + public void invalidFormat() throws Exception { + editor.setAsText("foo=bar"); } - public void testMatchesSpecific() throws Exception { - TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor(); - // TODO need FQN? - pe.setAsText( + @Test + public void matchesSpecific() throws Exception { + editor.setAsText( "java.lang.Object.hashCode=PROPAGATION_REQUIRED\n" + "java.lang.Object.equals=PROPAGATION_MANDATORY\n" + "java.lang.Object.*it=PROPAGATION_SUPPORTS\n" + "java.lang.Object.notify=PROPAGATION_SUPPORTS\n" + "java.lang.Object.not*=PROPAGATION_REQUIRED"); - TransactionAttributeSource tas = (TransactionAttributeSource) pe.getValue(); + TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue(); checkTransactionProperties(tas, Object.class.getMethod("hashCode", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); @@ -79,10 +79,10 @@ public class TransactionAttributeSourceEditorTests extends TestCase { checkTransactionProperties(tas, Object.class.getMethod("toString", (Class[]) null), -1); } - public void testMatchesAll() throws Exception { - TransactionAttributeSourceEditor pe = new TransactionAttributeSourceEditor(); - pe.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED"); - TransactionAttributeSource tas = (TransactionAttributeSource) pe.getValue(); + @Test + public void matchesAll() throws Exception { + editor.setAsText("java.lang.Object.*=PROPAGATION_REQUIRED"); + TransactionAttributeSource tas = (TransactionAttributeSource) editor.getValue(); checkTransactionProperties(tas, Object.class.getMethod("hashCode", (Class[]) null), TransactionDefinition.PROPAGATION_REQUIRED); @@ -105,12 +105,12 @@ public class TransactionAttributeSourceEditorTests extends TestCase { private void checkTransactionProperties(TransactionAttributeSource tas, Method method, int propagationBehavior) { TransactionAttribute ta = tas.getTransactionAttribute(method, null); if (propagationBehavior >= 0) { - assertTrue(ta != null); - assertTrue(ta.getIsolationLevel() == TransactionDefinition.ISOLATION_DEFAULT); - assertTrue(ta.getPropagationBehavior() == propagationBehavior); + assertNotNull(ta); + assertEquals(TransactionDefinition.ISOLATION_DEFAULT, ta.getIsolationLevel()); + assertEquals(propagationBehavior, ta.getPropagationBehavior()); } else { - assertTrue(ta == null); + assertNull(ta); } } diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java index 0dce66637d..0e51892b01 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/TransactionAttributeSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 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,11 +17,8 @@ package org.springframework.transaction.interceptor; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; import java.util.Properties; -import org.junit.Ignore; import org.junit.Test; import org.springframework.transaction.TransactionDefinition; @@ -41,7 +38,7 @@ import static org.junit.Assert.*; public final class TransactionAttributeSourceTests { @Test - public void testMatchAlwaysTransactionAttributeSource() throws Exception { + public void matchAlwaysTransactionAttributeSource() throws Exception { MatchAlwaysTransactionAttributeSource tas = new MatchAlwaysTransactionAttributeSource(); TransactionAttribute ta = tas.getTransactionAttribute( Object.class.getMethod("hashCode", (Class[]) null), null); @@ -56,7 +53,7 @@ public final class TransactionAttributeSourceTests { } @Test - public void testMatchAlwaysTransactionAttributeSourceWithNulls() throws Exception { + public void matchAlwaysTransactionAttributeSourceWithNulls() throws Exception { MatchAlwaysTransactionAttributeSource tas = new MatchAlwaysTransactionAttributeSource(); TransactionDefinition definition = tas.getTransactionAttribute(null, null); assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, definition.getPropagationBehavior()); @@ -65,65 +62,9 @@ public final class TransactionAttributeSourceTests { assertFalse(definition.isReadOnly()); } - @SuppressWarnings("unchecked") - @Ignore // no longer works now that setMethodMap has been parameterized @Test - public void testMethodMapTransactionAttributeSource() throws NoSuchMethodException { - MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource(); - Map methodMap = new HashMap(); - methodMap.put(Object.class.getName() + ".hashCode", TransactionDefinition.PROPAGATION_REQUIRED); - methodMap.put(Object.class.getName() + ".toString", - new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_SUPPORTS)); - tas.setMethodMap(methodMap); - tas.afterPropertiesSet(); - TransactionAttribute ta = tas.getTransactionAttribute( - Object.class.getMethod("hashCode", (Class[]) null), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior()); - ta = tas.getTransactionAttribute(Object.class.getMethod("toString", (Class[]) null), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior()); - } - - @SuppressWarnings("unchecked") - @Ignore // no longer works now that setMethodMap has been parameterized - @Test - public void testMethodMapTransactionAttributeSourceWithLazyInit() throws NoSuchMethodException { - MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource(); - Map methodMap = new HashMap(); - methodMap.put(Object.class.getName() + ".hashCode", "PROPAGATION_REQUIRED"); - methodMap.put(Object.class.getName() + ".toString", - new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_SUPPORTS)); - tas.setMethodMap(methodMap); - TransactionAttribute ta = tas.getTransactionAttribute( - Object.class.getMethod("hashCode", (Class[]) null), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior()); - ta = tas.getTransactionAttribute(Object.class.getMethod("toString", (Class[]) null), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior()); - } - - @SuppressWarnings("unchecked") - @Ignore // no longer works now that setMethodMap has been parameterized - @Test - public void testNameMatchTransactionAttributeSource() throws NoSuchMethodException { - NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource(); - Map methodMap = new HashMap(); - methodMap.put("hashCode", "PROPAGATION_REQUIRED"); - methodMap.put("toString", new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_SUPPORTS)); - tas.setNameMap(methodMap); - TransactionAttribute ta = tas.getTransactionAttribute( - Object.class.getMethod("hashCode", (Class[]) null), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_REQUIRED, ta.getPropagationBehavior()); - ta = tas.getTransactionAttribute(Object.class.getMethod("toString", (Class[]) null), null); - assertNotNull(ta); - assertEquals(TransactionDefinition.PROPAGATION_SUPPORTS, ta.getPropagationBehavior()); - } - - @Test - public void testNameMatchTransactionAttributeSourceWithStarAtStartOfMethodName() throws NoSuchMethodException { + public void nameMatchTransactionAttributeSourceWithStarAtStartOfMethodName() + throws NoSuchMethodException { NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource(); Properties attributes = new Properties(); attributes.put("*ashCode", "PROPAGATION_REQUIRED"); @@ -135,7 +76,8 @@ public final class TransactionAttributeSourceTests { } @Test - public void testNameMatchTransactionAttributeSourceWithStarAtEndOfMethodName() throws NoSuchMethodException { + public void nameMatchTransactionAttributeSourceWithStarAtEndOfMethodName() + throws NoSuchMethodException { NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource(); Properties attributes = new Properties(); attributes.put("hashCod*", "PROPAGATION_REQUIRED"); @@ -147,7 +89,8 @@ public final class TransactionAttributeSourceTests { } @Test - public void testNameMatchTransactionAttributeSourceMostSpecificMethodNameIsDefinitelyMatched() throws NoSuchMethodException { + public void nameMatchTransactionAttributeSourceMostSpecificMethodNameIsDefinitelyMatched() + throws NoSuchMethodException { NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource(); Properties attributes = new Properties(); attributes.put("*", "PROPAGATION_REQUIRED"); @@ -160,7 +103,8 @@ public final class TransactionAttributeSourceTests { } @Test - public void testNameMatchTransactionAttributeSourceWithEmptyMethodName() throws NoSuchMethodException { + public void nameMatchTransactionAttributeSourceWithEmptyMethodName() + throws NoSuchMethodException { NameMatchTransactionAttributeSource tas = new NameMatchTransactionAttributeSource(); Properties attributes = new Properties(); attributes.put("", "PROPAGATION_MANDATORY"); diff --git a/spring-tx/src/test/java/org/springframework/transaction/jta/MockUOWManager.java b/spring-tx/src/test/java/org/springframework/transaction/jta/MockUOWManager.java index 5daf7629ac..6542569118 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/jta/MockUOWManager.java +++ b/spring-tx/src/test/java/org/springframework/transaction/jta/MockUOWManager.java @@ -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. @@ -128,7 +128,7 @@ public class MockUOWManager implements UOWManager { this.synchronizations.add(sync); } - public List getSynchronizations() { + public List getSynchronizations() { return this.synchronizations; } diff --git a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java index 904e88f37f..68c8f05cd6 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java @@ -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,10 +20,7 @@ import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.UserTransaction; -import com.ibm.wsspi.uow.UOWAction; -import com.ibm.wsspi.uow.UOWException; -import com.ibm.wsspi.uow.UOWManager; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; @@ -36,14 +33,20 @@ import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionSynchronizationManager; +import com.ibm.wsspi.uow.UOWAction; +import com.ibm.wsspi.uow.UOWException; +import com.ibm.wsspi.uow.UOWManager; + +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Juergen Hoeller */ -public class WebSphereUowTransactionManagerTests extends TestCase { +public class WebSphereUowTransactionManagerTests { - public void testUowManagerFoundInJndi() { + @Test + public void uowManagerFoundInJndi() { MockUOWManager manager = new MockUOWManager(); ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate(WebSphereUowTransactionManager.DEFAULT_UOW_MANAGER_NAME, manager); @@ -64,7 +67,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertFalse(manager.getRollbackOnly()); } - public void testUowManagerAndUserTransactionFoundInJndi() throws Exception { + @Test + public void uowManagerAndUserTransactionFoundInJndi() throws Exception { UserTransaction ut = mock(UserTransaction.class); given(ut.getStatus()).willReturn( Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); @@ -93,7 +97,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { verify(ut).commit(); } - public void testPropagationMandatoryFailsInCaseOfNoExistingTransaction() { + @Test + public void propagationMandatoryFailsInCaseOfNoExistingTransaction() { MockUOWManager manager = new MockUOWManager(); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); @@ -113,47 +118,56 @@ public class WebSphereUowTransactionManagerTests extends TestCase { } } - public void testNewTransactionSynchronizationUsingPropagationSupports() { + @Test + public void newTransactionSynchronizationUsingPropagationSupports() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_SUPPORTS, WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS); } - public void testNewTransactionSynchronizationUsingPropagationNotSupported() { + @Test + public void newTransactionSynchronizationUsingPropagationNotSupported() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_NOT_SUPPORTED, WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS); } - public void testNewTransactionSynchronizationUsingPropagationNever() { + @Test + public void newTransactionSynchronizationUsingPropagationNever() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_NEVER, WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS); } - public void testNewTransactionSynchronizationUsingPropagationSupportsAndSynchOnActual() { + @Test + public void newTransactionSynchronizationUsingPropagationSupportsAndSynchOnActual() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_SUPPORTS, WebSphereUowTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } - public void testNewTransactionSynchronizationUsingPropagationNotSupportedAndSynchOnActual() { + @Test + public void newTransactionSynchronizationUsingPropagationNotSupportedAndSynchOnActual() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_NOT_SUPPORTED, WebSphereUowTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } - public void testNewTransactionSynchronizationUsingPropagationNeverAndSynchOnActual() { + @Test + public void newTransactionSynchronizationUsingPropagationNeverAndSynchOnActual() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_NEVER, WebSphereUowTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } - public void testNewTransactionSynchronizationUsingPropagationSupportsAndSynchNever() { + @Test + public void newTransactionSynchronizationUsingPropagationSupportsAndSynchNever() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_SUPPORTS, WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER); } - public void testNewTransactionSynchronizationUsingPropagationNotSupportedAndSynchNever() { + @Test + public void newTransactionSynchronizationUsingPropagationNotSupportedAndSynchNever() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_NOT_SUPPORTED, WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER); } - public void testNewTransactionSynchronizationUsingPropagationNeverAndSynchNever() { + @Test + public void newTransactionSynchronizationUsingPropagationNeverAndSynchNever() { doTestNewTransactionSynchronization( TransactionDefinition.PROPAGATION_NEVER, WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER); } @@ -197,47 +211,56 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertFalse(manager.getRollbackOnly()); } - public void testNewTransactionWithCommitUsingPropagationRequired() { + @Test + public void newTransactionWithCommitUsingPropagationRequired() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_REQUIRED, WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS); } - public void testNewTransactionWithCommitUsingPropagationRequiresNew() { + @Test + public void newTransactionWithCommitUsingPropagationRequiresNew() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_REQUIRES_NEW, WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS); } - public void testNewTransactionWithCommitUsingPropagationNested() { + @Test + public void newTransactionWithCommitUsingPropagationNested() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_NESTED, WebSphereUowTransactionManager.SYNCHRONIZATION_ALWAYS); } - public void testNewTransactionWithCommitUsingPropagationRequiredAndSynchOnActual() { + @Test + public void newTransactionWithCommitUsingPropagationRequiredAndSynchOnActual() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_REQUIRED, WebSphereUowTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } - public void testNewTransactionWithCommitUsingPropagationRequiresNewAndSynchOnActual() { + @Test + public void newTransactionWithCommitUsingPropagationRequiresNewAndSynchOnActual() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_REQUIRES_NEW, WebSphereUowTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } - public void testNewTransactionWithCommitUsingPropagationNestedAndSynchOnActual() { + @Test + public void newTransactionWithCommitUsingPropagationNestedAndSynchOnActual() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_NESTED, WebSphereUowTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); } - public void testNewTransactionWithCommitUsingPropagationRequiredAndSynchNever() { + @Test + public void newTransactionWithCommitUsingPropagationRequiredAndSynchNever() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_REQUIRED, WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER); } - public void testNewTransactionWithCommitUsingPropagationRequiresNewAndSynchNever() { + @Test + public void newTransactionWithCommitUsingPropagationRequiresNewAndSynchNever() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_REQUIRES_NEW, WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER); } - public void testNewTransactionWithCommitUsingPropagationNestedAndSynchNever() { + @Test + public void newTransactionWithCommitUsingPropagationNestedAndSynchNever() { doTestNewTransactionWithCommit( TransactionDefinition.PROPAGATION_NESTED, WebSphereUowTransactionManager.SYNCHRONIZATION_NEVER); } @@ -281,7 +304,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertFalse(manager.getRollbackOnly()); } - public void testNewTransactionWithCommitAndTimeout() { + @Test + public void newTransactionWithCommitAndTimeout() { MockUOWManager manager = new MockUOWManager(); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); @@ -312,7 +336,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertFalse(manager.getRollbackOnly()); } - public void testNewTransactionWithCommitException() { + @Test + public void newTransactionWithCommitException() { final RollbackException rex = new RollbackException(); MockUOWManager manager = new MockUOWManager() { @Override @@ -353,7 +378,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertEquals(0, manager.getUOWTimeout()); } - public void testNewTransactionWithRollback() { + @Test + public void newTransactionWithRollback() { MockUOWManager manager = new MockUOWManager(); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); @@ -388,7 +414,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertTrue(manager.getRollbackOnly()); } - public void testNewTransactionWithRollbackOnly() { + @Test + public void newTransactionWithRollbackOnly() { MockUOWManager manager = new MockUOWManager(); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); @@ -418,7 +445,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertTrue(manager.getRollbackOnly()); } - public void testExistingNonSpringTransaction() { + @Test + public void existingNonSpringTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); @@ -448,7 +476,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertFalse(manager.getRollbackOnly()); } - public void testPropagationNeverFailsInCaseOfExistingTransaction() { + @Test + public void propagationNeverFailsInCaseOfExistingTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); @@ -469,7 +498,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { } } - public void testPropagationNestedFailsInCaseOfExistingTransaction() { + @Test + public void propagationNestedFailsInCaseOfExistingTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); @@ -490,15 +520,18 @@ public class WebSphereUowTransactionManagerTests extends TestCase { } } - public void testExistingTransactionWithParticipationUsingPropagationRequired() { + @Test + public void existingTransactionWithParticipationUsingPropagationRequired() { doTestExistingTransactionWithParticipation(TransactionDefinition.PROPAGATION_REQUIRED); } - public void testExistingTransactionWithParticipationUsingPropagationSupports() { + @Test + public void existingTransactionWithParticipationUsingPropagationSupports() { doTestExistingTransactionWithParticipation(TransactionDefinition.PROPAGATION_SUPPORTS); } - public void testExistingTransactionWithParticipationUsingPropagationMandatory() { + @Test + public void existingTransactionWithParticipationUsingPropagationMandatory() { doTestExistingTransactionWithParticipation(TransactionDefinition.PROPAGATION_MANDATORY); } @@ -543,11 +576,13 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertFalse(manager.getRollbackOnly()); } - public void testExistingTransactionWithSuspensionUsingPropagationRequiresNew() { + @Test + public void existingTransactionWithSuspensionUsingPropagationRequiresNew() { doTestExistingTransactionWithSuspension(TransactionDefinition.PROPAGATION_REQUIRES_NEW); } - public void testExistingTransactionWithSuspensionUsingPropagationNotSupported() { + @Test + public void existingTransactionWithSuspensionUsingPropagationNotSupported() { doTestExistingTransactionWithSuspension(TransactionDefinition.PROPAGATION_NOT_SUPPORTED); } @@ -598,7 +633,8 @@ public class WebSphereUowTransactionManagerTests extends TestCase { assertFalse(manager.getRollbackOnly()); } - public void testExistingTransactionUsingPropagationNotSupported() { + @Test + public void existingTransactionUsingPropagationNotSupported() { MockUOWManager manager = new MockUOWManager(); final WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); diff --git a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java index c0c567c1d3..2c9c4d44fa 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java @@ -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,20 +19,22 @@ package org.springframework.transaction.support; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.util.SerializationTestUtils; -import static org.mockito.BDDMockito.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; /** * @author Rod Johnson */ -public class JtaTransactionManagerSerializationTests extends TestCase { +public class JtaTransactionManagerSerializationTests { - public void testSerializable() throws Exception { + @Test + public void serializable() throws Exception { UserTransaction ut1 = mock(UserTransaction.class); UserTransaction ut2 = mock(UserTransaction.class); TransactionManager tm = mock(TransactionManager.class); diff --git a/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java b/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java index a014f97f2b..c8a16a41c4 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/support/SimpleTransactionScopeTests.java @@ -32,6 +32,7 @@ import static org.junit.Assert.*; public class SimpleTransactionScopeTests { @Test + @SuppressWarnings("resource") public void getFromScope() throws Exception { GenericApplicationContext context = new GenericApplicationContext(); context.getBeanFactory().registerScope("tx", new SimpleTransactionScope()); diff --git a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java index 0d117c3719..4d212e4fec 100644 --- a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java @@ -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,9 +32,10 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import junit.framework.TestCase; import org.aopalliance.intercept.MethodInvocation; +import org.junit.Test; + import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; @@ -46,17 +47,21 @@ import org.springframework.remoting.support.RemoteInvocationResult; import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @since 09.08.2004 */ -public class HttpInvokerTests extends TestCase { +public class HttpInvokerTests { - public void testHttpInvokerProxyFactoryBeanAndServiceExporter() throws Throwable { + @Test + public void httpInvokerProxyFactoryBeanAndServiceExporter() throws Throwable { doTestHttpInvokerProxyFactoryBeanAndServiceExporter(false); } - public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithExplicitClassLoader() throws Throwable { + @Test + public void httpInvokerProxyFactoryBeanAndServiceExporterWithExplicitClassLoader() throws Throwable { doTestHttpInvokerProxyFactoryBeanAndServiceExporter(true); } @@ -126,7 +131,8 @@ public class HttpInvokerTests extends TestCase { } } - public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithIOException() throws Exception { + @Test + public void httpInvokerProxyFactoryBeanAndServiceExporterWithIOException() throws Exception { TestBean target = new TestBean("myname", 99); final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter(); @@ -158,7 +164,8 @@ public class HttpInvokerTests extends TestCase { } } - public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithGzipCompression() throws Throwable { + @Test + public void httpInvokerProxyFactoryBeanAndServiceExporterWithGzipCompression() throws Throwable { TestBean target = new TestBean("myname", 99); final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter() { @@ -242,7 +249,8 @@ public class HttpInvokerTests extends TestCase { } } - public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithWrappedInvocations() throws Throwable { + @Test + public void httpInvokerProxyFactoryBeanAndServiceExporterWithWrappedInvocations() throws Throwable { TestBean target = new TestBean("myname", 99); final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter() { @@ -321,7 +329,8 @@ public class HttpInvokerTests extends TestCase { } } - public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithInvocationAttributes() throws Exception { + @Test + public void httpInvokerProxyFactoryBeanAndServiceExporterWithInvocationAttributes() throws Exception { TestBean target = new TestBean("myname", 99); final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter(); @@ -383,7 +392,8 @@ public class HttpInvokerTests extends TestCase { assertEquals(99, proxy.getAge()); } - public void testHttpInvokerProxyFactoryBeanAndServiceExporterWithCustomInvocationObject() throws Exception { + @Test + public void httpInvokerProxyFactoryBeanAndServiceExporterWithCustomInvocationObject() throws Exception { TestBean target = new TestBean("myname", 99); final HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter(); @@ -434,7 +444,8 @@ public class HttpInvokerTests extends TestCase { assertEquals(99, proxy.getAge()); } - public void testHttpInvokerWithSpecialLocalMethods() throws Exception { + @Test + public void httpInvokerWithSpecialLocalMethods() throws Exception { String serviceUrl = "http://myurl"; HttpInvokerProxyFactoryBean pfb = new HttpInvokerProxyFactoryBean(); pfb.setServiceInterface(ITestBean.class); diff --git a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java index 40c65ba737..c12711dc23 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java @@ -100,7 +100,7 @@ public class WebRequestDataBinderIntegrationTests { @Test - public void testPartsBinding() { + public void partsBinding() { PartsBean bean = new PartsBean(); partsServlet.setBean(bean); @@ -117,7 +117,7 @@ public class WebRequestDataBinderIntegrationTests { } @Test - public void testPartListBinding() { + public void partListBinding() { PartListBean bean = new PartListBean(); partListServlet.setBean(bean); diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java index 6d9d28e0a7..550376b819 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestContextListenerTests.java @@ -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,18 +18,21 @@ package org.springframework.web.context.request; import javax.servlet.ServletRequestEvent; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.core.task.MockRunnable; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockServletContext; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller */ -public class RequestContextListenerTests extends TestCase { +public class RequestContextListenerTests { - public void testRequestContextListenerWithSameThread() { + @Test + public void requestContextListenerWithSameThread() { RequestContextListener listener = new RequestContextListener(); MockServletContext context = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(context); @@ -49,7 +52,8 @@ public class RequestContextListenerTests extends TestCase { assertTrue(runnable.wasExecuted()); } - public void testRequestContextListenerWithSameThreadAndAttributesGone() { + @Test + public void requestContextListenerWithSameThreadAndAttributesGone() { RequestContextListener listener = new RequestContextListener(); MockServletContext context = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(context); @@ -70,7 +74,8 @@ public class RequestContextListenerTests extends TestCase { assertTrue(runnable.wasExecuted()); } - public void testRequestContextListenerWithDifferentThread() { + @Test + public void requestContextListenerWithDifferentThread() { final RequestContextListener listener = new RequestContextListener(); final MockServletContext context = new MockServletContext(); final MockHttpServletRequest request = new MockHttpServletRequest(context); diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java index b044b8c2d6..fd01d40342 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java @@ -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,7 +16,9 @@ package org.springframework.web.context.request; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; @@ -29,18 +31,22 @@ import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller * @author Mark Fisher + * @author Sam Brannen + * @see SessionScopeTests */ -public class RequestScopeTests extends TestCase { +public class RequestScopeTests { - private DefaultListableBeanFactory beanFactory; + private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - @Override - protected void setUp() throws Exception { - this.beanFactory = new DefaultListableBeanFactory(); + + @Before + public void setUp() throws Exception { this.beanFactory.registerScope("request", new RequestScope()); this.beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver()); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); @@ -48,63 +54,57 @@ public class RequestScopeTests extends TestCase { this.beanFactory.preInstantiateSingletons(); } - public void testGetFromScope() throws Exception { + @After + public void resetRequestAttributes() { + RequestContextHolder.setRequestAttributes(null); + } + + @Test + public void getFromScope() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setContextPath("/path"); RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "requestScopedObject"; - assertNull(request.getAttribute(name)); - TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertEquals("/path", bean.getName()); - assertSame(bean, request.getAttribute(name)); - assertSame(bean, this.beanFactory.getBean(name)); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + String name = "requestScopedObject"; + assertNull(request.getAttribute(name)); + TestBean bean = (TestBean) this.beanFactory.getBean(name); + assertEquals("/path", bean.getName()); + assertSame(bean, request.getAttribute(name)); + assertSame(bean, this.beanFactory.getBean(name)); } - public void testDestructionAtRequestCompletion() throws Exception { + @Test + public void destructionAtRequestCompletion() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "requestScopedDisposableObject"; - assertNull(request.getAttribute(name)); - DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertSame(bean, request.getAttribute(name)); - assertSame(bean, this.beanFactory.getBean(name)); + String name = "requestScopedDisposableObject"; + assertNull(request.getAttribute(name)); + DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); + assertSame(bean, request.getAttribute(name)); + assertSame(bean, this.beanFactory.getBean(name)); - requestAttributes.requestCompleted(); - assertTrue(bean.wasDestroyed()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + requestAttributes.requestCompleted(); + assertTrue(bean.wasDestroyed()); } - public void testGetFromFactoryBeanInScope() throws Exception { + @Test + public void getFromFactoryBeanInScope() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "requestScopedFactoryBean"; - assertNull(request.getAttribute(name)); - TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertTrue(request.getAttribute(name) instanceof FactoryBean); - assertSame(bean, this.beanFactory.getBean(name)); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + String name = "requestScopedFactoryBean"; + assertNull(request.getAttribute(name)); + TestBean bean = (TestBean) this.beanFactory.getBean(name); + assertTrue(request.getAttribute(name) instanceof FactoryBean); + assertSame(bean, this.beanFactory.getBean(name)); } - public void testCircleLeadsToException() throws Exception { + @Test + public void circleLeadsToException() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); @@ -112,65 +112,54 @@ public class RequestScopeTests extends TestCase { try { String name = "requestScopedObjectCircle1"; assertNull(request.getAttribute(name)); + this.beanFactory.getBean(name); fail("Should have thrown BeanCreationException"); } catch (BeanCreationException ex) { - // expected assertTrue(ex.contains(BeanCurrentlyInCreationException.class)); } - finally { - RequestContextHolder.setRequestAttributes(null); - } } - public void testInnerBeanInheritsContainingBeanScopeByDefault() { + @Test + public void innerBeanInheritsContainingBeanScopeByDefault() { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String outerBeanName = "requestScopedOuterBean"; - assertNull(request.getAttribute(outerBeanName)); - TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertNotNull(request.getAttribute(outerBeanName)); - TestBean inner1 = (TestBean) outer1.getSpouse(); - assertSame(outer1, this.beanFactory.getBean(outerBeanName)); - requestAttributes.requestCompleted(); - assertTrue(outer1.wasDestroyed()); - assertTrue(inner1.wasDestroyed()); - request = new MockHttpServletRequest(); - requestAttributes = new ServletRequestAttributes(request); - RequestContextHolder.setRequestAttributes(requestAttributes); - TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertNotSame(outer1, outer2); - assertNotSame(inner1, outer2.getSpouse()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + String outerBeanName = "requestScopedOuterBean"; + assertNull(request.getAttribute(outerBeanName)); + TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName); + assertNotNull(request.getAttribute(outerBeanName)); + TestBean inner1 = (TestBean) outer1.getSpouse(); + assertSame(outer1, this.beanFactory.getBean(outerBeanName)); + requestAttributes.requestCompleted(); + assertTrue(outer1.wasDestroyed()); + assertTrue(inner1.wasDestroyed()); + request = new MockHttpServletRequest(); + requestAttributes = new ServletRequestAttributes(request); + RequestContextHolder.setRequestAttributes(requestAttributes); + TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName); + assertNotSame(outer1, outer2); + assertNotSame(inner1, outer2.getSpouse()); } - public void testRequestScopedInnerBeanDestroyedWhileContainedBySingleton() throws Exception { + @Test + public void requestScopedInnerBeanDestroyedWhileContainedBySingleton() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String outerBeanName = "singletonOuterBean"; - TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertNull(request.getAttribute(outerBeanName)); - TestBean inner1 = (TestBean) outer1.getSpouse(); - TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName); - assertSame(outer1, outer2); - assertSame(inner1, outer2.getSpouse()); - requestAttributes.requestCompleted(); - assertTrue(inner1.wasDestroyed()); - assertFalse(outer1.wasDestroyed()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + String outerBeanName = "singletonOuterBean"; + TestBean outer1 = (TestBean) this.beanFactory.getBean(outerBeanName); + assertNull(request.getAttribute(outerBeanName)); + TestBean inner1 = (TestBean) outer1.getSpouse(); + TestBean outer2 = (TestBean) this.beanFactory.getBean(outerBeanName); + assertSame(outer1, outer2); + assertSame(inner1, outer2.getSpouse()); + requestAttributes.requestCompleted(); + assertTrue(inner1.wasDestroyed()); + assertFalse(outer1.wasDestroyed()); } } diff --git a/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java index ead787e954..ab19823824 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java @@ -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,7 +18,9 @@ package org.springframework.web.context.request; import java.io.Serializable; -import junit.framework.TestCase; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanNameAware; @@ -32,74 +34,78 @@ import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller + * @author Sam Brannen + * @see RequestScopeTests */ -public class SessionScopeTests extends TestCase { +public class SessionScopeTests { - private DefaultListableBeanFactory beanFactory; + private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); - @Override - protected void setUp() throws Exception { - this.beanFactory = new DefaultListableBeanFactory(); + + @Before + public void setUp() throws Exception { this.beanFactory.registerScope("session", new SessionScope()); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory); reader.loadBeanDefinitions(new ClassPathResource("sessionScopeTests.xml", getClass())); } - public void testGetFromScope() throws Exception { + @After + public void resetRequestAttributes() { + RequestContextHolder.setRequestAttributes(null); + } + + @Test + public void getFromScope() throws Exception { MockHttpSession session = new MockHttpSession(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "sessionScopedObject"; - assertNull(session.getAttribute(name)); - TestBean bean = (TestBean) this.beanFactory.getBean(name); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + String name = "sessionScopedObject"; + assertNull(session.getAttribute(name)); + TestBean bean = (TestBean) this.beanFactory.getBean(name); + assertEquals(session.getAttribute(name), bean); + assertSame(bean, this.beanFactory.getBean(name)); } - public void testDestructionAtSessionTermination() throws Exception { + @Test + public void destructionAtSessionTermination() throws Exception { MockHttpSession session = new MockHttpSession(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "sessionScopedDisposableObject"; - assertNull(session.getAttribute(name)); - DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); + String name = "sessionScopedDisposableObject"; + assertNull(session.getAttribute(name)); + DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); + assertEquals(session.getAttribute(name), bean); + assertSame(bean, this.beanFactory.getBean(name)); - requestAttributes.requestCompleted(); - session.invalidate(); - assertTrue(bean.wasDestroyed()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + requestAttributes.requestCompleted(); + session.invalidate(); + assertTrue(bean.wasDestroyed()); } - public void testDestructionWithSessionSerialization() throws Exception { + @Test + public void destructionWithSessionSerialization() throws Exception { doTestDestructionWithSessionSerialization(false); } - public void testDestructionWithSessionSerializationAndBeanPostProcessor() throws Exception { + @Test + public void destructionWithSessionSerializationAndBeanPostProcessor() throws Exception { this.beanFactory.addBeanPostProcessor(new CustomDestructionAwareBeanPostProcessor()); doTestDestructionWithSessionSerialization(false); } - public void testDestructionWithSessionSerializationAndSerializableBeanPostProcessor() throws Exception { + @Test + public void destructionWithSessionSerializationAndSerializableBeanPostProcessor() throws Exception { this.beanFactory.addBeanPostProcessor(new CustomSerializableDestructionAwareBeanPostProcessor()); doTestDestructionWithSessionSerialization(true); } @@ -113,20 +119,15 @@ public class SessionScopeTests extends TestCase { ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "sessionScopedDisposableObject"; - assertNull(session.getAttribute(name)); - DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); + String name = "sessionScopedDisposableObject"; + assertNull(session.getAttribute(name)); + DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); + assertEquals(session.getAttribute(name), bean); + assertSame(bean, this.beanFactory.getBean(name)); - requestAttributes.requestCompleted(); - serializedState = session.serializeState(); - assertFalse(bean.wasDestroyed()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } + requestAttributes.requestCompleted(); + serializedState = session.serializeState(); + assertFalse(bean.wasDestroyed()); serializedState = (Serializable) SerializationTestUtils.serializeAndDeserialize(serializedState); @@ -137,26 +138,21 @@ public class SessionScopeTests extends TestCase { requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); - try { - String name = "sessionScopedDisposableObject"; - assertNotNull(session.getAttribute(name)); - DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name); - assertEquals(session.getAttribute(name), bean); - assertSame(bean, this.beanFactory.getBean(name)); + name = "sessionScopedDisposableObject"; + assertNotNull(session.getAttribute(name)); + bean = (DerivedTestBean) this.beanFactory.getBean(name); + assertEquals(session.getAttribute(name), bean); + assertSame(bean, this.beanFactory.getBean(name)); - requestAttributes.requestCompleted(); - session.invalidate(); - assertTrue(bean.wasDestroyed()); + requestAttributes.requestCompleted(); + session.invalidate(); + assertTrue(bean.wasDestroyed()); - if (beanNameReset) { - assertNull(bean.getBeanName()); - } - else { - assertNotNull(bean.getBeanName()); - } + if (beanNameReset) { + assertNull(bean.getBeanName()); } - finally { - RequestContextHolder.setRequestAttributes(null); + else { + assertNotNull(bean.getBeanName()); } } diff --git a/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java index 6091fa6a80..928bdd7513 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/CharacterEncodingFilterTests.java @@ -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,7 +20,7 @@ import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.test.MockFilterConfig; import org.springframework.mock.web.test.MockHttpServletResponse; @@ -33,14 +33,15 @@ import static org.mockito.BDDMockito.*; * @author Rick Evans * @author Juergen Hoeller */ -public class CharacterEncodingFilterTests extends TestCase { +public class CharacterEncodingFilterTests { private static final String FILTER_NAME = "boot"; private static final String ENCODING = "UTF-8"; - public void testForceAlwaysSetsEncoding() throws Exception { + @Test + public void forceEncodingAlwaysSetsEncoding() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); request.setCharacterEncoding(ENCODING); given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); @@ -61,7 +62,8 @@ public class CharacterEncodingFilterTests extends TestCase { verify(filterChain).doFilter(request, response); } - public void testEncodingIfEmptyAndNotForced() throws Exception { + @Test + public void encodingIfEmptyAndNotForced() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getCharacterEncoding()).willReturn(null); given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); @@ -83,7 +85,8 @@ public class CharacterEncodingFilterTests extends TestCase { verify(filterChain).doFilter(request, response); } - public void testDoesNowtIfEncodingIsNotEmptyAndNotForced() throws Exception { + @Test + public void doesNowtIfEncodingIsNotEmptyAndNotForced() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getCharacterEncoding()).willReturn(ENCODING); given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); @@ -103,7 +106,8 @@ public class CharacterEncodingFilterTests extends TestCase { verify(filterChain).doFilter(request, response); } - public void testWithBeanInitialization() throws Exception { + @Test + public void withBeanInitialization() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getCharacterEncoding()).willReturn(null); given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); @@ -125,7 +129,8 @@ public class CharacterEncodingFilterTests extends TestCase { verify(filterChain).doFilter(request, response); } - public void testWithIncompleteInitialization() throws Exception { + @Test + public void withIncompleteInitialization() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getCharacterEncoding()).willReturn(null); given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null); @@ -144,4 +149,5 @@ public class CharacterEncodingFilterTests extends TestCase { verify(request).removeAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX); verify(filterChain).doFilter(request, response); } + } diff --git a/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java b/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java index 5e303c7e9f..677a7e79a3 100644 --- a/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java +++ b/spring-web/src/test/java/org/springframework/web/filter/RequestContextFilterTests.java @@ -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. @@ -17,12 +17,13 @@ package org.springframework.web.filter; import java.io.IOException; + import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.test.MockFilterConfig; import org.springframework.mock.web.test.MockHttpServletRequest; @@ -31,21 +32,25 @@ import org.springframework.mock.web.test.MockServletContext; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller */ -public class RequestContextFilterTests extends TestCase { +public class RequestContextFilterTests { - public void testHappyPath() throws Exception { + @Test + public void happyPath() throws Exception { testFilterInvocation(null); } - public void testWithException() throws Exception { + @Test + public void withException() throws Exception { testFilterInvocation(new ServletException()); } - public void testFilterInvocation(final ServletException sex) throws Exception { + private void testFilterInvocation(final ServletException sex) throws Exception { final MockHttpServletRequest req = new MockHttpServletRequest(); req.setAttribute("myAttr", "myValue"); final MockHttpServletResponse resp = new MockHttpServletResponse(); diff --git a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java index 864fdb1b95..e7f111f297 100644 --- a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingNavigationHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 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,37 +19,35 @@ package org.springframework.web.jsf; import javax.faces.application.NavigationHandler; import javax.faces.context.FacesContext; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.StaticListableBeanFactory; +import static org.junit.Assert.*; + /** * @author Colin Sampaleanu * @author Juergen Hoeller */ -public class DelegatingNavigationHandlerTests extends TestCase { +public class DelegatingNavigationHandlerTests { - private MockFacesContext facesContext; - private StaticListableBeanFactory beanFactory; - private TestNavigationHandler origNavHandler; - private DelegatingNavigationHandlerProxy delNavHandler; + private final MockFacesContext facesContext = new MockFacesContext(); - @Override - protected void setUp() { - facesContext = new MockFacesContext(); - beanFactory = new StaticListableBeanFactory(); - origNavHandler = new TestNavigationHandler(); + private final StaticListableBeanFactory beanFactory = new StaticListableBeanFactory(); - delNavHandler = new DelegatingNavigationHandlerProxy(origNavHandler) { - @Override - protected BeanFactory getBeanFactory(FacesContext facesContext) { - return beanFactory; - } - }; - } + private final TestNavigationHandler origNavHandler = new TestNavigationHandler(); - public void testHandleNavigationWithoutDecoration() { + private final DelegatingNavigationHandlerProxy delNavHandler = new DelegatingNavigationHandlerProxy(origNavHandler) { + @Override + protected BeanFactory getBeanFactory(FacesContext facesContext) { + return beanFactory; + } + }; + + + @Test + public void handleNavigationWithoutDecoration() { TestNavigationHandler targetHandler = new TestNavigationHandler(); beanFactory.addBean("jsfNavigationHandler", targetHandler); @@ -58,7 +56,8 @@ public class DelegatingNavigationHandlerTests extends TestCase { assertEquals("myViewId", targetHandler.lastOutcome); } - public void testHandleNavigationWithDecoration() { + @Test + public void handleNavigationWithDecoration() { TestDecoratingNavigationHandler targetHandler = new TestDecoratingNavigationHandler(); beanFactory.addBean("jsfNavigationHandler", targetHandler); @@ -72,7 +71,7 @@ public class DelegatingNavigationHandlerTests extends TestCase { } - public static class TestNavigationHandler extends NavigationHandler { + static class TestNavigationHandler extends NavigationHandler { private String lastFromAction; private String lastOutcome; @@ -85,7 +84,7 @@ public class DelegatingNavigationHandlerTests extends TestCase { } - public static class TestDecoratingNavigationHandler extends DecoratingNavigationHandler { + static class TestDecoratingNavigationHandler extends DecoratingNavigationHandler { private String lastFromAction; private String lastOutcome; diff --git a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java index d74bf8a6ae..230b2c3f42 100644 --- a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java +++ b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingPhaseListenerTests.java @@ -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. @@ -21,36 +21,33 @@ import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.support.StaticListableBeanFactory; +import static org.junit.Assert.*; + /** * @author Colin Sampaleanu * @author Juergen Hoeller */ -public class DelegatingPhaseListenerTests extends TestCase { +public class DelegatingPhaseListenerTests { - private MockFacesContext facesContext; - private StaticListableBeanFactory beanFactory; - private DelegatingPhaseListenerMulticaster delPhaseListener; + private final MockFacesContext facesContext = new MockFacesContext(); + + private final StaticListableBeanFactory beanFactory = new StaticListableBeanFactory(); - @Override @SuppressWarnings("serial") - protected void setUp() { - facesContext = new MockFacesContext(); - beanFactory = new StaticListableBeanFactory(); + private final DelegatingPhaseListenerMulticaster delPhaseListener = new DelegatingPhaseListenerMulticaster() { + @Override + protected ListableBeanFactory getBeanFactory(FacesContext facesContext) { + return beanFactory; + } + }; - delPhaseListener = new DelegatingPhaseListenerMulticaster() { - @Override - protected ListableBeanFactory getBeanFactory(FacesContext facesContext) { - return beanFactory; - } - }; - } - - public void testBeforeAndAfterPhaseWithSingleTarget() { + @Test + public void beforeAndAfterPhaseWithSingleTarget() { TestListener target = new TestListener(); beanFactory.addBean("testListener", target); @@ -64,7 +61,8 @@ public class DelegatingPhaseListenerTests extends TestCase { assertTrue(target.afterCalled); } - public void testBeforeAndAfterPhaseWithMultipleTargets() { + @Test + public void beforeAndAfterPhaseWithMultipleTargets() { TestListener target1 = new TestListener(); TestListener target2 = new TestListener(); beanFactory.addBean("testListener1", target1); diff --git a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java index a3de4860ce..fdca3abc80 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/support/ByteArrayMultipartFileEditorTests.java @@ -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,33 +18,37 @@ package org.springframework.web.multipart.support; import java.io.IOException; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.web.multipart.MultipartFile; +import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; /** * @author Rick Evans + * @author Sam Brannen */ -public final class ByteArrayMultipartFileEditorTests extends TestCase { +public final class ByteArrayMultipartFileEditorTests { - public void testSetValueAsByteArray() throws Exception { - ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); + private final ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); + + @Test + public void setValueAsByteArray() throws Exception { String expectedValue = "Shumwere, shumhow, a shuck ish washing you. - Drunken Far Side"; editor.setValue(expectedValue.getBytes()); assertEquals(expectedValue, editor.getAsText()); } - public void testSetValueAsString() throws Exception { - ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); + @Test + public void setValueAsString() throws Exception { String expectedValue = "'Green Wing' - classic British comedy"; editor.setValue(expectedValue); assertEquals(expectedValue, editor.getAsText()); } - public void testSetValueAsCustomObjectInvokesToString() throws Exception { - ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); + @Test + public void setValueAsCustomObjectInvokesToString() throws Exception { final String expectedValue = "'Green Wing' - classic British comedy"; Object object = new Object() { @Override @@ -52,35 +56,31 @@ public final class ByteArrayMultipartFileEditorTests extends TestCase { return expectedValue; } }; + editor.setValue(object); assertEquals(expectedValue, editor.getAsText()); } - public void testSetValueAsNullGetsBackEmptyString() throws Exception { - ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); + @Test + public void setValueAsNullGetsBackEmptyString() throws Exception { editor.setValue(null); assertEquals("", editor.getAsText()); } - public void testSetValueAsMultipartFile() throws Exception { + @Test + public void setValueAsMultipartFile() throws Exception { String expectedValue = "That is comforting to know"; - ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); MultipartFile file = mock(MultipartFile.class); given(file.getBytes()).willReturn(expectedValue.getBytes()); editor.setValue(file); assertEquals(expectedValue, editor.getAsText()); } - public void testSetValueAsMultipartFileWithBadBytes() throws Exception { - ByteArrayMultipartFileEditor editor = new ByteArrayMultipartFileEditor(); + @Test(expected = IllegalArgumentException.class) + public void setValueAsMultipartFileWithBadBytes() throws Exception { MultipartFile file = mock(MultipartFile.class); given(file.getBytes()).willThrow(new IOException()); - try { - editor.setValue(file); - fail("Must have thrown an IllegalArgumentException: IOException thrown when reading MultipartFile bytes"); - } - catch (IllegalArgumentException expected) { - } + editor.setValue(file); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java index d99733d26c..0aa92526e2 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java @@ -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. @@ -23,7 +23,8 @@ import javax.portlet.PortletException; import javax.portlet.PortletMode; import javax.portlet.PortletSecurityException; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; @@ -44,24 +45,24 @@ import org.springframework.web.portlet.multipart.PortletMultipartResolver; import org.springframework.web.servlet.ViewRendererServlet; import org.springframework.web.servlet.view.InternalResourceView; +import static org.junit.Assert.*; + /** * @author Mark Fisher * @author Juergen Hoeller * @author Dan McCallum */ -public class DispatcherPortletTests extends TestCase { +public class DispatcherPortletTests { - private MockPortletConfig complexPortletConfig; + private final MockPortletConfig complexPortletConfig = new MockPortletConfig(new MockPortletContext(), "complex"); - private DispatcherPortlet complexDispatcherPortlet; + private final DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet(); - @Override - protected void setUp() throws PortletException { - complexPortletConfig = new MockPortletConfig(new MockPortletContext(), "complex"); + @Before + public void setUp() throws PortletException { complexPortletConfig.addInitParameter("publishContext", "false"); - complexDispatcherPortlet = new DispatcherPortlet(); complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class); complexDispatcherPortlet.setNamespace("test"); complexDispatcherPortlet.addRequiredProperty("publishContext"); @@ -73,14 +74,16 @@ public class DispatcherPortletTests extends TestCase { } - public void testDispatcherPortletGetPortletNameDoesNotFailWithoutConfig() { + @Test + public void dispatcherPortletGetPortletNameDoesNotFailWithoutConfig() { DispatcherPortlet dp = new DispatcherPortlet(); assertEquals(null, dp.getPortletConfig()); assertEquals(null, dp.getPortletName()); assertEquals(null, dp.getPortletContext()); } - public void testDispatcherPortlets() { + @Test + public void dispatcherPortlets() { assertTrue("Correct namespace", "test".equals(complexDispatcherPortlet.getNamespace())); assertTrue("Correct attribute", (FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "complex").equals(complexDispatcherPortlet.getPortletContextAttributeName())); @@ -88,7 +91,8 @@ public class DispatcherPortletTests extends TestCase { getPortletContext().getAttribute(FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "complex") == null); } - public void testPortletModeParameterMappingHelp1() throws Exception { + @Test + public void portletModeParameterMappingHelp1() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.HELP); @@ -98,7 +102,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("help1 was here", param); } - public void testPortletModeParameterMappingHelp2() throws Exception { + @Test + public void portletModeParameterMappingHelp2() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.HELP); @@ -108,7 +113,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("help2 was here", param); } - public void testPortletModeParameterMappingInvalidHelpActionRequest() throws Exception { + @Test + public void portletModeParameterMappingInvalidHelpActionRequest() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.HELP); @@ -119,7 +125,8 @@ public class DispatcherPortletTests extends TestCase { assertTrue(exceptionParam.startsWith(NoHandlerFoundException.class.getName())); } - public void testPortletModeParameterMappingInvalidHelpRenderRequest() throws Exception { + @Test + public void portletModeParameterMappingInvalidHelpRenderRequest() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.HELP); @@ -131,7 +138,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-unavailable", view.getBeanName()); } - public void testPortletModeMappingValidEditActionRequest() throws Exception { + @Test + public void portletModeMappingValidEditActionRequest() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.EDIT); @@ -142,7 +150,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("edit was here", response.getRenderParameter("param")); } - public void testPortletModeMappingEditActionRequestWithUnauthorizedUserRole() throws Exception { + @Test + public void portletModeMappingEditActionRequestWithUnauthorizedUserRole() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.EDIT); @@ -156,7 +165,8 @@ public class DispatcherPortletTests extends TestCase { assertTrue(exception.startsWith(name)); } - public void testPortletModeMappingValidViewRenderRequest() throws Exception { + @Test + public void portletModeMappingValidViewRenderRequest() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.VIEW); @@ -170,7 +180,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("someViewName", view.getBeanName()); } - public void testPortletModeMappingViewRenderRequestWithUnauthorizedUserRole() throws Exception { + @Test + public void portletModeMappingViewRenderRequestWithUnauthorizedUserRole() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.VIEW); @@ -186,7 +197,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-default-1", view.getBeanName()); } - public void testParameterMappingValidActionRequest() throws Exception { + @Test + public void parameterMappingValidActionRequest() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.EDIT); @@ -196,7 +208,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("test1-action", response.getRenderParameter("result")); } - public void testParameterMappingValidRenderRequest() throws Exception { + @Test + public void parameterMappingValidRenderRequest() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.VIEW); @@ -206,7 +219,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("test2-view", response.getProperty("result")); } - public void testUnknownHandlerActionRequest() throws Exception { + @Test + public void unknownHandlerActionRequest() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setParameter("myParam", "unknown"); @@ -217,7 +231,8 @@ public class DispatcherPortletTests extends TestCase { assertTrue(exceptionParam.indexOf("No adapter for handler") != -1); } - public void testUnknownHandlerRenderRequest() throws Exception { + @Test + public void unknownHandlerRenderRequest() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "unknown"); @@ -230,7 +245,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-default-1", view.getBeanName()); } - public void testNoDetectAllHandlerMappingsWithPortletModeActionRequest() throws Exception { + @Test + public void noDetectAllHandlerMappingsWithPortletModeActionRequest() throws Exception { DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet(); complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class); complexDispatcherPortlet.setNamespace("test"); @@ -245,7 +261,8 @@ public class DispatcherPortletTests extends TestCase { assertTrue(exceptionParam.startsWith(NoHandlerFoundException.class.getName())); } - public void testNoDetectAllHandlerMappingsWithParameterRenderRequest() throws Exception { + @Test + public void noDetectAllHandlerMappingsWithParameterRenderRequest() throws Exception { DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet(); complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class); complexDispatcherPortlet.setNamespace("test"); @@ -262,7 +279,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-unavailable", view.getBeanName()); } - public void testExistingMultipartRequest() throws Exception { + @Test + public void existingMultipartRequest() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.EDIT); @@ -275,7 +293,8 @@ public class DispatcherPortletTests extends TestCase { assertNotNull(request.getAttribute("cleanedUp")); } - public void testMultipartResolutionFailed() throws Exception { + @Test + public void multipartResolutionFailed() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.EDIT); @@ -286,7 +305,8 @@ public class DispatcherPortletTests extends TestCase { assertTrue(exception.startsWith(MaxUploadSizeExceededException.class.getName())); } - public void testActionRequestHandledEvent() throws Exception { + @Test + public void actionRequestHandledEvent() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); complexDispatcherPortlet.processAction(request, response); @@ -296,7 +316,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals(1, listener.counter); } - public void testRenderRequestHandledEvent() throws Exception { + @Test + public void renderRequestHandledEvent() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); complexDispatcherPortlet.doDispatch(request, response); @@ -306,7 +327,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals(1, listener.counter); } - public void testPublishEventsOff() throws Exception { + @Test + public void publishEventsOff() throws Exception { complexDispatcherPortlet.setPublishEvents(false); MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); @@ -318,7 +340,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals(0, listener.counter); } - public void testCorrectLocaleInRequest() throws Exception { + @Test + public void correctLocaleInRequest() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "requestLocaleChecker"); @@ -327,7 +350,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("locale-ok", response.getContentAsString()); } - public void testIncorrectLocaleInRequest() throws Exception { + @Test + public void incorrectLocaleInRequest() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "requestLocaleChecker"); @@ -341,7 +365,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-default-1", view.getBeanName()); } - public void testCorrectLocaleInLocaleContextHolder() throws Exception { + @Test + public void correctLocaleInLocaleContextHolder() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "contextLocaleChecker"); @@ -350,7 +375,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("locale-ok", response.getContentAsString()); } - public void testIncorrectLocaleInLocalContextHolder() throws Exception { + @Test + public void incorrectLocaleInLocalContextHolder() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "contextLocaleChecker"); @@ -364,7 +390,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-default-1", view.getBeanName()); } - public void testHandlerInterceptorNoAbort() throws Exception { + @Test + public void handlerInterceptorNoAbort() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.VIEW); @@ -379,7 +406,8 @@ public class DispatcherPortletTests extends TestCase { assertTrue(request.getAttribute("test2-remove-after") == null); } - public void testHandlerInterceptorAbort() throws Exception { + @Test + public void handlerInterceptorAbort() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.VIEW); @@ -394,7 +422,8 @@ public class DispatcherPortletTests extends TestCase { assertTrue(request.getAttribute("test2-remove-after") == null); } - public void testHandlerInterceptorNotClearingModelAndView() throws Exception { + @Test + public void handlerInterceptorNotClearingModelAndView() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.VIEW); @@ -407,7 +436,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("someViewName", view.getBeanName()); } - public void testHandlerInterceptorClearingModelAndView() throws Exception { + @Test + public void handlerInterceptorClearingModelAndView() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setPortletMode(PortletMode.VIEW); @@ -420,7 +450,8 @@ public class DispatcherPortletTests extends TestCase { assertNull(view); } - public void testParameterMappingInterceptorWithCorrectParam() throws Exception { + @Test + public void parameterMappingInterceptorWithCorrectParam() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.VIEW); @@ -430,7 +461,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("test1", response.getRenderParameter("interceptingParam")); } - public void testParameterMappingInterceptorWithIncorrectParam() throws Exception { + @Test + public void parameterMappingInterceptorWithIncorrectParam() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setPortletMode(PortletMode.VIEW); @@ -441,7 +473,8 @@ public class DispatcherPortletTests extends TestCase { assertNull(response.getRenderParameter("interceptingParam")); } - public void testPortletHandlerAdapterActionRequest() throws Exception { + @Test + public void portletHandlerAdapterActionRequest() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setParameter("myParam", "myPortlet"); @@ -456,7 +489,8 @@ public class DispatcherPortletTests extends TestCase { assertNull(myPortlet.getPortletConfig()); } - public void testPortletHandlerAdapterRenderRequest() throws Exception { + @Test + public void portletHandlerAdapterRenderRequest() throws Exception { MockRenderRequest request = new MockRenderRequest(); MockRenderResponse response = new MockRenderResponse(); request.setParameter("myParam", "myPortlet"); @@ -473,7 +507,8 @@ public class DispatcherPortletTests extends TestCase { assertNull(myPortlet.getPortletConfig()); } - public void testModelAndViewDefiningExceptionInMappedHandler() throws Exception { + @Test + public void modelAndViewDefiningExceptionInMappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception1"); @@ -484,7 +519,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-modelandview", view.getBeanName()); } - public void testModelAndViewDefiningExceptionInUnmappedHandler() throws Exception { + @Test + public void modelAndViewDefiningExceptionInUnmappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception2"); @@ -495,7 +531,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-modelandview", view.getBeanName()); } - public void testIllegalAccessExceptionInMappedHandler() throws Exception { + @Test + public void illegalAccessExceptionInMappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception1"); @@ -506,7 +543,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-exception", view.getBeanName()); } - public void testIllegalAccessExceptionInUnmappedHandler() throws Exception { + @Test + public void illegalAccessExceptionInUnmappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception2"); @@ -517,7 +555,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-illegalaccess", view.getBeanName()); } - public void testPortletRequestBindingExceptionInMappedHandler() throws Exception { + @Test + public void portletRequestBindingExceptionInMappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception1"); @@ -528,7 +567,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-exception", view.getBeanName()); } - public void testPortletRequestBindingExceptionInUnmappedHandler() throws Exception { + @Test + public void portletRequestBindingExceptionInUnmappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception2"); @@ -539,7 +579,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-binding", view.getBeanName()); } - public void testIllegalArgumentExceptionInMappedHandler() throws Exception { + @Test + public void illegalArgumentExceptionInMappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception1"); @@ -550,7 +591,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-runtime", view.getBeanName()); } - public void testIllegalArgumentExceptionInUnmappedHandler() throws Exception { + @Test + public void illegalArgumentExceptionInUnmappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception2"); @@ -561,7 +603,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-default-1", view.getBeanName()); } - public void testExceptionInMappedHandler() throws Exception { + @Test + public void exceptionInMappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception1"); @@ -572,7 +615,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-exception", view.getBeanName()); } - public void testExceptionInUnmappedHandler() throws Exception { + @Test + public void exceptionInUnmappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception2"); @@ -583,7 +627,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-default-1", view.getBeanName()); } - public void testRuntimeExceptionInMappedHandler() throws Exception { + @Test + public void runtimeExceptionInMappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception1"); @@ -594,7 +639,8 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-runtime", view.getBeanName()); } - public void testRuntimeExceptionInUnmappedHandler() throws Exception { + @Test + public void runtimeExceptionInUnmappedHandler() throws Exception { MockRenderRequest request = new MockRenderRequest(); request.setPortletMode(PortletMode.HELP); request.addParameter("myParam", "exception2"); @@ -605,23 +651,27 @@ public class DispatcherPortletTests extends TestCase { assertEquals("failed-default-1", view.getBeanName()); } - public void testGetMessage() { + @Test + public void getMessage() { String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test", null, Locale.ENGLISH); assertEquals("test message", message); } - public void testGetMessageOtherLocale() { + @Test + public void getMessageOtherLocale() { String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test", null, Locale.CANADA); assertEquals("Canadian & test message", message); } - public void testGetMessageWithArgs() { + @Test + public void getMessageWithArgs() { Object[] args = new String[] {"this", "that"}; String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test.args", args, Locale.ENGLISH); assertEquals("test this and that", message); } - public void testPortletApplicationContextLookup() { + @Test + public void portletApplicationContextLookup() { MockPortletContext portletContext = new MockPortletContext(); ApplicationContext ac = PortletApplicationContextUtils.getWebApplicationContext(portletContext); assertNull(ac); @@ -643,7 +693,8 @@ public class DispatcherPortletTests extends TestCase { } } - public void testDispatcherPortletRefresh() throws PortletException { + @Test + public void dispatcherPortletRefresh() throws PortletException { MockPortletContext portletContext = new MockPortletContext("org/springframework/web/portlet/context"); DispatcherPortlet portlet = new DispatcherPortlet(); @@ -673,7 +724,8 @@ public class DispatcherPortletTests extends TestCase { portlet.destroy(); } - public void testDispatcherPortletContextRefresh() throws PortletException { + @Test + public void dispatcherPortletContextRefresh() throws PortletException { MockPortletContext portletContext = new MockPortletContext("org/springframework/web/portlet/context"); DispatcherPortlet portlet = new DispatcherPortlet(); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java index 7028c8bb33..19766ef882 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java @@ -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,24 @@ package org.springframework.web.portlet; import javax.portlet.PortletContext; import javax.portlet.PortletException; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockPortletConfig; import org.springframework.mock.web.portlet.MockPortletContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher */ -public class GenericPortletBeanTests extends TestCase { +public class GenericPortletBeanTests { - public void testInitParameterSet() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + private final PortletContext portletContext = new MockPortletContext(); + + private final MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + + @Test + public void initParameterSet() throws Exception { String testValue = "testValue"; portletConfig.addInitParameter("testParam", testValue); TestPortletBean portletBean = new TestPortletBean(); @@ -41,18 +46,16 @@ public class GenericPortletBeanTests extends TestCase { assertEquals(testValue, portletBean.getTestParam()); } - public void testInitParameterNotSet() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void initParameterNotSet() throws Exception { TestPortletBean portletBean = new TestPortletBean(); assertNull(portletBean.getTestParam()); portletBean.init(portletConfig); assertNull(portletBean.getTestParam()); } - public void testMultipleInitParametersSet() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void multipleInitParametersSet() throws Exception { String testValue = "testValue"; String anotherValue = "anotherValue"; portletConfig.addInitParameter("testParam", testValue); @@ -68,9 +71,8 @@ public class GenericPortletBeanTests extends TestCase { assertEquals(anotherValue, portletBean.getAnotherParam()); } - public void testMultipleInitParametersOnlyOneSet() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void multipleInitParametersOnlyOneSet() throws Exception { String testValue = "testValue"; portletConfig.addInitParameter("testParam", testValue); portletConfig.addInitParameter("unknownParam", "unknownValue"); @@ -83,9 +85,8 @@ public class GenericPortletBeanTests extends TestCase { assertNull(portletBean.getAnotherParam()); } - public void testRequiredInitParameterSet() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void requiredInitParameterSet() throws Exception { String testParam = "testParam"; String testValue = "testValue"; portletConfig.addInitParameter(testParam, testValue); @@ -97,9 +98,8 @@ public class GenericPortletBeanTests extends TestCase { assertEquals(testValue, portletBean.getTestParam()); } - public void testRequiredInitParameterNotSet() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void requiredInitParameterNotSet() throws Exception { String testParam = "testParam"; TestPortletBean portletBean = new TestPortletBean(); portletBean.addRequiredProperty(testParam); @@ -113,9 +113,8 @@ public class GenericPortletBeanTests extends TestCase { } } - public void testRequiredInitParameterNotSetOtherParameterNotSet() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void requiredInitParameterNotSetOtherParameterNotSet() throws Exception { String testParam = "testParam"; String testValue = "testValue"; portletConfig.addInitParameter(testParam, testValue); @@ -132,9 +131,8 @@ public class GenericPortletBeanTests extends TestCase { assertNull(portletBean.getTestParam()); } - public void testUnknownRequiredInitParameter() throws Exception { - PortletContext portletContext = new MockPortletContext(); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void unknownRequiredInitParameter() throws Exception { String testParam = "testParam"; String testValue = "testValue"; portletConfig.addInitParameter(testParam, testValue); @@ -152,6 +150,7 @@ public class GenericPortletBeanTests extends TestCase { } + @SuppressWarnings("unused") private static class TestPortletBean extends GenericPortletBean { private String testParam; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java index 032faf3a73..29725a79e5 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java @@ -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. @@ -23,7 +23,7 @@ import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.StringArrayPropertyEditor; @@ -32,15 +32,20 @@ import org.springframework.tests.sample.beans.ITestBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BindingResult; +import static org.junit.Assert.*; + /** * @author Mark Fisher */ -public class PortletRequestDataBinderTests extends TestCase { +public class PortletRequestDataBinderTests { - public void testSimpleBind() { - TestBean bean = new TestBean(); + private final MockPortletRequest request = new MockPortletRequest(); + + private final TestBean bean = new TestBean(); + + @Test + public void simpleBind() { - MockPortletRequest request = new MockPortletRequest(); request.addParameter("age", "35"); request.addParameter("name", "test"); @@ -51,11 +56,10 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals("test", bean.getName()); } - public void testNestedBind() { - TestBean bean = new TestBean(); + @Test + public void nestedBind() { bean.setSpouse(new TestBean()); - MockPortletRequest request = new MockPortletRequest(); request.addParameter("spouse.name", "test"); PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); @@ -65,9 +69,8 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals("test", bean.getSpouse().getName()); } - public void testNestedBindWithPropertyEditor() { - TestBean bean = new TestBean(); - + @Test + public void nestedBindWithPropertyEditor() { PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() { @Override @@ -76,7 +79,6 @@ public class PortletRequestDataBinderTests extends TestCase { } }); - MockPortletRequest request = new MockPortletRequest(); request.addParameter("spouse", "test"); request.addParameter("spouse.age", "32"); binder.bind(request); @@ -86,11 +88,10 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals(32, bean.getSpouse().getAge()); } - public void testBindingMismatch() { - TestBean bean = new TestBean(); + @Test + public void bindingMismatch() { bean.setAge(30); - MockPortletRequest request = new MockPortletRequest(); request.addParameter("age", "zzz"); PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); @@ -102,10 +103,8 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals(30, bean.getAge()); } - public void testBindingStringWithCommaSeparatedValue() throws Exception { - TestBean bean = new TestBean(); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void bindingStringWithCommaSeparatedValue() throws Exception { request.addParameter("stringArray", "test1,test2"); PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); @@ -116,10 +115,8 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals("test1,test2", bean.getStringArray()[0]); } - public void testBindingStringArrayWithSplitting() { - TestBean bean = new TestBean(); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void bindingStringArrayWithSplitting() { request.addParameter("stringArray", "test1,test2"); PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); @@ -132,10 +129,8 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals("test2", bean.getStringArray()[1]); } - public void testBindingList() { - TestBean bean = new TestBean(); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void bindingList() { request.addParameter("someList[0]", "test1"); request.addParameter("someList[1]", "test2"); @@ -148,10 +143,8 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals("test2", bean.getSomeList().get(1)); } - public void testBindingMap() { - TestBean bean = new TestBean(); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void bindingMap() { request.addParameter("someMap['key1']", "val1"); request.addParameter("someMap['key2']", "val2"); @@ -164,14 +157,13 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals("val2", bean.getSomeMap().get("key2")); } - public void testBindingSet() { - TestBean bean = new TestBean(); + @Test + public void bindingSet() { Set set = new LinkedHashSet(2); set.add(new TestBean("test1")); set.add(new TestBean("test2")); bean.setSomeSet(set); - MockPortletRequest request = new MockPortletRequest(); request.addParameter("someSet[0].age", "35"); request.addParameter("someSet[1].age", "36"); @@ -192,12 +184,11 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals(36, bean2.getAge()); } - public void testBindingDate() throws Exception { - TestBean bean = new TestBean(); + @Test + public void bindingDate() throws Exception { SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date expected = dateFormat.parse("06-03-2006"); - MockPortletRequest request = new MockPortletRequest(); request.addParameter("date", "06-03-2006"); PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); @@ -207,12 +198,11 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals(expected, bean.getDate()); } - public void testBindingFailsWhenMissingRequiredParam() { - TestBean bean = new TestBean(); + @Test + public void bindingFailsWhenMissingRequiredParam() { PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); binder.setRequiredFields(new String[] {"age", "name"}); - MockPortletRequest request = new MockPortletRequest(); request.addParameter("age", "35"); binder.bind(request); @@ -221,12 +211,11 @@ public class PortletRequestDataBinderTests extends TestCase { assertEquals("required", error.getFieldError("name").getCode()); } - public void testBindingExcludesDisallowedParam() { - TestBean bean = new TestBean(); + @Test + public void bindingExcludesDisallowedParam() { PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); binder.setAllowedFields(new String[] {"age"}); - MockPortletRequest request = new MockPortletRequest(); request.addParameter("age", "35"); request.addParameter("name", "test"); binder.bind(request); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java index 94dfaf3f3b..405f12060e 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java @@ -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,30 +16,34 @@ package org.springframework.web.portlet.bind; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockPortletRequest; +import static org.junit.Assert.*; + /** * @author Mark Fisher */ -public class PortletRequestParameterPropertyValuesTests extends TestCase { +public class PortletRequestParameterPropertyValuesTests { - public void testWithNoParams() { - MockPortletRequest request = new MockPortletRequest(); + private final MockPortletRequest request = new MockPortletRequest(); + + @Test + public void withNoParams() { PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request); assertTrue("Should not have any property values", pvs.getPropertyValues().length == 0); } - public void testWithNoPrefix() { - MockPortletRequest request = new MockPortletRequest(); + @Test + public void withNoPrefix() { request.addParameter("param", "value"); PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request); assertEquals("value", pvs.getPropertyValue("param").getValue()); } - public void testWithPrefix() { - MockPortletRequest request = new MockPortletRequest(); + @Test + public void withPrefix() { request.addParameter("test_param", "value"); PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request, "test"); assertTrue(pvs.contains("param")); @@ -47,8 +51,8 @@ public class PortletRequestParameterPropertyValuesTests extends TestCase { assertEquals("value", pvs.getPropertyValue("param").getValue()); } - public void testWithPrefixAndOverridingSeparator() { - MockPortletRequest request = new MockPortletRequest(); + @Test + public void withPrefixAndOverridingSeparator() { request.addParameter("test.param", "value"); request.addParameter("test_another", "anotherValue"); request.addParameter("some.other", "someValue"); @@ -61,4 +65,5 @@ public class PortletRequestParameterPropertyValuesTests extends TestCase { assertTrue(pvs.contains("param")); assertEquals("value", pvs.getPropertyValue("param").getValue()); } + } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java index 79f3fb7801..9a9158fcff 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java @@ -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,6 +18,7 @@ package org.springframework.web.portlet.context; import javax.servlet.ServletException; +import org.junit.Test; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.AbstractApplicationContextTests; @@ -26,6 +27,8 @@ import org.springframework.context.TestListener; import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.context.ConfigurableWebApplicationContext; +import static org.junit.Assert.*; + /** * Should ideally be eliminated. Copied when splitting .testsuite up into individual bundles. * @@ -53,13 +56,15 @@ public abstract class AbstractXmlWebApplicationContextTests extends AbstractAppl }; + @Test @Override - public void testCount() { + public void count() { assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(), this.applicationContext.getBeanDefinitionCount() == 14); } - 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")); @@ -74,7 +79,8 @@ public abstract class AbstractXmlWebApplicationContextTests extends AbstractAppl 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); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java index 2f526c27e8..0b371b306f 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java @@ -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,90 +19,90 @@ package org.springframework.web.portlet.context; import javax.portlet.PortletConfig; import javax.portlet.PortletContext; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockPortletConfig; import org.springframework.mock.web.portlet.MockPortletContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher + * @author Sam Brannen */ -public class PortletContextAwareProcessorTests extends TestCase { +public class PortletContextAwareProcessorTests { - public void testPortletContextAwareWithPortletContext() { - PortletContext portletContext = new MockPortletContext(); - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext); - PortletContextAwareBean bean = new PortletContextAwareBean(); + private final PortletContext portletContext = new MockPortletContext(); + + private final PortletConfig portletConfig = new MockPortletConfig(portletContext); + + private final PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext); + + private final PortletContextAwareBean bean = new PortletContextAwareBean(); + + + @Test + public void portletContextAwareWithPortletContext() { assertNull(bean.getPortletContext()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNotNull("PortletContext should have been set", bean.getPortletContext()); assertEquals(portletContext, bean.getPortletContext()); } - public void testPortletContextAwareWithPortletConfig() { - PortletContext portletContext = new MockPortletContext(); - PortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void portletContextAwareWithPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig); - PortletContextAwareBean bean = new PortletContextAwareBean(); assertNull(bean.getPortletContext()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNotNull("PortletContext should have been set", bean.getPortletContext()); assertEquals(portletContext, bean.getPortletContext()); } - public void testPortletContextAwareWithPortletContextAndPortletConfig() { - PortletContext portletContext = new MockPortletContext(); - PortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void portletContextAwareWithPortletContextAndPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig); - PortletContextAwareBean bean = new PortletContextAwareBean(); assertNull(bean.getPortletContext()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNotNull("PortletContext should have been set", bean.getPortletContext()); assertEquals(portletContext, bean.getPortletContext()); } - public void testPortletContextAwareWithNullPortletContextAndNonNullPortletConfig() { - PortletContext portletContext = new MockPortletContext(); - PortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void portletContextAwareWithNullPortletContextAndNonNullPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig); - PortletContextAwareBean bean = new PortletContextAwareBean(); assertNull(bean.getPortletContext()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNotNull("PortletContext should have been set", bean.getPortletContext()); assertEquals(portletContext, bean.getPortletContext()); } - public void testPortletContextAwareWithNonNullPortletContextAndNullPortletConfig() { - PortletContext portletContext = new MockPortletContext(); + @Test + public void portletContextAwareWithNonNullPortletContextAndNullPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null); - PortletContextAwareBean bean = new PortletContextAwareBean(); assertNull(bean.getPortletContext()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNotNull("PortletContext should have been set", bean.getPortletContext()); assertEquals(portletContext, bean.getPortletContext()); } - public void testPortletContextAwareWithNullPortletContext() { - PortletContext portletContext = null; - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext); - PortletContextAwareBean bean = new PortletContextAwareBean(); + @Test + public void portletContextAwareWithNullPortletContext() { + PortletContextAwareProcessor processor = new PortletContextAwareProcessor((PortletContext) null); assertNull(bean.getPortletContext()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNull(bean.getPortletContext()); } - public void testPortletConfigAwareWithPortletContextOnly() { - PortletContext portletContext = new MockPortletContext(); - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext); + @Test + public void portletConfigAwareWithPortletContextOnly() { PortletConfigAwareBean bean = new PortletConfigAwareBean(); assertNull(bean.getPortletConfig()); processor.postProcessBeforeInitialization(bean, "testBean"); assertNull(bean.getPortletConfig()); } - public void testPortletConfigAwareWithPortletConfig() { - PortletContext portletContext = new MockPortletContext(); - PortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void portletConfigAwareWithPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig); PortletConfigAwareBean bean = new PortletConfigAwareBean(); assertNull(bean.getPortletConfig()); @@ -111,9 +111,8 @@ public class PortletContextAwareProcessorTests extends TestCase { assertEquals(portletConfig, bean.getPortletConfig()); } - public void testPortletConfigAwareWithPortletContextAndPortletConfig() { - PortletContext portletContext = new MockPortletContext(); - PortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void portletConfigAwareWithPortletContextAndPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig); PortletConfigAwareBean bean = new PortletConfigAwareBean(); assertNull(bean.getPortletConfig()); @@ -122,9 +121,8 @@ public class PortletContextAwareProcessorTests extends TestCase { assertEquals(portletConfig, bean.getPortletConfig()); } - public void testPortletConfigAwareWithNullPortletContextAndNonNullPortletConfig() { - PortletContext portletContext = new MockPortletContext(); - PortletConfig portletConfig = new MockPortletConfig(portletContext); + @Test + public void portletConfigAwareWithNullPortletContextAndNonNullPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig); PortletConfigAwareBean bean = new PortletConfigAwareBean(); assertNull(bean.getPortletConfig()); @@ -133,8 +131,8 @@ public class PortletContextAwareProcessorTests extends TestCase { assertEquals(portletConfig, bean.getPortletConfig()); } - public void testPortletConfigAwareWithNonNullPortletContextAndNullPortletConfig() { - PortletContext portletContext = new MockPortletContext(); + @Test + public void portletConfigAwareWithNonNullPortletContextAndNullPortletConfig() { PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null); PortletConfigAwareBean bean = new PortletConfigAwareBean(); assertNull(bean.getPortletConfig()); @@ -142,9 +140,9 @@ public class PortletContextAwareProcessorTests extends TestCase { assertNull(bean.getPortletConfig()); } - public void testPortletConfigAwareWithNullPortletContext() { - PortletContext portletContext = null; - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext); + @Test + public void portletConfigAwareWithNullPortletContext() { + PortletContextAwareProcessor processor = new PortletContextAwareProcessor((PortletContext) null); PortletConfigAwareBean bean = new PortletConfigAwareBean(); assertNull(bean.getPortletConfig()); processor.postProcessBeforeInitialization(bean, "testBean"); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java index 85f90606f4..67a4530e63 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java @@ -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,9 +17,12 @@ package org.springframework.web.portlet.context; import java.util.Locale; + import javax.portlet.PortletConfig; import javax.portlet.PortletContext; +import org.junit.Test; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; @@ -30,6 +33,8 @@ import org.springframework.mock.web.portlet.MockPortletConfig; import org.springframework.mock.web.portlet.MockPortletContext; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller @@ -80,7 +85,9 @@ public class XmlPortletApplicationContextTests extends AbstractXmlWebApplication * Overridden in order to use MockPortletConfig * @see org.springframework.web.context.XmlWebApplicationContextTests#testWithoutMessageSource() */ - public void testWithoutMessageSource() throws Exception { + @Test + @SuppressWarnings("resource") + public void withoutMessageSource() throws Exception { MockPortletContext portletContext = new MockPortletContext(""); MockPortletConfig portletConfig = new MockPortletConfig(portletContext); XmlPortletApplicationContext pac = new XmlPortletApplicationContext(); @@ -97,15 +104,17 @@ public class XmlPortletApplicationContextTests extends AbstractXmlWebApplication // expected; } String msg = pac.getMessage("someMessage", null, "default", Locale.getDefault()); - assertTrue("Default message returned", "default".equals(msg)); + assertEquals("Default message returned", "default", msg); } /** - * Overridden in order to access the root ApplicationContext - * @see org.springframework.web.context.XmlWebApplicationContextTests#testContextNesting() + * Overridden in order to access the root ApplicationContext. + * + * @see org.springframework.web.context.XmlWebApplicationContextTests#contextNesting() */ + @Test @Override - public void testContextNesting() { + 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")); @@ -120,18 +129,21 @@ public class XmlPortletApplicationContextTests extends AbstractXmlWebApplication assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend")); } + @Test @Override - public void testCount() { + public void count() { assertTrue("should have 16 beans, not "+ this.applicationContext.getBeanDefinitionCount(), this.applicationContext.getBeanDefinitionCount() == 16); } - public void testPortletContextAwareBean() { + @Test + public void portletContextAwareBean() { PortletContextAwareBean bean = (PortletContextAwareBean)this.applicationContext.getBean("portletContextAwareBean"); assertNotNull(bean.getPortletContext()); } - public void testPortletConfigAwareBean() { + @Test + public void portletConfigAwareBean() { PortletConfigAwareBean bean = (PortletConfigAwareBean)this.applicationContext.getBean("portletConfigAwareBean"); assertNotNull(bean.getPortletConfig()); } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java index b942d1dfb3..061fc9b698 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java @@ -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,89 +16,83 @@ package org.springframework.web.portlet.handler; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.mock.web.portlet.MockPortletContext; import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.web.portlet.HandlerMapping; import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext; import org.springframework.web.portlet.context.XmlPortletApplicationContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher + * @author Sam Brannen */ -public class ParameterHandlerMappingTests extends TestCase { +public class ParameterHandlerMappingTests { public static final String CONF = "/org/springframework/web/portlet/handler/parameterMapping.xml"; - private ConfigurablePortletApplicationContext pac; + private final ConfigurablePortletApplicationContext pac = new XmlPortletApplicationContext(); - @Override + private final MockPortletContext portletContext = new MockPortletContext(); + + private final MockPortletRequest request = new MockPortletRequest(); + + private ParameterHandlerMapping hm; + + @Before public void setUp() throws Exception { - MockPortletContext portletContext = new MockPortletContext(); - pac = new XmlPortletApplicationContext(); pac.setPortletContext(portletContext); pac.setConfigLocations(new String[] {CONF}); pac.refresh(); + + hm = pac.getBean(ParameterHandlerMapping.class); } - public void testParameterMapping() throws Exception { - HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping"); - - MockPortletRequest addRequest = new MockPortletRequest(); + @Test + public void parameterMapping() throws Exception { + MockPortletRequest addRequest = request; addRequest.addParameter("action", "add"); + Object addHandler = hm.getHandler(addRequest).getHandler(); + assertEquals(pac.getBean("addItemHandler"), addHandler); MockPortletRequest removeRequest = new MockPortletRequest(); removeRequest.addParameter("action", "remove"); - - Object addHandler = hm.getHandler(addRequest).getHandler(); Object removeHandler = hm.getHandler(removeRequest).getHandler(); - - assertEquals(pac.getBean("addItemHandler"), addHandler); assertEquals(pac.getBean("removeItemHandler"), removeHandler); } - public void testUnregisteredHandlerWithNoDefault() throws Exception { - HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping"); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void unregisteredHandlerWithNoDefault() throws Exception { request.addParameter("action", "modify"); assertNull(hm.getHandler(request)); } - public void testUnregisteredHandlerWithDefault() throws Exception { - ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping"); + @Test + public void unregisteredHandlerWithDefault() throws Exception { Object defaultHandler = new Object(); hm.setDefaultHandler(defaultHandler); - - MockPortletRequest request = new MockPortletRequest(); request.addParameter("action", "modify"); assertNotNull(hm.getHandler(request)); assertEquals(defaultHandler, hm.getHandler(request).getHandler()); } - public void testConfiguredParameterName() throws Exception { - ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping"); + @Test + public void configuredParameterName() throws Exception { hm.setParameterName("someParam"); - - MockPortletRequest request = new MockPortletRequest(); request.addParameter("someParam", "add"); Object handler = hm.getHandler(request).getHandler(); assertEquals(pac.getBean("addItemHandler"), handler); } - public void testDuplicateMappingAttempt() { - ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping"); - try { - hm.registerHandler("add", new Object()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + @Test(expected = IllegalStateException.class) + public void duplicateMappingAttempt() { + hm.registerHandler("add", new Object()); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java index dea0e2c82a..60bff0cfc6 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java @@ -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,23 +16,30 @@ package org.springframework.web.portlet.handler; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockActionRequest; import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; + +import static org.junit.Assert.*; /** * @author Mark Fisher + * @author Sam Brannen */ -public class ParameterMappingInterceptorTests extends TestCase { +public class ParameterMappingInterceptorTests { - public void testDefaultParameterMapped() throws Exception { - ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); - Object handler = new Object(); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); + private final ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); + + private final Object handler = new Object(); + + private final MockActionRequest request = new MockActionRequest(); + + private final MockActionResponse response = new MockActionResponse(); + + + @Test + public void defaultParameterMapped() throws Exception { String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME; String value = "someValue"; request.setParameter(param, value); @@ -43,11 +50,8 @@ public class ParameterMappingInterceptorTests extends TestCase { assertEquals(value, response.getRenderParameter(param)); } - public void testNonDefaultParameterNotMapped() throws Exception { - ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); - Object handler = new Object(); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); + @Test + public void nonDefaultParameterNotMapped() throws Exception { String param = "myParam"; String value = "someValue"; request.setParameter(param, value); @@ -58,16 +62,13 @@ public class ParameterMappingInterceptorTests extends TestCase { assertNull(response.getRenderParameter(ParameterHandlerMapping.DEFAULT_PARAMETER_NAME)); } - public void testNonDefaultParameterMappedWhenHandlerMappingProvided() throws Exception { + @Test + public void nonDefaultParameterMappedWhenHandlerMappingProvided() throws Exception { String param = "myParam"; String value = "someValue"; ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping(); handlerMapping.setParameterName(param); - ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); interceptor.setParameterName(param); - Object handler = new Object(); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); request.setParameter(param, value); assertNull(response.getRenderParameter(param)); boolean shouldProceed = interceptor.preHandleAction(request, response, handler); @@ -77,11 +78,8 @@ public class ParameterMappingInterceptorTests extends TestCase { assertEquals(value, response.getRenderParameter(param)); } - public void testNoEffectForRenderRequest() throws Exception { - ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); - Object handler = new Object(); - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); + @Test + public void noEffectForRenderRequest() throws Exception { String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME; String value = "someValue"; request.setParameter(param, value); @@ -89,11 +87,8 @@ public class ParameterMappingInterceptorTests extends TestCase { assertTrue(shouldProceed); } - public void testNoParameterValueSetWithDefaultParameterName() throws Exception { - ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); - Object handler = new Object(); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); + @Test + public void noParameterValueSetWithDefaultParameterName() throws Exception { String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME; assertNull(response.getRenderParameter(param)); boolean shouldProceed = interceptor.preHandle(request, response, handler); @@ -101,11 +96,8 @@ public class ParameterMappingInterceptorTests extends TestCase { assertNull(response.getRenderParameter(param)); } - public void testNoParameterValueSetWithNonDefaultParameterName() throws Exception { - ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); - Object handler = new Object(); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); + @Test + public void noParameterValueSetWithNonDefaultParameterName() throws Exception { String param = "myParam"; assertNull(response.getRenderParameter(param)); boolean shouldProceed = interceptor.preHandle(request, response, handler); @@ -113,15 +105,12 @@ public class ParameterMappingInterceptorTests extends TestCase { assertNull(response.getRenderParameter(param)); } - public void testNoParameterValueSetWithNonDefaultParameterNameWhenHandlerMappingProvided() throws Exception { + @Test + public void noParameterValueSetWithNonDefaultParameterNameWhenHandlerMappingProvided() throws Exception { String param = "myParam"; ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping(); handlerMapping.setParameterName(param); - ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); interceptor.setParameterName(param); - Object handler = new Object(); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); assertNull(response.getRenderParameter(param)); boolean shouldProceed = interceptor.preHandle(request, response, handler); assertTrue(shouldProceed); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java index 26e4d9600f..2acd2ed686 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java @@ -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,71 +18,69 @@ package org.springframework.web.portlet.handler; import javax.portlet.PortletMode; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.mock.web.portlet.MockPortletContext; import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.web.portlet.HandlerMapping; import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext; import org.springframework.web.portlet.context.XmlPortletApplicationContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher + * @author Sam Brannen */ -public class PortletModeHandlerMappingTests extends TestCase { +public class PortletModeHandlerMappingTests { public static final String CONF = "/org/springframework/web/portlet/handler/portletModeMapping.xml"; - private ConfigurablePortletApplicationContext pac; + private final ConfigurablePortletApplicationContext pac = new XmlPortletApplicationContext(); - @Override + private final MockPortletContext portletContext = new MockPortletContext(); + + private final MockPortletRequest request = new MockPortletRequest(); + + private PortletModeHandlerMapping hm; + + + @Before public void setUp() throws Exception { - MockPortletContext portletContext = new MockPortletContext(); - pac = new XmlPortletApplicationContext(); pac.setPortletContext(portletContext); pac.setConfigLocations(new String[] {CONF}); pac.refresh(); + + hm = pac.getBean(PortletModeHandlerMapping.class); } - public void testPortletModeView() throws Exception { - HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping"); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void portletModeView() throws Exception { request.setPortletMode(PortletMode.VIEW); Object handler = hm.getHandler(request).getHandler(); assertEquals(pac.getBean("viewHandler"), handler); } - public void testPortletModeEdit() throws Exception { - HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping"); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void portletModeEdit() throws Exception { request.setPortletMode(PortletMode.EDIT); Object handler = hm.getHandler(request).getHandler(); assertEquals(pac.getBean("editHandler"), handler); } - public void testPortletModeHelp() throws Exception { - HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping"); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void portletModeHelp() throws Exception { request.setPortletMode(PortletMode.HELP); Object handler = hm.getHandler(request).getHandler(); assertEquals(pac.getBean("helpHandler"), handler); } - public void testDuplicateMappingAttempt() { - PortletModeHandlerMapping hm = (PortletModeHandlerMapping)pac.getBean("handlerMapping"); - try { - hm.registerHandler(PortletMode.VIEW, new Object()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + @Test(expected = IllegalStateException.class) + public void duplicateMappingAttempt() { + hm.registerHandler(PortletMode.VIEW, new Object()); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java index 6cfd9440f4..f634e51255 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java @@ -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,54 +18,59 @@ package org.springframework.web.portlet.handler; import javax.portlet.PortletMode; -import junit.framework.TestCase; +import org.junit.Before; +import org.junit.Test; import org.springframework.mock.web.portlet.MockPortletContext; import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.web.portlet.HandlerMapping; import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext; import org.springframework.web.portlet.context.XmlPortletApplicationContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher + * @author Sam Brannen */ -public class PortletModeParameterHandlerMappingTests extends TestCase { +public class PortletModeParameterHandlerMappingTests { public static final String CONF = "/org/springframework/web/portlet/handler/portletModeParameterMapping.xml"; - private ConfigurablePortletApplicationContext pac; + private final ConfigurablePortletApplicationContext pac = new XmlPortletApplicationContext(); - @Override + private final MockPortletContext portletContext = new MockPortletContext(); + + private final MockPortletRequest request = new MockPortletRequest(); + + private PortletModeParameterHandlerMapping hm; + + + @Before public void setUp() throws Exception { - MockPortletContext portletContext = new MockPortletContext(); - pac = new XmlPortletApplicationContext(); pac.setPortletContext(portletContext); pac.setConfigLocations(new String[] {CONF}); pac.refresh(); + + hm = pac.getBean(PortletModeParameterHandlerMapping.class); } - public void testPortletModeViewWithParameter() throws Exception { - HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping"); - - MockPortletRequest addRequest = new MockPortletRequest(); + @Test + public void portletModeViewWithParameter() throws Exception { + MockPortletRequest addRequest = request; addRequest.setPortletMode(PortletMode.VIEW); addRequest.setParameter("action", "add"); + Object addHandler = hm.getHandler(addRequest).getHandler(); + assertEquals(pac.getBean("addItemHandler"), addHandler); MockPortletRequest removeRequest = new MockPortletRequest(); removeRequest.setPortletMode(PortletMode.VIEW); removeRequest.setParameter("action", "remove"); - - Object addHandler = hm.getHandler(addRequest).getHandler(); Object removeHandler = hm.getHandler(removeRequest).getHandler(); - - assertEquals(pac.getBean("addItemHandler"), addHandler); assertEquals(pac.getBean("removeItemHandler"), removeHandler); } - public void testPortletModeEditWithParameter() throws Exception { - HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping"); - - MockPortletRequest request = new MockPortletRequest(); + @Test + public void portletModeEditWithParameter() throws Exception { request.setPortletMode(PortletMode.EDIT); request.setParameter("action", "prefs"); @@ -73,36 +78,23 @@ public class PortletModeParameterHandlerMappingTests extends TestCase { assertEquals(pac.getBean("preferencesHandler"), handler); } - public void testDuplicateMappingInSamePortletMode() { - PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping"); - try { - hm.registerHandler(PortletMode.VIEW, "remove", new Object()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + @Test(expected = IllegalStateException.class) + public void duplicateMappingInSamePortletMode() { + hm.registerHandler(PortletMode.VIEW, "remove", new Object()); } - public void testDuplicateMappingInDifferentPortletMode() { - PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping"); - try { - hm.registerHandler(PortletMode.EDIT, "remove", new Object()); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } + @Test(expected = IllegalStateException.class) + public void duplicateMappingInDifferentPortletMode() { + hm.registerHandler(PortletMode.EDIT, "remove", new Object()); } - public void testAllowDuplicateMappingInDifferentPortletMode() throws Exception { - PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping"); + @Test + public void allowDuplicateMappingInDifferentPortletMode() throws Exception { hm.setAllowDuplicateParameters(true); Object editRemoveHandler = new Object(); hm.registerHandler(PortletMode.EDIT, "remove", editRemoveHandler); - MockPortletRequest request = new MockPortletRequest(); request.setPortletMode(PortletMode.EDIT); request.setParameter("action", "remove"); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java index 1632f5074a..fed02db643 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java @@ -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,70 +20,75 @@ import java.util.Collections; import java.util.Properties; import javax.portlet.WindowState; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockRenderRequest; import org.springframework.mock.web.portlet.MockRenderResponse; import org.springframework.web.portlet.ModelAndView; +import static org.junit.Assert.*; + /** * @author Seth Ladd * @author Mark Fisher * @author Juergen Hoeller + * @author Sam Brannen */ -public class SimpleMappingExceptionResolverTests extends TestCase { +public class SimpleMappingExceptionResolverTests { private static final String DEFAULT_VIEW = "default-view"; - private SimpleMappingExceptionResolver exceptionResolver; - private MockRenderRequest request; - private MockRenderResponse response; - private Object handler1; - private Object handler2; - private Exception genericException; + private final SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver(); - @Override - protected void setUp() { - exceptionResolver = new SimpleMappingExceptionResolver(); - request = new MockRenderRequest(); - response = new MockRenderResponse(); - handler1 = new String(); - handler2 = new Object(); - genericException = new Exception(); - } + private final MockRenderRequest request = new MockRenderRequest(); - public void testSetOrder() { + private final MockRenderResponse response = new MockRenderResponse(); + + private final Object handler1 = new String(); + + private final Object handler2 = new Object(); + + private final Exception genericException = new Exception(); + + + @Test + public void setOrder() { exceptionResolver.setOrder(2); assertEquals(2, exceptionResolver.getOrder()); } - public void testDefaultErrorView() { + @Test + public void defaultErrorView() { exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); assertEquals(DEFAULT_VIEW, mav.getViewName()); assertEquals(genericException, mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); } - public void testDefaultErrorViewDifferentHandler() { + @Test + public void defaultErrorViewDifferentHandler() { exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); assertNull("Handler not mapped - ModelAndView should be null", mav); } - public void testDefaultErrorViewDifferentHandlerClass() { + @Test + public void defaultErrorViewDifferentHandlerClass() { exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); exceptionResolver.setMappedHandlerClasses(new Class[] {String.class}); ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); assertNull("Handler not mapped - ModelAndView should be null", mav); } - public void testNullDefaultErrorView() { + @Test + public void nullDefaultErrorView() { ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); assertNull("No default error view set - ModelAndView should be null", mav); } - public void testNullExceptionAttribute() { + @Test + public void nullExceptionAttribute() { exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); exceptionResolver.setExceptionAttribute(null); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); @@ -91,21 +96,24 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertNull(mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); } - public void testNullExceptionMappings() { + @Test + public void nullExceptionMappings() { exceptionResolver.setExceptionMappings(null); exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); assertEquals(DEFAULT_VIEW, mav.getViewName()); } - public void testDefaultNoRenderWhenMinimized() { + @Test + public void defaultNoRenderWhenMinimized() { exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); request.setWindowState(WindowState.MINIMIZED); ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); assertNull("Should not render when WindowState is MINIMIZED", mav); } - public void testDoRenderWhenMinimized() { + @Test + public void doRenderWhenMinimized() { exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); exceptionResolver.setRenderWhenMinimized(true); request.setWindowState(WindowState.MINIMIZED); @@ -114,7 +122,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals(DEFAULT_VIEW, mav.getViewName()); } - public void testSimpleExceptionMapping() { + @Test + public void simpleExceptionMapping() { Properties props = new Properties(); props.setProperty("Exception", "error"); exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION"); @@ -123,7 +132,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("error", mav.getViewName()); } - public void testExactExceptionMappingWithHandlerSpecified() { + @Test + public void exactExceptionMappingWithHandlerSpecified() { Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); @@ -132,7 +142,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("error", mav.getViewName()); } - public void testExactExceptionMappingWithHandlerClassSpecified() { + @Test + public void exactExceptionMappingWithHandlerClassSpecified() { Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); exceptionResolver.setMappedHandlerClasses(new Class[] {String.class}); @@ -141,7 +152,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("error", mav.getViewName()); } - public void testExactExceptionMappingWithHandlerInterfaceSpecified() { + @Test + public void exactExceptionMappingWithHandlerInterfaceSpecified() { Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); exceptionResolver.setMappedHandlerClasses(new Class[] {Comparable.class}); @@ -150,7 +162,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("error", mav.getViewName()); } - public void testSimpleExceptionMappingWithHandlerSpecifiedButWrongHandler() { + @Test + public void simpleExceptionMappingWithHandlerSpecifiedButWrongHandler() { Properties props = new Properties(); props.setProperty("Exception", "error"); exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); @@ -159,7 +172,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertNull("Handler not mapped - ModelAndView should be null", mav); } - public void testSimpleExceptionMappingWithHandlerSpecifiedButWrongHandlerClass() { + @Test + public void simpleExceptionMappingWithHandlerSpecifiedButWrongHandlerClass() { Properties props = new Properties(); props.setProperty("Exception", "error"); exceptionResolver.setMappedHandlerClasses(new Class[] {String.class}); @@ -168,7 +182,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertNull("Handler not mapped - ModelAndView should be null", mav); } - public void testMissingExceptionInMapping() { + @Test + public void missingExceptionInMapping() { Properties props = new Properties(); props.setProperty("SomeFooThrowable", "error"); exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION"); @@ -177,7 +192,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertNull("Exception not mapped - ModelAndView should be null", mav); } - public void testTwoMappings() { + @Test + public void twoMappings() { Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); props.setProperty("AnotherException", "another-error"); @@ -187,7 +203,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("error", mav.getViewName()); } - public void testTwoMappingsOneShortOneLong() { + @Test + public void twoMappingsOneShortOneLong() { Properties props = new Properties(); props.setProperty("Exception", "error"); props.setProperty("AnotherException", "another-error"); @@ -197,7 +214,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("error", mav.getViewName()); } - public void testTwoMappingsOneShortOneLongThrowOddException() { + @Test + public void twoMappingsOneShortOneLongThrowOddException() { Exception oddException = new SomeOddException(); Properties props = new Properties(); props.setProperty("Exception", "error"); @@ -208,7 +226,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("another-error", mav.getViewName()); } - public void testTwoMappingsThrowOddExceptionUseLongExceptionMapping() { + @Test + public void twoMappingsThrowOddExceptionUseLongExceptionMapping() { Exception oddException = new SomeOddException(); Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); @@ -219,7 +238,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("another-error", mav.getViewName()); } - public void testThreeMappings() { + @Test + public void threeMappings() { Exception oddException = new AnotherOddException(); Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); @@ -231,7 +251,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("another-some-error", mav.getViewName()); } - public void testExceptionWithSubstringMatchingParent() { + @Test + public void exceptionWithSubstringMatchingParent() { Exception oddException = new SomeOddExceptionChild(); Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); @@ -243,7 +264,8 @@ public class SimpleMappingExceptionResolverTests extends TestCase { assertEquals("child-error", mav.getViewName()); } - public void testMostSpecificExceptionInHierarchyWins() { + @Test + public void mostSpecificExceptionInHierarchyWins() { Exception oddException = new NoSubstringMatchesThisException(); Properties props = new Properties(); props.setProperty("java.lang.Exception", "error"); diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java index 873b7a5fad..777b8c3f82 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java @@ -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,22 +18,30 @@ package org.springframework.web.portlet.handler; import javax.portlet.PortletSecurityException; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockRenderRequest; import org.springframework.mock.web.portlet.MockRenderResponse; +import static org.junit.Assert.*; + /** * @author Mark Fisher + * @author Sam Brannen */ -public class UserRoleAuthorizationInterceptorTests extends TestCase { +public class UserRoleAuthorizationInterceptorTests { - public void testAuthorizedUser() throws Exception { - UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor(); + private final UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor(); + + private final MockRenderRequest request = new MockRenderRequest(); + + private final MockRenderResponse response = new MockRenderResponse(); + + + @Test + public void authorizedUser() throws Exception { String validRole = "allowed"; interceptor.setAuthorizedRoles(new String[] {validRole}); - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); Object handler = new Object(); request.addUserRole(validRole); assertTrue(request.isUserInRole(validRole)); @@ -41,13 +49,11 @@ public class UserRoleAuthorizationInterceptorTests extends TestCase { assertTrue(shouldProceed); } - public void testAuthorizedUserWithMultipleRoles() throws Exception { - UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor(); + @Test + public void authorizedUserWithMultipleRoles() throws Exception { String validRole1 = "allowed1"; String validRole2 = "allowed2"; interceptor.setAuthorizedRoles(new String[] {validRole1, validRole2}); - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); Object handler = new Object(); request.addUserRole(validRole2); request.addUserRole("someOtherRole"); @@ -57,54 +63,29 @@ public class UserRoleAuthorizationInterceptorTests extends TestCase { assertTrue(shouldProceed); } - public void testUnauthorizedUser() throws Exception { - UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor(); + @Test(expected = PortletSecurityException.class) + public void unauthorizedUser() throws Exception { String validRole = "allowed"; interceptor.setAuthorizedRoles(new String[] {validRole}); - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - Object handler = new Object(); request.addUserRole("someOtherRole"); assertFalse(request.isUserInRole(validRole)); - try { - interceptor.preHandle(request, response, handler); - fail("should have thrown PortletSecurityException"); - } - catch (PortletSecurityException ex) { - // expected - } + + interceptor.preHandle(request, response, new Object()); } - public void testRequestWithNoUserRoles() throws Exception { - UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor(); + @Test(expected = PortletSecurityException.class) + public void requestWithNoUserRoles() throws Exception { String validRole = "allowed"; interceptor.setAuthorizedRoles(new String[] {validRole}); - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - Object handler = new Object(); assertFalse(request.isUserInRole(validRole)); - try { - interceptor.preHandle(request, response, handler); - fail("should have thrown PortletSecurityException"); - } - catch (PortletSecurityException ex) { - // expected - } + + interceptor.preHandle(request, response, new Object()); } - public void testInterceptorWithNoAuthorizedRoles() throws Exception { - UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor(); - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - Object handler = new Object(); + @Test(expected = PortletSecurityException.class) + public void interceptorWithNoAuthorizedRoles() throws Exception { request.addUserRole("someRole"); - try { - interceptor.preHandle(request, response, handler); - fail("should have thrown PortletSecurityException"); - } - catch (PortletSecurityException ex) { - // expected - } + interceptor.preHandle(request, response, new Object()); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java index 3cb40f68cf..4caaa7f6a3 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java @@ -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,13 +16,11 @@ package org.springframework.web.portlet.mvc; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockActionRequest; import org.springframework.mock.web.portlet.MockActionResponse; @@ -31,43 +29,37 @@ import org.springframework.mock.web.portlet.MockRenderResponse; import org.springframework.web.portlet.ModelAndView; import org.springframework.web.portlet.context.StaticPortletApplicationContext; +import static org.junit.Assert.*; + /** * @author Mark Fisher + * @author Sam Brannen */ -public class ParameterizableViewControllerTests extends TestCase { +public class ParameterizableViewControllerTests { - public void testRenderRequestWithViewNameSet() throws Exception { - ParameterizableViewController controller = new ParameterizableViewController(); + private final ParameterizableViewController controller = new ParameterizableViewController(); + + private final RenderRequest request = new MockRenderRequest(); + + private final RenderResponse response = new MockRenderResponse(); + + + @Test + public void renderRequestWithViewNameSet() throws Exception { String viewName = "testView"; controller.setViewName(viewName); - RenderRequest request = new MockRenderRequest(); - RenderResponse response = new MockRenderResponse(); ModelAndView mav = controller.handleRenderRequest(request, response); assertEquals(viewName, mav.getViewName()); } - public void testInitApplicationContextWithNoViewNameSet() throws Exception { - ParameterizableViewController controller = new ParameterizableViewController(); - try { - controller.setApplicationContext(new StaticPortletApplicationContext()); - fail("should have thrown IllegalArgumentException"); - } - catch (IllegalArgumentException ex) { - // expected - } + @Test(expected = IllegalArgumentException.class) + public void initApplicationContextWithNoViewNameSet() throws Exception { + controller.setApplicationContext(new StaticPortletApplicationContext()); } - public void testActionRequestNotHandled() throws Exception { - ParameterizableViewController controller = new ParameterizableViewController(); - ActionRequest request = new MockActionRequest(); - ActionResponse response = new MockActionResponse(); - try { - controller.handleActionRequest(request, response); - fail("should have thrown PortletException"); - } - catch (PortletException ex) { - // expected - } + @Test(expected = PortletException.class) + public void actionRequestNotHandled() throws Exception { + controller.handleActionRequest(new MockActionRequest(), new MockActionResponse()); } } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java index 1f2f9a8d62..ceee4ff5a0 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java @@ -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,7 +19,7 @@ package org.springframework.web.portlet.mvc; import javax.portlet.PortletException; import javax.portlet.PortletMode; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.mock.web.portlet.MockActionRequest; import org.springframework.mock.web.portlet.MockActionResponse; @@ -27,51 +27,45 @@ import org.springframework.mock.web.portlet.MockRenderRequest; import org.springframework.mock.web.portlet.MockRenderResponse; import org.springframework.web.portlet.ModelAndView; +import static org.junit.Assert.*; + /** * @author Mark Fisher + * @author Sam Brannen */ -public class PortletModeNameViewControllerTests extends TestCase { +public class PortletModeNameViewControllerTests { - private PortletModeNameViewController controller; + private final PortletModeNameViewController controller = new PortletModeNameViewController(); - @Override - public void setUp() { - controller = new PortletModeNameViewController(); - } + private final MockRenderRequest request = new MockRenderRequest(); - public void testEditPortletMode() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); + private final MockRenderResponse response = new MockRenderResponse(); + + + @Test + public void editPortletMode() throws Exception { request.setPortletMode(PortletMode.EDIT); ModelAndView mav = controller.handleRenderRequest(request, response); assertEquals("edit", mav.getViewName()); } - public void testHelpPortletMode() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); + @Test + public void helpPortletMode() throws Exception { request.setPortletMode(PortletMode.HELP); ModelAndView mav = controller.handleRenderRequest(request, response); assertEquals("help", mav.getViewName()); } - public void testViewPortletMode() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); + @Test + public void viewPortletMode() throws Exception { request.setPortletMode(PortletMode.VIEW); ModelAndView mav = controller.handleRenderRequest(request, response); assertEquals("view", mav.getViewName()); } - public void testActionRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - try { - controller.handleActionRequest(request, response); - fail("Should have thrown PortletException"); - } - catch(PortletException ex) { - // expected - } + @Test(expected = PortletException.class) + public void actionRequest() throws Exception { + controller.handleActionRequest(new MockActionRequest(), new MockActionResponse()); } + } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java index 0aebb6e72b..3a5df549c1 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java @@ -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. @@ -47,6 +47,7 @@ import static org.junit.Assert.*; * @author Mark Fisher * @author Rick Evans * @author Chris Beams + * @author Sam Brannen */ public final class PortletWrappingControllerTests { @@ -55,11 +56,11 @@ public final class PortletWrappingControllerTests { private static final String RENDERED_RESPONSE_CONTENT = "myPortlet-view"; private static final String PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME = "portletName"; - private PortletWrappingController controller; @Before + @SuppressWarnings("resource") public void setUp() { ConfigurablePortletApplicationContext applicationContext = new MyApplicationContext(); MockPortletConfig config = new MockPortletConfig(new MockPortletContext(), "wrappedPortlet"); @@ -70,67 +71,65 @@ public final class PortletWrappingControllerTests { @Test - public void testActionRequest() throws Exception { + public void actionRequest() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setParameter("test", "test"); + controller.handleActionRequest(request, response); - String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME); - assertEquals("myPortlet-action", result); + assertEquals("myPortlet-action", response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME)); } @Test - public void testRenderRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); + public void renderRequest() throws Exception { MockRenderResponse response = new MockRenderResponse(); - controller.handleRenderRequest(request, response); - String result = response.getContentAsString(); - assertEquals(RENDERED_RESPONSE_CONTENT, result); + + controller.handleRenderRequest(new MockRenderRequest(), response); + assertEquals(RENDERED_RESPONSE_CONTENT, response.getContentAsString()); } - @Test(expected=IllegalArgumentException.class) - public void testActionRequestWithNoParameters() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - controller.handleActionRequest(request, response); + @Test(expected = IllegalArgumentException.class) + public void actionRequestWithNoParameters() throws Exception { + controller.handleActionRequest(new MockActionRequest(), new MockActionResponse()); } - @Test(expected=IllegalArgumentException.class) - public void testRejectsPortletClassThatDoesNotImplementPortletInterface() throws Exception { + @Test(expected = IllegalArgumentException.class) + public void rejectsPortletClassThatDoesNotImplementPortletInterface() throws Exception { PortletWrappingController controller = new PortletWrappingController(); controller.setPortletClass(String.class); + controller.afterPropertiesSet(); } - @Test(expected=IllegalArgumentException.class) - public void testRejectsIfPortletClassIsNotSupplied() throws Exception { + @Test(expected = IllegalArgumentException.class) + public void rejectsIfPortletClassIsNotSupplied() throws Exception { PortletWrappingController controller = new PortletWrappingController(); controller.setPortletClass(null); + controller.afterPropertiesSet(); } - @Test(expected=IllegalStateException.class) - public void testDestroyingTheControllerPropagatesDestroyToWrappedPortlet() throws Exception { + @Test(expected = IllegalStateException.class) + public void destroyingTheControllerPropagatesDestroyToWrappedPortlet() throws Exception { final PortletWrappingController controller = new PortletWrappingController(); controller.setPortletClass(MyPortlet.class); controller.afterPropertiesSet(); - // test for destroy() call being propagated via exception being thrown :( + + // test for destroy() call being propagated via exception being thrown controller.destroy(); } @Test - public void testPortletName() throws Exception { + public void portletName() throws Exception { MockActionRequest request = new MockActionRequest(); MockActionResponse response = new MockActionResponse(); request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "test"); controller.handleActionRequest(request, response); - String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME); - assertEquals("wrappedPortlet", result); + assertEquals("wrappedPortlet", response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME)); } @Test - public void testDelegationToMockPortletConfigIfSoConfigured() throws Exception { - + public void delegationToMockPortletConfigIfSoConfigured() throws Exception { final String BEAN_NAME = "Sixpence None The Richer"; MockActionRequest request = new MockActionRequest(); @@ -145,8 +144,7 @@ public final class PortletWrappingControllerTests { request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "true"); controller.handleActionRequest(request, response); - String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME); - assertEquals(BEAN_NAME, result); + assertEquals(BEAN_NAME, response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME)); } diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java index f692946c06..7c2872b995 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java @@ -993,6 +993,7 @@ public class Portlet20AnnotationControllerTests { } @ModelAttribute + @SuppressWarnings("unchecked") protected TB2 getModelAttr() { return (TB2) new DerivedTestBean(); } @@ -1032,6 +1033,7 @@ public class Portlet20AnnotationControllerTests { @Controller + @SuppressWarnings("rawtypes") private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { @InitBinder @@ -1044,9 +1046,9 @@ public class Portlet20AnnotationControllerTests { @Controller + @SuppressWarnings("rawtypes") private static class MySpecificBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { - @SuppressWarnings("unused") @InitBinder({"myCommand", "date"}) private void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); @@ -1238,13 +1240,14 @@ public class Portlet20AnnotationControllerTests { private static class TestView { + @SuppressWarnings("deprecation") public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception { TestBean tb = (TestBean) model.get("testBean"); if (tb == null) { tb = (TestBean) model.get("myCommand"); } if (tb.getName().endsWith("myDefaultName")) { - assertTrue(tb.getDate().getYear() == 107); + assertEquals(107, tb.getDate().getYear()); } Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean"); if (errors == null) { diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java index 0231edb196..db72a361fe 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java @@ -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. @@ -35,7 +35,7 @@ import javax.portlet.RenderResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import junit.framework.TestCase; +import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; @@ -78,13 +78,16 @@ import org.springframework.web.portlet.mvc.AbstractController; import org.springframework.web.servlet.View; import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @since 2.5 */ -public class PortletAnnotationControllerTests extends TestCase { +public class PortletAnnotationControllerTests { - public void testStandardHandleMethod() throws Exception { + @Test + public void standardHandleMethod() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -102,15 +105,18 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("test", response.getContentAsString()); } - public void testAdaptedHandleMethods() throws Exception { + @Test + public void adaptedHandleMethods() throws Exception { doTestAdaptedHandleMethods(MyAdaptedController.class); } - public void testAdaptedHandleMethods2() throws Exception { + @Test + public void adaptedHandleMethods2() throws Exception { doTestAdaptedHandleMethods(MyAdaptedController2.class); } - public void testAdaptedHandleMethods3() throws Exception { + @Test + public void adaptedHandleMethods3() throws Exception { doTestAdaptedHandleMethods(MyAdaptedController3.class); } @@ -153,7 +159,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("test-name1-typeMismatch", response.getContentAsString()); } - public void testFormController() throws Exception { + @Test + public void formController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -177,7 +184,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); } - public void testModelFormController() throws Exception { + @Test + public void modelFormController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -201,7 +209,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); } - public void testCommandProvidingFormController() throws Exception { + @Test + public void commandProvidingFormController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -229,7 +238,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); } - public void testTypedCommandProvidingFormController() throws Exception { + @Test + public void typedCommandProvidingFormController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -278,7 +288,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("myView-myName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); } - public void testBinderInitializingCommandProvidingFormController() throws Exception { + @Test + public void binderInitializingCommandProvidingFormController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -303,7 +314,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); } - public void testSpecificBinderInitializingCommandProvidingFormController() throws Exception { + @Test + public void specificBinderInitializingCommandProvidingFormController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -328,7 +340,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); } - public void testParameterDispatchingController() throws Exception { + @Test + public void parameterDispatchingController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -369,7 +382,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("mySurpriseView", response.getContentAsString()); } - public void testTypeLevelParameterDispatchingController() throws Exception { + @Test + public void typeLevelParameterDispatchingController() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -455,7 +469,8 @@ public class PortletAnnotationControllerTests extends TestCase { assertEquals("mySurpriseView", response.getContentAsString()); } - public void testMavResolver() throws Exception { + @Test + public void mavResolver() throws Exception { DispatcherPortlet portlet = new DispatcherPortlet() { @Override protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { @@ -636,6 +651,7 @@ public class PortletAnnotationControllerTests extends TestCase { } @ModelAttribute + @SuppressWarnings("unchecked") protected TB2 getModelAttr() { return (TB2) new DerivedTestBean(); } @@ -674,6 +690,7 @@ public class PortletAnnotationControllerTests extends TestCase { @Controller + @SuppressWarnings("rawtypes") private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { @InitBinder @@ -686,9 +703,9 @@ public class PortletAnnotationControllerTests extends TestCase { @Controller + @SuppressWarnings("rawtypes") private static class MySpecificBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { - @SuppressWarnings("unused") @InitBinder({"myCommand", "date"}) private void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); @@ -796,13 +813,14 @@ public class PortletAnnotationControllerTests extends TestCase { private static class TestView { + @SuppressWarnings("deprecation") public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception { TestBean tb = (TestBean) model.get("testBean"); if (tb == null) { tb = (TestBean) model.get("myCommand"); } if (tb.getName().endsWith("myDefaultName")) { - assertTrue(tb.getDate().getYear() == 107); + assertEquals(107, tb.getDate().getYear()); } Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean"); if (errors == null) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java index 6b74b004fc..38ddf87726 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/ServletContextAwareProcessorTests.java @@ -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(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java index e526ffad9d..e2d1853818 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java @@ -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); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java index db442acd38..ed0aca2753 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java @@ -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 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 mappedHandlers = new ManagedList(); 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 { public int counter = 0; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index 1ef593c8a5..d5cb10f78c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -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")); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java index 907f6f9358..9bed303a1a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java @@ -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)) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java index c8e3a860d7..8868086fcf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/BeanNameUrlHandlerMappingTests.java @@ -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()); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java index 2d7dbf00a9..3ab23141c9 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/ControllerTests.java @@ -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(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java index 98c40d14ac..690ae54128 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/UrlFilenameViewControllerTests.java @@ -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")); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameHandlerMappingTests.java index 6c495b31ab..152324d1bf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ControllerClassNameHandlerMappingTests.java @@ -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()); } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerBeanNameHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerBeanNameHandlerMappingTests.java index a0822913bc..e1180de9b8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerBeanNameHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerBeanNameHandlerMappingTests.java @@ -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()); } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerClassNameHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerClassNameHandlerMappingTests.java index 15cdacd232..610159de13 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerClassNameHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/mapping/ControllerClassNameHandlerMappingTests.java @@ -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()); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java index bc4f322ade..c0b9c6c00d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java @@ -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}. diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java index 0aa2f8f642..fc49ce3b34 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java @@ -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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java index ae1b7c081d..5dfb3db104 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/AbstractTagTests.java @@ -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(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java index 2b3a5a00c6..fb11f53fa8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ArgumentTagTests.java @@ -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(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java index eefeb2138b..bec2c223ec 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java @@ -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&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&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<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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java index 78665e815c..307f7ef840 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java @@ -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("<p>", ((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 map = new HashMap(); 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); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java index 2e8ca80776..a818078fe1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/HtmlEscapeTagTests.java @@ -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 & 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() { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java index c992d67f39..7afc890f20 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/MessageTagTests.java @@ -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 & 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 <&> é", 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", "' test & 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")); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java index 2be185550b..ef549f2e86 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTagTests.java @@ -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") diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java index 4231d24ad2..90b0d6fddc 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ParamTests.java @@ -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()); } + } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java index c120f6b3dd..bae7e8cd70 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/ThemeTagTests.java @@ -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")); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java index 15ce412677..1647d4a40b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java @@ -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 params = new LinkedList(); Set usedParams = new HashSet(); @@ -214,7 +228,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals("", queryString); } - public void testCreateQueryStringOneParam() throws JspException { + @Test + public void createQueryStringOneParam() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -228,7 +243,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals("?name=value", queryString); } - public void testCreateQueryStringOneParamForExsistingQueryString() + @Test + public void createQueryStringOneParamForExsistingQueryString() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -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 params = new LinkedList(); Set usedParams = new HashSet(); @@ -257,7 +274,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals("?name=", queryString); } - public void testCreateQueryStringOneParamNullValue() throws JspException { + @Test + public void createQueryStringOneParamNullValue() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -271,7 +289,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals("?name", queryString); } - public void testCreateQueryStringOneParamAlreadyUsed() throws JspException { + @Test + public void createQueryStringOneParamAlreadyUsed() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -287,7 +306,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals("", queryString); } - public void testCreateQueryStringTwoParams() throws JspException { + @Test + public void createQueryStringTwoParams() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -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 params = new LinkedList(); Set usedParams = new HashSet(); @@ -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 params = new LinkedList(); Set usedParams = new HashSet(); @@ -339,7 +361,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals("", queryString); } - public void testCreateQueryStringParamEmptyName() throws JspException { + @Test + public void createQueryStringParamEmptyName() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -353,7 +376,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals("", queryString); } - public void testReplaceUriTemplateParamsNoParams() throws JspException { + @Test + public void replaceUriTemplateParamsNoParams() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -364,7 +388,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals(0, usedParams.size()); } - public void testReplaceUriTemplateParamsTemplateWithoutParamMatch() + @Test + public void replaceUriTemplateParamsTemplateWithoutParamMatch() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -376,7 +401,8 @@ public class UrlTagTests extends AbstractTagTests { assertEquals(0, usedParams.size()); } - public void testReplaceUriTemplateParamsTemplateWithParamMatch() + @Test + public void replaceUriTemplateParamsTemplateWithParamMatch() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -394,7 +420,8 @@ public class UrlTagTests extends AbstractTagTests { assertTrue(usedParams.contains("name")); } - public void testReplaceUriTemplateParamsTemplateWithParamMatchNamePreEncoding() + @Test + public void replaceUriTemplateParamsTemplateWithParamMatchNamePreEncoding() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -412,7 +439,8 @@ public class UrlTagTests extends AbstractTagTests { assertTrue(usedParams.contains("n me")); } - public void testReplaceUriTemplateParamsTemplateWithParamMatchValueEncoded() + @Test + public void replaceUriTemplateParamsTemplateWithParamMatchValueEncoded() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -432,7 +460,8 @@ public class UrlTagTests extends AbstractTagTests { // SPR-11401 - public void testReplaceUriTemplateParamsTemplateWithPathSegment() + @Test + public void replaceUriTemplateParamsTemplateWithPathSegment() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -449,7 +478,8 @@ public class UrlTagTests extends AbstractTagTests { assertTrue(usedParams.contains("name")); } - public void testReplaceUriTemplateParamsTemplateWithPath() + @Test + public void replaceUriTemplateParamsTemplateWithPath() throws JspException { List params = new LinkedList(); Set usedParams = new HashSet(); @@ -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 } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java index 49f7f0bd5c..1251b9ced9 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractHtmlElementTagTests.java @@ -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 model = Collections.singletonMap( + BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, errors); // replace the request context with one containing the errors MockPageContext pageContext = getPageContext(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java index 270e8561c8..f5a680d3bd 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java @@ -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(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java index b577c4c2ef..e8fe9c6dac 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java @@ -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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java index bb63f8b572..6ec93354c8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java @@ -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("
"); 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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/Country.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/Country.java index 8af7c0125a..c6711a8037 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/Country.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/Country.java @@ -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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java index 0d4f2a64f4..5b6b7cf59e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java @@ -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 & 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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index 7d8d9d5351..09839477c5 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java @@ -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=\">"; 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(""); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java index 8ff78909c3..2d6808ab35 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java @@ -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(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java index 25a9208138..7e6c37fb20 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java @@ -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 "I Love Mangos" 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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java index 67ec7aed58..e8e0aeee92 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java @@ -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 ")); } - 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("")); } - 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 ")); } - public void testOverrideFor() throws Exception { + @Test + public void overrideFor() throws Exception { this.tag.setPath("name"); this.tag.setFor("myElement"); int startResult = this.tag.doStartTag(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java index aa853b99bf..87c3fee015 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java @@ -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); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java index c9396899c6..f341953202 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java @@ -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("", getOutput()); } - public void testOptionTagNotNestedWithinSelectTag() throws Exception { + @Test + public void optionTagNotNestedWithinSelectTag() throws Exception { try { tag.setParent(null); tag.setValue("foo"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java index d6ba42f6c5..302f457b06 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java @@ -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); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/PasswordInputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/PasswordInputTagTests.java index 8bca618fdf..b5e5a9894e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/PasswordInputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/PasswordInputTagTests.java @@ -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(); } + } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java index 5576714986..f399720ec3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java @@ -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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java index a8c46292ff..7f574be803 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java @@ -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("
"); 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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java index 63796f3577..2cf94778c1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java @@ -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("", 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("", 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 value. * */ - 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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagIdGeneratorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagIdGeneratorTests.java index 6442bcdbee..bd0218b44e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagIdGeneratorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagIdGeneratorTests.java @@ -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)); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagWriterTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagWriterTests.java index 9c64ac0e26..31f314b09e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagWriterTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TagWriterTests.java @@ -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("
", 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("", 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("", 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("", 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("Rob Harrop", 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("Rob Harrop", 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("Rob Harrop", 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"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java index d624a22285..503262d46b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java @@ -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 "I Love Mangos" 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); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/theme/ThemeResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/theme/ThemeResolverTests.java index a71265c8c1..aee25fd99e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/theme/ThemeResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/theme/ThemeResolverTests.java @@ -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); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java index 67946cf8b4..c464388e1c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/BaseViewTests.java @@ -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}. + * + *

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(), 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 actual) { - Set keys = expected.keySet(); - for (Iterator 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 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 model; + Map model; - public TestView(WebApplicationContext wac) { + TestView(WebApplicationContext wac) { this.wac = wac; - } + @Override - protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - // do nothing - this.model = model; - } + protected void renderMergedOutputModel(Map 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); } - } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java index e29e4555ec..5c5854c130 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/InternalResourceViewTests.java @@ -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 model = Collections.unmodifiableMap(new HashMap() {{ + 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 model = new HashMap(); - 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 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 model = new HashMap(); - 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 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 model = new HashMap(); - 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 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 model = new HashMap(); - 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 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))); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java index 304e5dab16..53b82d7cc3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java @@ -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 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 model, HttpServletRequest request, + HttpServletResponse response) { } @Override diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportViewResolverTests.java index c743d6254c..b3aff5268e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportViewResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/jasperreports/JasperReportViewResolverTests.java @@ -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"}); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/TestVelocityEngine.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/TestVelocityEngine.java index 63c320b73f..da0d14b433 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/TestVelocityEngine.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/TestVelocityEngine.java @@ -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 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 + "]"); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java index 2242915880..f900788161 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java @@ -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 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 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())); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java index 711096e4a2..1c46a1bad0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java @@ -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 msgMap = new HashMap(); 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 msgMap = new HashMap(); msgMap.put("hello", "Howdy"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewResolverTests.java index c61641ccfe..9c76057636 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewResolverTests.java @@ -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()); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewTests.java index c7ccdd2c93..86fc0ac3b1 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/xslt/XsltViewTests.java @@ -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 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 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 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 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()); } + }