diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java index d0009394a13..26e61840cd4 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -15,15 +15,6 @@ */ package org.springframework.aop.aspectj.annotation; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.FileNotFoundException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -46,7 +37,9 @@ import org.aspectj.lang.annotation.DeclareParents; import org.aspectj.lang.annotation.DeclarePrecedence; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; + import org.junit.Test; + import org.springframework.aop.Advisor; import org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor; import org.springframework.aop.framework.Advised; @@ -66,6 +59,9 @@ import test.aop.Lockable; import test.aop.PerTargetAspect; import test.aop.TwoAdviceAspect; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + /** * Abstract tests for AspectJAdvisorFactory. * See subclasses for tests of concrete factories. diff --git a/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java index 03cf0b719e3..f858da5e86f 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -16,10 +16,6 @@ package org.springframework.aop.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.io.IOException; import org.junit.Before; @@ -27,6 +23,8 @@ import org.junit.Test; import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Dmitriy Kopylenko diff --git a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java index 7c37c37adce..dfb4b9224a2 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -16,14 +16,6 @@ package org.springframework.aop.framework; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; @@ -41,9 +33,11 @@ import junit.framework.TestCase; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; + import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.aop.Advisor; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.DynamicIntroductionAdvice; @@ -85,6 +79,8 @@ import test.mixin.LockMixinAdvisor; import test.mixin.Lockable; import test.mixin.LockedException; +import static org.junit.Assert.*; + /** * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionTestCase.java b/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java similarity index 85% rename from spring-expression/src/test/java/org/springframework/expression/spel/ExpressionTestCase.java rename to spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java index 74d5aa8e12e..23e82ee240d 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionTestCase.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/AbstractExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * 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. @@ -16,9 +16,6 @@ package org.springframework.expression.spel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import java.util.Arrays; import java.util.List; @@ -29,12 +26,14 @@ import org.springframework.expression.ParseException; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import static org.junit.Assert.*; + /** * Common superclass for expression tests. * * @author Andy Clement */ -public abstract class ExpressionTestCase { +public abstract class AbstractExpressionTests { private final static boolean DEBUG = false; @@ -44,6 +43,7 @@ public abstract class ExpressionTestCase { protected final ExpressionParser parser = new SpelExpressionParser(); protected final StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); + /** * Evaluate an expression and check that the actual result matches the expectedValue and the class of the result * matches the expectedClassOfResult. @@ -51,7 +51,7 @@ public abstract class ExpressionTestCase { * @param expectedValue the expected result for evaluating the expression * @param expectedResultType the expected class of the evaluation result */ - public void evaluate(String expression, Object expectedValue, Class expectedResultType) { + protected void evaluate(String expression, Object expectedValue, Class expectedResultType) { try { Expression expr = parser.parseExpression(expression); if (expr == null) { @@ -61,9 +61,9 @@ public abstract class ExpressionTestCase { SpelUtilities.printAbstractSyntaxTree(System.out, expr); } // Class expressionType = expr.getValueType(); - // assertEquals("Type of the expression is not as expected. Should be '"+expectedResultType+"' but is - // '"+expressionType+"'", - // expectedResultType,expressionType); + // assertEquals("Type of the expression is not as expected. Should be '" + + // expectedResultType + "' but is '" + // + expressionType + "'", expectedResultType, expressionType); Object value = expr.getValue(eContext); @@ -73,7 +73,7 @@ public abstract class ExpressionTestCase { return; // no point doing other checks } assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue, - null); + null); } Class resultType = value.getClass(); @@ -86,20 +86,23 @@ public abstract class ExpressionTestCase { if (expectedValue instanceof String) { assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, - ExpressionTestCase.stringValueOf(value)); - } else { + AbstractExpressionTests.stringValueOf(value)); + } + else { assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value); } - } catch (EvaluationException ee) { + } + catch (EvaluationException ee) { ee.printStackTrace(); fail("Unexpected Exception: " + ee.getMessage()); - } catch (ParseException pe) { + } + catch (ParseException pe) { pe.printStackTrace(); fail("Unexpected Exception: " + pe.getMessage()); } } - public void evaluateAndAskForReturnType(String expression, Object expectedValue, Class expectedResultType) { + protected void evaluateAndAskForReturnType(String expression, Object expectedValue, Class expectedResultType) { try { Expression expr = parser.parseExpression(expression); if (expr == null) { @@ -109,16 +112,16 @@ public abstract class ExpressionTestCase { SpelUtilities.printAbstractSyntaxTree(System.out, expr); } // Class expressionType = expr.getValueType(); - // assertEquals("Type of the expression is not as expected. Should be '"+expectedResultType+"' but is - // '"+expressionType+"'", - // expectedResultType,expressionType); + // assertEquals("Type of the expression is not as expected. Should be '" + + // expectedResultType + "' but is '" + // + expressionType + "'", expectedResultType, expressionType); Object value = expr.getValue(eContext, expectedResultType); if (value == null) { if (expectedValue == null) return; // no point doing other checks assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue, - null); + null); } Class resultType = value.getClass(); @@ -128,11 +131,13 @@ public abstract class ExpressionTestCase { assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value); // isAssignableFrom would allow some room for compatibility // in the above expression... - } catch (EvaluationException ee) { + } + catch (EvaluationException ee) { SpelEvaluationException ex = (SpelEvaluationException) ee; ex.printStackTrace(); fail("Unexpected EvaluationException: " + ex.getMessage()); - } catch (ParseException pe) { + } + catch (ParseException pe) { fail("Unexpected ParseException: " + pe.getMessage()); } } @@ -147,7 +152,7 @@ public abstract class ExpressionTestCase { * @param expectedClassOfResult the expected class of the evaluation result * @param shouldBeWritable should the parsed expression be writable? */ - public void evaluate(String expression, Object expectedValue, Class expectedClassOfResult, + protected void evaluate(String expression, Object expectedValue, Class expectedClassOfResult, boolean shouldBeWritable) { try { Expression e = parser.parseExpression(expression); @@ -163,20 +168,21 @@ public abstract class ExpressionTestCase { return; // no point doing other // checks assertEquals("Expression returned null value, but expected '" + expectedValue + "'", expectedValue, - null); + null); } Class resultType = value.getClass(); if (expectedValue instanceof String) { assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, - ExpressionTestCase.stringValueOf(value)); - } else { + AbstractExpressionTests.stringValueOf(value)); + } + else { assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value); } -// assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, -// ExpressionTestCase.stringValueOf(value)); + // assertEquals("Did not get expected value for expression '" + expression + + // "'.", expectedValue, stringValueOf(value)); assertEquals("Type of the result was not as expected. Expected '" + expectedClassOfResult - + "' but result was of type '" + resultType + "'", expectedClassOfResult - .equals/* isAssignableFrom */(resultType), true); + + "' but result was of type '" + resultType + "'", + expectedClassOfResult.equals/* isAssignableFrom */(resultType), true); // TODO isAssignableFrom would allow some room for compatibility // in the above expression... @@ -187,10 +193,12 @@ public abstract class ExpressionTestCase { else fail("Expected the expression to be readonly but it is not"); } - } catch (EvaluationException ee) { + } + catch (EvaluationException ee) { ee.printStackTrace(); fail("Unexpected Exception: " + ee.getMessage()); - } catch (ParseException pe) { + } + catch (ParseException pe) { pe.printStackTrace(); fail("Unexpected Exception: " + pe.getMessage()); } @@ -228,15 +236,16 @@ public abstract class ExpressionTestCase { if (expectedReturnType != null) { @SuppressWarnings("unused") Object value = expr.getValue(eContext, expectedReturnType); - } else { + } + else { @SuppressWarnings("unused") Object value = expr.getValue(eContext); } fail("Should have failed with message " + expectedMessage); - } catch (EvaluationException ee) { + } + catch (EvaluationException ee) { SpelEvaluationException ex = (SpelEvaluationException) ee; if (ex.getMessageCode() != expectedMessage) { -// System.out.println(ex.getMessage()); ex.printStackTrace(); assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode()); } @@ -262,13 +271,15 @@ public abstract class ExpressionTestCase { fail("Insert does not match, expected 'null' but insert value was '" + inserts[i - 1] + "'"); } - } else if (inserts[i - 1] == null) { + } + else if (inserts[i - 1] == null) { if (otherProperties[i] != null) { ex.printStackTrace(); fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was 'null'"); } - } else if (!inserts[i - 1].equals(otherProperties[i])) { + } + else if (!inserts[i - 1].equals(otherProperties[i])) { ex.printStackTrace(); fail("Insert does not match, expected '" + otherProperties[i] + "' but insert value was '" + inserts[i - 1] + "'"); @@ -276,7 +287,8 @@ public abstract class ExpressionTestCase { } } } - } catch (ParseException pe) { + } + catch (ParseException pe) { pe.printStackTrace(); fail("Unexpected Exception: " + pe.getMessage()); } @@ -295,21 +307,22 @@ public abstract class ExpressionTestCase { Expression expr = parser.parseExpression(expression); SpelUtilities.printAbstractSyntaxTree(System.out, expr); fail("Parsing should have failed!"); - } catch (ParseException pe) { -// pe.printStackTrace(); -// Throwable t = pe.getCause(); -// if (t == null) { -// fail("ParseException caught with no defined cause"); -// } -// if (!(t instanceof SpelEvaluationException)) { -// t.printStackTrace(); -// fail("Cause of parse exception is not a SpelException"); -// } -// SpelEvaluationException ex = (SpelEvaluationException) t; -// pe.printStackTrace(); - SpelParseException ex = (SpelParseException)pe; + } + catch (ParseException pe) { + // pe.printStackTrace(); + // Throwable t = pe.getCause(); + // if (t == null) { + // fail("ParseException caught with no defined cause"); + // } + // if (!(t instanceof SpelEvaluationException)) { + // t.printStackTrace(); + // fail("Cause of parse exception is not a SpelException"); + // } + // SpelEvaluationException ex = (SpelEvaluationException) t; + // pe.printStackTrace(); + SpelParseException ex = (SpelParseException) pe; if (ex.getMessageCode() != expectedMessage) { -// System.out.println(ex.getMessage()); + // System.out.println(ex.getMessage()); ex.printStackTrace(); assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode()); } @@ -340,16 +353,17 @@ public abstract class ExpressionTestCase { } } - public static String stringValueOf(Object value) { + protected static String stringValueOf(Object value) { return stringValueOf(value, false); } + /** * Produce a nice string representation of the input object. * * @param value object to be formatted * @return a nice string */ - public static String stringValueOf(Object value, boolean isNested) { + protected static String stringValueOf(Object value, boolean isNested) { // do something nice for arrays if (value == null) { return "null"; @@ -368,7 +382,8 @@ public abstract class ExpressionTestCase { sb.append(stringValueOf(l[j])); } sb.append("}"); - } else if (primitiveType == Long.TYPE) { + } + else if (primitiveType == Long.TYPE) { long[] l = (long[]) value; sb.append("long[").append(l.length).append("]{"); for (int j = 0; j < l.length; j++) { @@ -378,11 +393,13 @@ public abstract class ExpressionTestCase { sb.append(stringValueOf(l[j])); } sb.append("}"); - } else { + } + else { throw new RuntimeException("Please implement support for type " + primitiveType.getName() + " in ExpressionTestCase.stringValueOf()"); } - } else if (value.getClass().getComponentType().isArray()) { + } + else if (value.getClass().getComponentType().isArray()) { List l = Arrays.asList((Object[]) value); if (!isNested) { sb.append(value.getClass().getComponentType().getName()); @@ -397,7 +414,8 @@ public abstract class ExpressionTestCase { sb.append(stringValueOf(object, true)); } sb.append("}"); - } else { + } + else { List l = Arrays.asList((Object[]) value); if (!isNested) { sb.append(value.getClass().getComponentType().getName()); @@ -414,7 +432,8 @@ public abstract class ExpressionTestCase { sb.append("}"); } return sb.toString(); - } else { + } + else { return value.toString(); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java index 1667115532a..41725f24d76 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ArrayConstructorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * 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. @@ -13,35 +13,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.expression.spel; -import org.junit.Assert; import org.junit.Test; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import static org.junit.Assert.*; + /** * Test construction of arrays. * * @author Andy Clement */ -public class ArrayConstructorTests extends ExpressionTestCase { +public class ArrayConstructorTests extends AbstractExpressionTests { @Test - public void testSimpleArrayWithInitializer() { + public void simpleArrayWithInitializer() { evaluateArrayBuildingExpression("new int[]{1,2,3}", "[1,2,3]"); evaluateArrayBuildingExpression("new int[]{}", "[]"); evaluate("new int[]{}.length", "0", Integer.class); } @Test - public void testConversion() { + public void conversion() { evaluate("new String[]{1,2,3}[0]", "1", String.class); evaluate("new int[]{'123'}[0]", 123, Integer.class); } @Test - public void testMultidimensionalArrays() { + public void multidimensionalArrays() { evaluateAndCheckError("new int[][]{{1,2},{3,4}}", SpelMessage.MULTIDIM_ARRAY_INITIALIZER_NOT_SUPPORTED); evaluateAndCheckError("new int[3][]", SpelMessage.MISSING_ARRAY_DIMENSION); evaluateAndCheckError("new int[]", SpelMessage.MISSING_ARRAY_DIMENSION); @@ -50,7 +52,7 @@ public class ArrayConstructorTests extends ExpressionTestCase { } @Test - public void testPrimitiveTypeArrayConstructors() { + public void primitiveTypeArrayConstructors() { evaluateArrayBuildingExpression("new int[]{1,2,3,4}", "[1,2,3,4]"); evaluateArrayBuildingExpression("new boolean[]{true,false,true}", "[true,false,true]"); evaluateArrayBuildingExpression("new char[]{'a','b','c'}", "[a,b,c]"); @@ -62,7 +64,7 @@ public class ArrayConstructorTests extends ExpressionTestCase { } @Test - public void testPrimitiveTypeArrayConstructorsElements() { + public void primitiveTypeArrayConstructorsElements() { evaluate("new int[]{1,2,3,4}[0]", 1, Integer.class); evaluate("new boolean[]{true,false,true}[0]", true, Boolean.class); evaluate("new char[]{'a','b','c'}[0]", 'a', Character.class); @@ -75,7 +77,7 @@ public class ArrayConstructorTests extends ExpressionTestCase { } @Test - public void testErrorCases() { + public void errorCases() { evaluateAndCheckError("new char[7]{'a','c','d','e'}", SpelMessage.INITIALIZER_LENGTH_INCORRECT); evaluateAndCheckError("new char[3]{'a','c','d','e'}", SpelMessage.INITIALIZER_LENGTH_INCORRECT); evaluateAndCheckError("new char[2]{'hello','world'}", SpelMessage.TYPE_CONVERSION_ERROR); @@ -83,32 +85,32 @@ public class ArrayConstructorTests extends ExpressionTestCase { } @Test - public void testTypeArrayConstructors() { + public void typeArrayConstructors() { evaluate("new String[]{'a','b','c','d'}[1]", "b", String.class); evaluateAndCheckError("new String[]{'a','b','c','d'}.size()", SpelMessage.METHOD_NOT_FOUND, 30, "size()", - "java.lang.String[]"); + "java.lang.String[]"); evaluate("new String[]{'a','b','c','d'}.length", 4, Integer.class); } @Test - public void testBasicArray() { + public void basicArray() { evaluate("new String[3]", "java.lang.String[3]{null,null,null}", String[].class); } @Test - public void testMultiDimensionalArray() { + public void multiDimensionalArray() { evaluate("new String[2][2]", "[Ljava.lang.String;[2]{[2]{null,null},[2]{null,null}}", String[][].class); evaluate("new String[3][2][1]", - "[[Ljava.lang.String;[3]{[2]{[1]{null},[1]{null}},[2]{[1]{null},[1]{null}},[2]{[1]{null},[1]{null}}}", - String[][][].class); + "[[Ljava.lang.String;[3]{[2]{[1]{null},[1]{null}},[2]{[1]{null},[1]{null}},[2]{[1]{null},[1]{null}}}", + String[][][].class); } @Test - public void testConstructorInvocation03() { + public void constructorInvocation03() { evaluateAndCheckError("new String[]", SpelMessage.MISSING_ARRAY_DIMENSION); } - public void testConstructorInvocation04() { + public void constructorInvocation04() { evaluateAndCheckError("new Integer[3]{'3','ghi','5'}", SpelMessage.INCORRECT_ELEMENT_TYPE_FOR_ARRAY, 4); } @@ -116,8 +118,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { SpelExpressionParser parser = new SpelExpressionParser(); Expression e = parser.parseExpression(expression); Object o = e.getValue(); - Assert.assertNotNull(o); - Assert.assertTrue(o.getClass().isArray()); + assertNotNull(o); + assertTrue(o.getClass().isArray()); StringBuilder s = new StringBuilder(); s.append('['); if (o instanceof int[]) { @@ -128,7 +130,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else if (o instanceof boolean[]) { + } + else if (o instanceof boolean[]) { boolean[] array = (boolean[]) o; for (int i = 0; i < array.length; i++) { if (i > 0) { @@ -136,7 +139,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else if (o instanceof char[]) { + } + else if (o instanceof char[]) { char[] array = (char[]) o; for (int i = 0; i < array.length; i++) { if (i > 0) { @@ -144,7 +148,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else if (o instanceof long[]) { + } + else if (o instanceof long[]) { long[] array = (long[]) o; for (int i = 0; i < array.length; i++) { if (i > 0) { @@ -152,7 +157,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else if (o instanceof short[]) { + } + else if (o instanceof short[]) { short[] array = (short[]) o; for (int i = 0; i < array.length; i++) { if (i > 0) { @@ -160,7 +166,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else if (o instanceof double[]) { + } + else if (o instanceof double[]) { double[] array = (double[]) o; for (int i = 0; i < array.length; i++) { if (i > 0) { @@ -168,7 +175,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else if (o instanceof float[]) { + } + else if (o instanceof float[]) { float[] array = (float[]) o; for (int i = 0; i < array.length; i++) { if (i > 0) { @@ -176,7 +184,8 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else if (o instanceof byte[]) { + } + else if (o instanceof byte[]) { byte[] array = (byte[]) o; for (int i = 0; i < array.length; i++) { if (i > 0) { @@ -184,11 +193,12 @@ public class ArrayConstructorTests extends ExpressionTestCase { } s.append(array[i]); } - } else { - Assert.fail("Not supported " + o.getClass()); + } + else { + fail("Not supported " + o.getClass()); } s.append(']'); - Assert.assertEquals(expectedToString, s.toString()); + assertEquals(expectedToString, s.toString()); return s.toString(); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/BooleanExpressionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/BooleanExpressionTests.java index f84a53b0e43..bdc030cebad 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/BooleanExpressionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/BooleanExpressionTests.java @@ -27,7 +27,7 @@ import org.springframework.expression.spel.support.StandardTypeConverter; * @author Andy Clement * @author Oliver Becker */ -public class BooleanExpressionTests extends ExpressionTestCase { +public class BooleanExpressionTests extends AbstractExpressionTests { @Test public void testBooleanTrue() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java index 4b1c619c8ac..2d027a4b60f 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ConstructorInvocationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * 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. @@ -19,9 +19,9 @@ package org.springframework.expression.spel; import java.util.ArrayList; import java.util.List; -import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; + import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; import org.springframework.expression.ConstructorExecutor; @@ -32,12 +32,14 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.PlaceOfBirth; +import static org.junit.Assert.*; + /** * Tests invocation of constructors. * * @author Andy Clement */ -public class ConstructorInvocationTests extends ExpressionTestCase { +public class ConstructorInvocationTests extends AbstractExpressionTests { @Test public void testTypeConstructors() { @@ -46,29 +48,33 @@ public class ConstructorInvocationTests extends ExpressionTestCase { @Test public void testNonExistentType() { - evaluateAndCheckError("new FooBar()",SpelMessage.CONSTRUCTOR_INVOCATION_PROBLEM); + evaluateAndCheckError("new FooBar()", SpelMessage.CONSTRUCTOR_INVOCATION_PROBLEM); } + @SuppressWarnings("serial") static class TestException extends Exception { } static class Tester { + public static int counter; public int i; - public Tester() {} + + public Tester() { + } public Tester(int i) throws Exception { counter++; - if (i==1) { + if (i == 1) { throw new IllegalArgumentException("IllegalArgumentException for 1"); } - if (i==2) { + if (i == 2) { throw new RuntimeException("RuntimeException for 2"); } - if (i==4) { + if (i == 4) { throw new TestException(); } this.i = i; @@ -79,6 +85,8 @@ public class ConstructorInvocationTests extends ExpressionTestCase { } } + + @Test public void testConstructorThrowingException_SPR6760() { // Test ctor on inventor: @@ -93,60 +101,65 @@ public class ConstructorInvocationTests extends ExpressionTestCase { // Normal exit StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); eContext.setRootObject(new Tester()); - eContext.setVariable("bar",3); + eContext.setVariable("bar", 3); Object o = expr.getValue(eContext); - Assert.assertEquals(o,3); - Assert.assertEquals(1,parser.parseExpression("counter").getValue(eContext)); + assertEquals(o, 3); + assertEquals(1, parser.parseExpression("counter").getValue(eContext)); - // Now the expression has cached that throwException(int) is the right thing to call - // Let's change 'bar' to be a PlaceOfBirth which indicates the cached reference is - // out of date. - eContext.setVariable("bar",new PlaceOfBirth("London")); + // Now the expression has cached that throwException(int) is the right thing to + // call. Let's change 'bar' to be a PlaceOfBirth which indicates the cached + // reference is out of date. + eContext.setVariable("bar", new PlaceOfBirth("London")); o = expr.getValue(eContext); - Assert.assertEquals(0, o); + assertEquals(0, o); // That confirms the logic to mark the cached reference stale and retry is working - // Now let's cause the method to exit via exception and ensure it doesn't cause // a retry. // First, switch back to throwException(int) - eContext.setVariable("bar",3); + eContext.setVariable("bar", 3); o = expr.getValue(eContext); - Assert.assertEquals(3, o); - Assert.assertEquals(2,parser.parseExpression("counter").getValue(eContext)); + assertEquals(3, o); + assertEquals(2, parser.parseExpression("counter").getValue(eContext)); - // 4 will make it throw a checked exception - this will be wrapped by spel on the way out - eContext.setVariable("bar",4); + // 4 will make it throw a checked exception - this will be wrapped by spel on the + // way out + eContext.setVariable("bar", 4); try { o = expr.getValue(eContext); - Assert.fail("Should have failed"); - } catch (Exception e) { - // A problem occurred whilst attempting to construct an object of type 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' using arguments '(java.lang.Integer)' + fail("Should have failed"); + } + catch (Exception e) { + // A problem occurred whilst attempting to construct an object of type + // 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' + // using arguments '(java.lang.Integer)' int idx = e.getMessage().indexOf("Tester"); - if (idx==-1) { - Assert.fail("Expected reference to Tester in :"+e.getMessage()); + if (idx == -1) { + fail("Expected reference to Tester in :" + e.getMessage()); } // normal } // If counter is 4 then the method got called twice! - Assert.assertEquals(3,parser.parseExpression("counter").getValue(eContext)); - + assertEquals(3, parser.parseExpression("counter").getValue(eContext)); // 1 will make it throw a RuntimeException - SpEL will let this through - eContext.setVariable("bar",1); + eContext.setVariable("bar", 1); try { o = expr.getValue(eContext); - Assert.fail("Should have failed"); - } catch (Exception e) { - // A problem occurred whilst attempting to construct an object of type 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' using arguments '(java.lang.Integer)' + fail("Should have failed"); + } + catch (Exception e) { + // A problem occurred whilst attempting to construct an object of type + // 'org.springframework.expression.spel.ConstructorInvocationTests$Tester' + // using arguments '(java.lang.Integer)' if (e instanceof SpelEvaluationException) { e.printStackTrace(); - Assert.fail("Should not have been wrapped"); + fail("Should not have been wrapped"); } } // If counter is 5 then the method got called twice! - Assert.assertEquals(4,parser.parseExpression("counter").getValue(eContext)); + assertEquals(4, parser.parseExpression("counter").getValue(eContext)); } @Test @@ -155,58 +168,69 @@ public class ConstructorInvocationTests extends ExpressionTestCase { // reflective constructor accessor is the only one by default List constructorResolvers = ctx.getConstructorResolvers(); - Assert.assertEquals(1,constructorResolvers.size()); + assertEquals(1, constructorResolvers.size()); ConstructorResolver dummy = new DummyConstructorResolver(); ctx.addConstructorResolver(dummy); - Assert.assertEquals(2,ctx.getConstructorResolvers().size()); + assertEquals(2, ctx.getConstructorResolvers().size()); List copy = new ArrayList(); copy.addAll(ctx.getConstructorResolvers()); - Assert.assertTrue(ctx.removeConstructorResolver(dummy)); - Assert.assertFalse(ctx.removeConstructorResolver(dummy)); - Assert.assertEquals(1,ctx.getConstructorResolvers().size()); + assertTrue(ctx.removeConstructorResolver(dummy)); + assertFalse(ctx.removeConstructorResolver(dummy)); + assertEquals(1, ctx.getConstructorResolvers().size()); ctx.setConstructorResolvers(copy); - Assert.assertEquals(2,ctx.getConstructorResolvers().size()); + assertEquals(2, ctx.getConstructorResolvers().size()); } + static class DummyConstructorResolver implements ConstructorResolver { @Override - public ConstructorExecutor resolve(EvaluationContext context, String typeName, List argumentTypes) - throws AccessException { + public ConstructorExecutor resolve(EvaluationContext context, String typeName, + List argumentTypes) throws AccessException { throw new UnsupportedOperationException("Auto-generated method stub"); } } + @Test public void testVarargsInvocation01() { // Calling 'Fruit(String... strings)' - evaluate("new org.springframework.expression.spel.testresources.Fruit('a','b','c').stringscount()", 3, Integer.class); + evaluate("new org.springframework.expression.spel.testresources.Fruit('a','b','c').stringscount()", 3, + Integer.class); evaluate("new org.springframework.expression.spel.testresources.Fruit('a').stringscount()", 1, Integer.class); evaluate("new org.springframework.expression.spel.testresources.Fruit().stringscount()", 0, Integer.class); - evaluate("new org.springframework.expression.spel.testresources.Fruit(1,2,3).stringscount()", 3, Integer.class); // all need converting to strings - evaluate("new org.springframework.expression.spel.testresources.Fruit(1).stringscount()", 1, Integer.class); // needs string conversion - evaluate("new org.springframework.expression.spel.testresources.Fruit(1,'a',3.0d).stringscount()", 3, Integer.class); // first and last need conversion + // all need converting to strings + evaluate("new org.springframework.expression.spel.testresources.Fruit(1,2,3).stringscount()", 3, Integer.class); + // needs string conversion + evaluate("new org.springframework.expression.spel.testresources.Fruit(1).stringscount()", 1, Integer.class); + // first and last need conversion + evaluate("new org.springframework.expression.spel.testresources.Fruit(1,'a',3.0d).stringscount()", 3, + Integer.class); } @Test public void testVarargsInvocation02() { // Calling 'Fruit(int i, String... strings)' - returns int+length_of_strings - evaluate("new org.springframework.expression.spel.testresources.Fruit(5,'a','b','c').stringscount()", 8, Integer.class); + evaluate("new org.springframework.expression.spel.testresources.Fruit(5,'a','b','c').stringscount()", 8, + Integer.class); evaluate("new org.springframework.expression.spel.testresources.Fruit(2,'a').stringscount()", 3, Integer.class); evaluate("new org.springframework.expression.spel.testresources.Fruit(4).stringscount()", 4, Integer.class); evaluate("new org.springframework.expression.spel.testresources.Fruit(8,2,3).stringscount()", 10, Integer.class); evaluate("new org.springframework.expression.spel.testresources.Fruit(9).stringscount()", 9, Integer.class); - evaluate("new org.springframework.expression.spel.testresources.Fruit(2,'a',3.0d).stringscount()", 4, Integer.class); - evaluate("new org.springframework.expression.spel.testresources.Fruit(8,stringArrayOfThreeItems).stringscount()", 11, Integer.class); + evaluate("new org.springframework.expression.spel.testresources.Fruit(2,'a',3.0d).stringscount()", 4, + Integer.class); + evaluate( + "new org.springframework.expression.spel.testresources.Fruit(8,stringArrayOfThreeItems).stringscount()", + 11, Integer.class); } /* - * These tests are attempting to call constructors where we need to widen or convert the argument in order to - * satisfy a suitable constructor. + * These tests are attempting to call constructors where we need to widen or convert + * the argument in order to satisfy a suitable constructor. */ @Test public void testWidening01() { @@ -220,7 +244,8 @@ public class ConstructorInvocationTests extends ExpressionTestCase { @Ignore public void testArgumentConversion01() { // Closest ctor will be new String(String) and converter supports Double>String - // TODO currently failing as with new ObjectToArray converter closest constructor matched becomes String(byte[]) which fails... + // TODO currently failing as with new ObjectToArray converter closest constructor + // matched becomes String(byte[]) which fails... evaluate("new String(3.0d)", "3.0", String.class); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java index c60680ca539..f6b2c0f7cae 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java @@ -59,7 +59,7 @@ import org.springframework.expression.spel.testresources.TestPerson; * @author Giovanni Dall'Oglio Risso * @since 3.0 */ -public class EvaluationTests extends ExpressionTestCase { +public class EvaluationTests extends AbstractExpressionTests { @Test public void testCreateListsOnAttemptToIndexNull01() throws EvaluationException, ParseException { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java index 1419f1da966..1cbc03739b7 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionLanguageScenarioTests.java @@ -60,7 +60,7 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; * * @author Andy Clement */ -public class ExpressionLanguageScenarioTests extends ExpressionTestCase { +public class ExpressionLanguageScenarioTests extends AbstractExpressionTests { /** * Scenario: using the standard infrastructure and running simple expression evaluation. diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java index 583609b23e7..972b23a5756 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionStateTests.java @@ -39,7 +39,7 @@ import org.springframework.expression.spel.testresources.Inventor; * * @author Andy Clement */ -public class ExpressionStateTests extends ExpressionTestCase { +public class ExpressionStateTests extends AbstractExpressionTests { @Test public void testConstruction() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java index 5b73e2ede77..d8e871e3c98 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ExpressionWithConversionTests.java @@ -42,7 +42,7 @@ import static org.junit.Assert.*; * @author Andy Clement * @author Dave Syer */ -public class ExpressionWithConversionTests extends ExpressionTestCase { +public class ExpressionWithConversionTests extends AbstractExpressionTests { private static List listOfString = new ArrayList(); private static TypeDescriptor typeDescriptorForListOfString = null; diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java index 6729476f183..5b389cf89b8 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/InProgressTests.java @@ -32,7 +32,7 @@ import org.springframework.expression.spel.standard.SpelExpression; * * @author Andy Clement */ -public class InProgressTests extends ExpressionTestCase { +public class InProgressTests extends AbstractExpressionTests { @Test public void testRelOperatorsBetween01() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java index 26182a2397a..a0ed0f34d10 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ListTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -13,17 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.expression.spel; import java.util.ArrayList; import java.util.Collections; -import org.junit.Assert; import org.junit.Test; + import org.springframework.expression.spel.ast.InlineList; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import static org.junit.Assert.*; + /** * Test usage of inline lists. * @@ -31,11 +34,13 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; * @author Giovanni Dall'Oglio Risso * @since 3.0.4 */ -public class ListTests extends ExpressionTestCase { +public class ListTests extends AbstractExpressionTests { - // if the list is full of literals then it will be of the type unmodifiableClass rather than ArrayList + // if the list is full of literals then it will be of the type unmodifiableClass + // rather than ArrayList Class unmodifiableClass = Collections.unmodifiableList(new ArrayList()).getClass(); + @Test public void testInlineListCreation01() { evaluate("{1, 2, 3, 4, 5}", "[1, 2, 3, 4, 5]", unmodifiableClass); @@ -111,10 +116,14 @@ public class ListTests extends ExpressionTestCase { @Test public void testRelOperatorsBetween04() { - evaluate("new java.math.BigDecimal('1') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", "true", Boolean.class); - evaluate("new java.math.BigDecimal('3') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", "true", Boolean.class); - evaluate("new java.math.BigDecimal('5') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", "true", Boolean.class); - evaluate("new java.math.BigDecimal('8') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", "false", Boolean.class); + evaluate("new java.math.BigDecimal('1') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", + "true", Boolean.class); + evaluate("new java.math.BigDecimal('3') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", + "true", Boolean.class); + evaluate("new java.math.BigDecimal('5') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", + "true", Boolean.class); + evaluate("new java.math.BigDecimal('8') between {new java.math.BigDecimal('1'),new java.math.BigDecimal('5')}", + "false", Boolean.class); } @Test @@ -136,23 +145,19 @@ public class ListTests extends ExpressionTestCase { SpelExpressionParser parser = new SpelExpressionParser(); SpelExpression expression = (SpelExpression) parser.parseExpression(expressionText); SpelNode node = expression.getAST(); - Assert.assertTrue(node instanceof InlineList); + assertTrue(node instanceof InlineList); InlineList inlineList = (InlineList) node; if (expectedToBeConstant) { - Assert.assertTrue(inlineList.isConstant()); - } else { - Assert.assertFalse(inlineList.isConstant()); + assertTrue(inlineList.isConstant()); + } + else { + assertFalse(inlineList.isConstant()); } } - @Test + @Test(expected = UnsupportedOperationException.class) public void testInlineListWriting() { // list should be unmodifiable - try { - evaluate("{1, 2, 3, 4, 5}[0]=6", "[1, 2, 3, 4, 5]", unmodifiableClass); - Assert.fail(); - } catch (UnsupportedOperationException uoe) { - // success - } + evaluate("{1, 2, 3, 4, 5}[0]=6", "[1, 2, 3, 4, 5]", unmodifiableClass); } } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java index a3097e03ca4..7e389ce4900 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/LiteralTests.java @@ -27,7 +27,7 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; * * @author Andy Clement */ -public class LiteralTests extends ExpressionTestCase { +public class LiteralTests extends AbstractExpressionTests { @Test public void testLiteralBoolean01() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java index 47412fc18ad..17703a20f8c 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java @@ -37,7 +37,7 @@ import static org.junit.Assert.*; * * @author Andy Clement */ -public class MapAccessTests extends ExpressionTestCase { +public class MapAccessTests extends AbstractExpressionTests { @Test public void testSimpleMapAccess01() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java index 682dfe525ec..4487ee8eb75 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * 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. @@ -16,9 +16,6 @@ package org.springframework.expression.spel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; - import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -26,8 +23,8 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; -import org.junit.Assert; import org.junit.Test; + import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; import org.springframework.expression.BeanResolver; @@ -42,13 +39,15 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.testresources.PlaceOfBirth; +import static org.junit.Assert.*; + /** * Tests invocation of methods. * * @author Andy Clement * @author Phillip Webb */ -public class MethodInvocationTests extends ExpressionTestCase { +public class MethodInvocationTests extends AbstractExpressionTests { @Test public void testSimpleAccess01() { @@ -110,15 +109,15 @@ public class MethodInvocationTests extends ExpressionTestCase { StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); eContext.setVariable("bar",3); Object o = expr.getValue(eContext); - Assert.assertEquals(o,3); - Assert.assertEquals(1,parser.parseExpression("counter").getValue(eContext)); + assertEquals(o, 3); + assertEquals(1, parser.parseExpression("counter").getValue(eContext)); // Now the expression has cached that throwException(int) is the right thing to call // Let's change 'bar' to be a PlaceOfBirth which indicates the cached reference is // out of date. eContext.setVariable("bar",new PlaceOfBirth("London")); o = expr.getValue(eContext); - Assert.assertEquals("London", o); + assertEquals("London", o); // That confirms the logic to mark the cached reference stale and retry is working @@ -128,39 +127,39 @@ public class MethodInvocationTests extends ExpressionTestCase { // First, switch back to throwException(int) eContext.setVariable("bar",3); o = expr.getValue(eContext); - Assert.assertEquals(3, o); - Assert.assertEquals(2,parser.parseExpression("counter").getValue(eContext)); + assertEquals(3, o); + assertEquals(2, parser.parseExpression("counter").getValue(eContext)); // Now cause it to throw an exception: eContext.setVariable("bar",1); try { o = expr.getValue(eContext); - Assert.fail(); + fail(); } catch (Exception e) { if (e instanceof SpelEvaluationException) { e.printStackTrace(); - Assert.fail("Should not be a SpelEvaluationException"); + fail("Should not be a SpelEvaluationException"); } // normal } // If counter is 4 then the method got called twice! - Assert.assertEquals(3,parser.parseExpression("counter").getValue(eContext)); + assertEquals(3, parser.parseExpression("counter").getValue(eContext)); eContext.setVariable("bar",4); try { o = expr.getValue(eContext); - Assert.fail(); + fail(); } catch (Exception e) { // 4 means it will throw a checked exception - this will be wrapped if (!(e instanceof ExpressionInvocationTargetException)) { e.printStackTrace(); - Assert.fail("Should have been wrapped"); + fail("Should have been wrapped"); } // normal } // If counter is 5 then the method got called twice! - Assert.assertEquals(4,parser.parseExpression("counter").getValue(eContext)); + assertEquals(4, parser.parseExpression("counter").getValue(eContext)); } /** @@ -180,11 +179,11 @@ public class MethodInvocationTests extends ExpressionTestCase { eContext.setVariable("bar",2); try { expr.getValue(eContext); - Assert.fail(); + fail(); } catch (Exception e) { if (e instanceof SpelEvaluationException) { e.printStackTrace(); - Assert.fail("Should not be a SpelEvaluationException"); + fail("Should not be a SpelEvaluationException"); } // normal } @@ -204,13 +203,15 @@ public class MethodInvocationTests extends ExpressionTestCase { eContext.setVariable("bar",4); try { expr.getValue(eContext); - Assert.fail(); + fail(); } catch (ExpressionInvocationTargetException e) { Throwable t = e.getCause(); - Assert.assertEquals("org.springframework.expression.spel.testresources.Inventor$TestException", t.getClass().getName()); + assertEquals( + "org.springframework.expression.spel.testresources.Inventor$TestException", + t.getClass().getName()); return; } - Assert.fail("Should not be a SpelEvaluationException"); + fail("Should not be a SpelEvaluationException"); } @Test @@ -224,24 +225,24 @@ public class MethodInvocationTests extends ExpressionTestCase { // Filter will be called but not do anything, so first doit() will be invoked SpelExpression expr = (SpelExpression) parser.parseExpression("doit(1)"); String result = expr.getValue(context,String.class); - Assert.assertEquals("1",result); - Assert.assertTrue(filter.filterCalled); + assertEquals("1", result); + assertTrue(filter.filterCalled); // Filter will now remove non @Anno annotated methods filter.removeIfNotAnnotated = true; filter.filterCalled = false; expr = (SpelExpression) parser.parseExpression("doit(1)"); result = expr.getValue(context,String.class); - Assert.assertEquals("double 1.0",result); - Assert.assertTrue(filter.filterCalled); + assertEquals("double 1.0", result); + assertTrue(filter.filterCalled); // check not called for other types filter.filterCalled=false; context.setRootObject(new String("abc")); expr = (SpelExpression) parser.parseExpression("charAt(0)"); result = expr.getValue(context,String.class); - Assert.assertEquals("a",result); - Assert.assertFalse(filter.filterCalled); + assertEquals("a", result); + assertFalse(filter.filterCalled); // check de-registration works filter.filterCalled = false; @@ -249,8 +250,8 @@ public class MethodInvocationTests extends ExpressionTestCase { context.setRootObject(new TestObject()); expr = (SpelExpression) parser.parseExpression("doit(1)"); result = expr.getValue(context,String.class); - Assert.assertEquals("1",result); - Assert.assertFalse(filter.filterCalled); + assertEquals("1", result); + assertFalse(filter.filterCalled); } // Simple filter @@ -312,20 +313,20 @@ public class MethodInvocationTests extends ExpressionTestCase { // reflective method accessor is the only one by default List methodResolvers = ctx.getMethodResolvers(); - Assert.assertEquals(1,methodResolvers.size()); + assertEquals(1, methodResolvers.size()); MethodResolver dummy = new DummyMethodResolver(); ctx.addMethodResolver(dummy); - Assert.assertEquals(2,ctx.getMethodResolvers().size()); + assertEquals(2, ctx.getMethodResolvers().size()); List copy = new ArrayList(); copy.addAll(ctx.getMethodResolvers()); - Assert.assertTrue(ctx.removeMethodResolver(dummy)); - Assert.assertFalse(ctx.removeMethodResolver(dummy)); - Assert.assertEquals(1,ctx.getMethodResolvers().size()); + assertTrue(ctx.removeMethodResolver(dummy)); + assertFalse(ctx.removeMethodResolver(dummy)); + assertEquals(1, ctx.getMethodResolvers().size()); ctx.setMethodResolvers(copy); - Assert.assertEquals(2,ctx.getMethodResolvers().size()); + assertEquals(2, ctx.getMethodResolvers().size()); } static class DummyMethodResolver implements MethodResolver { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java index 394ec38817e..a0f4f878cc6 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorOverloaderTests.java @@ -30,7 +30,7 @@ import org.springframework.expression.spel.standard.SpelExpression; * * @author Andy Clement */ -public class OperatorOverloaderTests extends ExpressionTestCase { +public class OperatorOverloaderTests extends AbstractExpressionTests { static class StringAndBooleanAddition implements OperatorOverloader { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java index 12e4af382d8..0ae86345618 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/OperatorTests.java @@ -29,7 +29,7 @@ import org.springframework.expression.spel.standard.SpelExpression; * @author Andy Clement * @author Giovanni Dall'Oglio Risso */ -public class OperatorTests extends ExpressionTestCase { +public class OperatorTests extends AbstractExpressionTests { @Test public void testIntegerLiteral() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ParserErrorMessagesTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/ParserErrorMessagesTests.java index d574d96b5ac..836f9d2cd5a 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ParserErrorMessagesTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ParserErrorMessagesTests.java @@ -23,7 +23,7 @@ import org.junit.Test; * * @author Andy Clement */ -public class ParserErrorMessagesTests extends ExpressionTestCase { +public class ParserErrorMessagesTests extends AbstractExpressionTests { @Test public void testBrokenExpression01() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java index 117d7b87f20..c6230fe9843 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java @@ -44,7 +44,7 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; * * @author Andy Clement */ -public class PropertyAccessTests extends ExpressionTestCase { +public class PropertyAccessTests extends AbstractExpressionTests { @Test public void testSimpleAccess01() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java b/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java index ca44e2e762f..dcfc26afbe6 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/ScenariosForSpringSecurity.java @@ -45,7 +45,7 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; * * @author Andy Clement */ -public class ScenariosForSpringSecurity extends ExpressionTestCase { +public class ScenariosForSpringSecurity extends AbstractExpressionTests { @Test public void testScenario01_Roles() throws Exception { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java index 4f27e433d54..30d71941b9c 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SetValueTests.java @@ -38,7 +38,7 @@ import org.springframework.expression.spel.testresources.PlaceOfBirth; * @author Keith Donald * @author Andy Clement */ -public class SetValueTests extends ExpressionTestCase { +public class SetValueTests extends AbstractExpressionTests { private final static boolean DEBUG = false; diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java index 41261a4d7ce..002fef3a96c 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java @@ -48,7 +48,7 @@ import org.springframework.expression.spel.testresources.PlaceOfBirth; * * @author Andy Clement */ -public class SpelDocumentationTests extends ExpressionTestCase { +public class SpelDocumentationTests extends AbstractExpressionTests { static Inventor tesla ; static Inventor pupin ; diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index 5de7887c4c3..784bd190e4e 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -19,6 +19,7 @@ package org.springframework.expression.spel; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -66,39 +67,41 @@ import static org.junit.Assert.*; * @author Juergen Hoeller * @author Clark Duplichien * @author Phillip Webb + * @author Sam Brannen */ -public class SpelReproTests extends ExpressionTestCase { +public class SpelReproTests extends AbstractExpressionTests { @Rule public ExpectedException thrown = ExpectedException.none(); + @Test - public void testNPE_SPR5661() { + public void NPE_SPR5661() { evaluate("joinThreeStrings('a',null,'c')", "anullc", String.class); } @Test - public void testSWF1086() { + public void SWF1086() { evaluate("printDouble(T(java.math.BigDecimal).valueOf(14.35))", "14.35", String.class); } @Test - public void testDoubleCoercion() { + public void doubleCoercion() { evaluate("printDouble(14.35)", "14.35", String.class); } @Test - public void testDoubleArrayCoercion() { + public void doubleArrayCoercion() { evaluate("printDoubles(getDoublesAsStringList())", "{14.35, 15.45}", String.class); } @Test - public void testSPR5899() throws Exception { + public void SPR5899() throws Exception { StandardEvaluationContext eContext = new StandardEvaluationContext(new Spr5899Class()); Expression expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(12)"); - assertEquals(12,expr.getValue(eContext)); + assertEquals(12, expr.getValue(eContext)); expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(null)"); - assertEquals(null,expr.getValue(eContext)); + assertEquals(null, expr.getValue(eContext)); try { expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)"); expr.getValue(); @@ -111,28 +114,29 @@ public class SpelReproTests extends ExpressionTestCase { // varargs expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull3(null,'a','b')"); - assertEquals("ab",expr.getValue(eContext)); + assertEquals("ab", expr.getValue(eContext)); // varargs 2 - null is packed into the varargs expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull3(12,'a',null,'c')"); - assertEquals("anullc",expr.getValue(eContext)); + assertEquals("anullc", expr.getValue(eContext)); // check we can find the ctor ok expr = new SpelExpressionParser().parseRaw("new Spr5899Class().toString()"); - assertEquals("instance",expr.getValue(eContext)); + assertEquals("instance", expr.getValue(eContext)); expr = new SpelExpressionParser().parseRaw("new Spr5899Class(null).toString()"); - assertEquals("instance",expr.getValue(eContext)); + assertEquals("instance", expr.getValue(eContext)); // ctor varargs expr = new SpelExpressionParser().parseRaw("new Spr5899Class(null,'a','b').toString()"); - assertEquals("instance",expr.getValue(eContext)); + assertEquals("instance", expr.getValue(eContext)); // ctor varargs 2 expr = new SpelExpressionParser().parseRaw("new Spr5899Class(null,'a', null, 'b').toString()"); - assertEquals("instance",expr.getValue(eContext)); + assertEquals("instance", expr.getValue(eContext)); } + static class MyTypeLocator extends StandardTypeLocator { @Override @@ -149,60 +153,63 @@ public class SpelReproTests extends ExpressionTestCase { static class Spr5899Class { - public Spr5899Class() { - } + public Spr5899Class() { + } - public Spr5899Class(Integer i) { - } + public Spr5899Class(Integer i) { + } - public Spr5899Class(Integer i, String... s) { - } + public Spr5899Class(Integer i, String... s) { + } - public Integer tryToInvokeWithNull(Integer value) { - return value; - } + public Integer tryToInvokeWithNull(Integer value) { + return value; + } - public Integer tryToInvokeWithNull2(int i) { - return new Integer(i); - } + public Integer tryToInvokeWithNull2(int i) { + return new Integer(i); + } - public String tryToInvokeWithNull3(Integer value, String... strings) { - StringBuilder sb = new StringBuilder(); - for (String string : strings) { - if (string == null) { - sb.append("null"); - } - else { - sb.append(string); - } - } - return sb.toString(); - } + public String tryToInvokeWithNull3(Integer value, String... strings) { + StringBuilder sb = new StringBuilder(); + for (String string : strings) { + if (string == null) { + sb.append("null"); + } + else { + sb.append(string); + } + } + return sb.toString(); + } - @Override - public String toString() { - return "instance"; - } + @Override + public String toString() { + return "instance"; + } } + @Test - public void testSPR5905_InnerTypeReferences() throws Exception { + public void SPR5905_InnerTypeReferences() throws Exception { StandardEvaluationContext eContext = new StandardEvaluationContext(new Spr5899Class()); Expression expr = new SpelExpressionParser().parseRaw("T(java.util.Map$Entry)"); - assertEquals(Map.Entry.class,expr.getValue(eContext)); + assertEquals(Map.Entry.class, expr.getValue(eContext)); expr = new SpelExpressionParser().parseRaw("T(org.springframework.expression.spel.SpelReproTests$Outer$Inner).run()"); - assertEquals(12,expr.getValue(eContext)); + assertEquals(12, expr.getValue(eContext)); expr = new SpelExpressionParser().parseRaw("new org.springframework.expression.spel.SpelReproTests$Outer$Inner().run2()"); - assertEquals(13,expr.getValue(eContext)); + assertEquals(13, expr.getValue(eContext)); } + static class Outer { static class Inner { - public Inner() {} + public Inner() { + } public static int run() { return 12; @@ -214,59 +221,67 @@ public class SpelReproTests extends ExpressionTestCase { } } + @Test - public void testSPR5804() throws Exception { - Map m = new HashMap(); + public void SPR5804() throws Exception { + Map m = new HashMap(); m.put("foo", "bar"); - StandardEvaluationContext eContext = new StandardEvaluationContext(m); // root is a map instance + StandardEvaluationContext eContext = new StandardEvaluationContext(m); // root is + // a map + // instance eContext.addPropertyAccessor(new MapAccessor()); Expression expr = new SpelExpressionParser().parseRaw("['foo']"); assertEquals("bar", expr.getValue(eContext)); } @Test - public void testSPR5847() throws Exception { + public void SPR5847() throws Exception { StandardEvaluationContext eContext = new StandardEvaluationContext(new TestProperties()); String name = null; Expression expr = null; expr = new SpelExpressionParser().parseRaw("jdbcProperties['username']"); - name = expr.getValue(eContext,String.class); - assertEquals("Dave",name); + name = expr.getValue(eContext, String.class); + assertEquals("Dave", name); expr = new SpelExpressionParser().parseRaw("jdbcProperties[username]"); - name = expr.getValue(eContext,String.class); - assertEquals("Dave",name); + name = expr.getValue(eContext, String.class); + assertEquals("Dave", name); // MapAccessor required for this to work expr = new SpelExpressionParser().parseRaw("jdbcProperties.username"); eContext.addPropertyAccessor(new MapAccessor()); - name = expr.getValue(eContext,String.class); - assertEquals("Dave",name); + name = expr.getValue(eContext, String.class); + assertEquals("Dave", name); // --- dotted property names - // lookup foo on the root, then bar on that, then use that as the key into jdbcProperties + // lookup foo on the root, then bar on that, then use that as the key into + // jdbcProperties expr = new SpelExpressionParser().parseRaw("jdbcProperties[foo.bar]"); eContext.addPropertyAccessor(new MapAccessor()); - name = expr.getValue(eContext,String.class); - assertEquals("Dave2",name); + name = expr.getValue(eContext, String.class); + assertEquals("Dave2", name); // key is foo.bar expr = new SpelExpressionParser().parseRaw("jdbcProperties['foo.bar']"); eContext.addPropertyAccessor(new MapAccessor()); - name = expr.getValue(eContext,String.class); - assertEquals("Elephant",name); + name = expr.getValue(eContext, String.class); + assertEquals("Elephant", name); } + static class TestProperties { + public Properties jdbcProperties = new Properties(); public Properties foo = new Properties(); + + TestProperties() { - jdbcProperties.put("username","Dave"); - jdbcProperties.put("alias","Dave2"); - jdbcProperties.put("foo.bar","Elephant"); - foo.put("bar","alias"); + jdbcProperties.put("username", "Dave"); + jdbcProperties.put("alias", "Dave2"); + jdbcProperties.put("foo.bar", "Elephant"); + foo.put("bar", "alias"); } } @@ -274,12 +289,12 @@ public class SpelReproTests extends ExpressionTestCase { @Override public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException { - return (((Map) target).containsKey(name)); + return (((Map) target).containsKey(name)); } @Override public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException { - return new TypedValue(((Map) target).get(name)); + return new TypedValue(((Map) target).get(name)); } @Override @@ -289,53 +304,63 @@ public class SpelReproTests extends ExpressionTestCase { @Override @SuppressWarnings("unchecked") - public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException { + public void write(EvaluationContext context, Object target, String name, Object newValue) + throws AccessException { ((Map) target).put(name, newValue); } @Override public Class[] getSpecificTargetClasses() { - return new Class[] {Map.class}; + return new Class[] { Map.class }; } } + @Test - public void testNPE_SPR5673() throws Exception { + public void NPE_SPR5673() throws Exception { ParserContext hashes = TemplateExpressionParsingTests.HASH_DELIMITED_PARSER_CONTEXT; ParserContext dollars = TemplateExpressionParsingTests.DEFAULT_TEMPLATE_PARSER_CONTEXT; - checkTemplateParsing("abc${'def'} ghi","abcdef ghi"); + checkTemplateParsing("abc${'def'} ghi", "abcdef ghi"); - checkTemplateParsingError("abc${ {}( 'abc'","Missing closing ')' for '(' at position 8"); - checkTemplateParsingError("abc${ {}[ 'abc'","Missing closing ']' for '[' at position 8"); - checkTemplateParsingError("abc${ {}{ 'abc'","Missing closing '}' for '{' at position 8"); - checkTemplateParsingError("abc${ ( 'abc' }","Found closing '}' at position 14 but most recent opening is '(' at position 6"); - checkTemplateParsingError("abc${ '... }","Found non terminating string literal starting at position 6"); - checkTemplateParsingError("abc${ \"... }","Found non terminating string literal starting at position 6"); - checkTemplateParsingError("abc${ ) }","Found closing ')' at position 6 without an opening '('"); - checkTemplateParsingError("abc${ ] }","Found closing ']' at position 6 without an opening '['"); - checkTemplateParsingError("abc${ } }","No expression defined within delimiter '${}' at character 3"); - checkTemplateParsingError("abc$[ } ]",DOLLARSQUARE_TEMPLATE_PARSER_CONTEXT,"Found closing '}' at position 6 without an opening '{'"); + checkTemplateParsingError("abc${ {}( 'abc'", "Missing closing ')' for '(' at position 8"); + checkTemplateParsingError("abc${ {}[ 'abc'", "Missing closing ']' for '[' at position 8"); + checkTemplateParsingError("abc${ {}{ 'abc'", "Missing closing '}' for '{' at position 8"); + checkTemplateParsingError("abc${ ( 'abc' }", + "Found closing '}' at position 14 but most recent opening is '(' at position 6"); + checkTemplateParsingError("abc${ '... }", "Found non terminating string literal starting at position 6"); + checkTemplateParsingError("abc${ \"... }", "Found non terminating string literal starting at position 6"); + checkTemplateParsingError("abc${ ) }", "Found closing ')' at position 6 without an opening '('"); + checkTemplateParsingError("abc${ ] }", "Found closing ']' at position 6 without an opening '['"); + checkTemplateParsingError("abc${ } }", "No expression defined within delimiter '${}' at character 3"); + checkTemplateParsingError("abc$[ } ]", DOLLARSQUARE_TEMPLATE_PARSER_CONTEXT, + "Found closing '}' at position 6 without an opening '{'"); - checkTemplateParsing("abc ${\"def''g}hi\"} jkl","abc def'g}hi jkl"); - checkTemplateParsing("abc ${'def''g}hi'} jkl","abc def'g}hi jkl"); - checkTemplateParsing("}","}"); - checkTemplateParsing("${'hello'} world","hello world"); - checkTemplateParsing("Hello ${'}'}]","Hello }]"); - checkTemplateParsing("Hello ${'}'}","Hello }"); - checkTemplateParsingError("Hello ${ ( ","No ending suffix '}' for expression starting at character 6: ${ ( "); - checkTemplateParsingError("Hello ${ ( }","Found closing '}' at position 11 but most recent opening is '(' at position 9"); - checkTemplateParsing("#{'Unable to render embedded object: File ({#this == 2}'}", hashes,"Unable to render embedded object: File ({#this == 2}"); - checkTemplateParsing("This is the last odd number in the list: ${listOfNumbersUpToTen.$[#this%2==1]}",dollars,"This is the last odd number in the list: 9"); - checkTemplateParsing("Hello ${'here is a curly bracket }'}",dollars,"Hello here is a curly bracket }"); - checkTemplateParsing("He${'${'}llo ${'here is a curly bracket }'}}",dollars,"He${llo here is a curly bracket }}"); - checkTemplateParsing("Hello ${'()()()}{}{}{][]{}{][}[][][}{()()'} World",dollars,"Hello ()()()}{}{}{][]{}{][}[][][}{()() World"); - checkTemplateParsing("Hello ${'inner literal that''s got {[(])]}an escaped quote in it'} World","Hello inner literal that's got {[(])]}an escaped quote in it World"); - checkTemplateParsingError("Hello ${","No ending suffix '}' for expression starting at character 6: ${"); + checkTemplateParsing("abc ${\"def''g}hi\"} jkl", "abc def'g}hi jkl"); + checkTemplateParsing("abc ${'def''g}hi'} jkl", "abc def'g}hi jkl"); + checkTemplateParsing("}", "}"); + checkTemplateParsing("${'hello'} world", "hello world"); + checkTemplateParsing("Hello ${'}'}]", "Hello }]"); + checkTemplateParsing("Hello ${'}'}", "Hello }"); + checkTemplateParsingError("Hello ${ ( ", "No ending suffix '}' for expression starting at character 6: ${ ( "); + checkTemplateParsingError("Hello ${ ( }", + "Found closing '}' at position 11 but most recent opening is '(' at position 9"); + checkTemplateParsing("#{'Unable to render embedded object: File ({#this == 2}'}", hashes, + "Unable to render embedded object: File ({#this == 2}"); + checkTemplateParsing("This is the last odd number in the list: ${listOfNumbersUpToTen.$[#this%2==1]}", dollars, + "This is the last odd number in the list: 9"); + checkTemplateParsing("Hello ${'here is a curly bracket }'}", dollars, "Hello here is a curly bracket }"); + checkTemplateParsing("He${'${'}llo ${'here is a curly bracket }'}}", dollars, + "He${llo here is a curly bracket }}"); + checkTemplateParsing("Hello ${'()()()}{}{}{][]{}{][}[][][}{()()'} World", dollars, + "Hello ()()()}{}{}{][]{}{][}[][][}{()() World"); + checkTemplateParsing("Hello ${'inner literal that''s got {[(])]}an escaped quote in it'} World", + "Hello inner literal that's got {[(])]}an escaped quote in it World"); + checkTemplateParsingError("Hello ${", "No ending suffix '}' for expression starting at character 6: ${"); } @Test - public void testAccessingNullPropertyViaReflection_SPR5663() throws AccessException { + public void accessingNullPropertyViaReflection_SPR5663() throws AccessException { PropertyAccessor propertyAccessor = new ReflectivePropertyAccessor(); EvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); assertFalse(propertyAccessor.canRead(context, null, "abc")); @@ -348,7 +373,7 @@ public class SpelReproTests extends ExpressionTestCase { // success } try { - propertyAccessor.write(context, null, "abc","foo"); + propertyAccessor.write(context, null, "abc", "foo"); fail("Should have failed with an AccessException"); } catch (AccessException ae) { @@ -356,18 +381,18 @@ public class SpelReproTests extends ExpressionTestCase { } } - @Test - public void testNestedProperties_SPR6923() { + public void nestedProperties_SPR6923() { StandardEvaluationContext eContext = new StandardEvaluationContext(new Foo()); String name = null; Expression expr = null; expr = new SpelExpressionParser().parseRaw("resource.resource.server"); - name = expr.getValue(eContext,String.class); - assertEquals("abc",name); + name = expr.getValue(eContext, String.class); + assertEquals("abc", name); } + static class Foo { public ResourceSummary resource = new ResourceSummary(); @@ -377,6 +402,7 @@ public class SpelReproTests extends ExpressionTestCase { private final Resource resource; + ResourceSummary() { this.resource = new Resource(); } @@ -393,86 +419,90 @@ public class SpelReproTests extends ExpressionTestCase { } } + /** Should be accessing Goo.getKey because 'bar' field evaluates to "key" */ @Test - public void testIndexingAsAPropertyAccess_SPR6968_1() { + public void indexingAsAPropertyAccess_SPR6968_1() { StandardEvaluationContext eContext = new StandardEvaluationContext(new Goo()); String name = null; Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[bar]"); - name = expr.getValue(eContext,String.class); - assertEquals("hello",name); - name = expr.getValue(eContext,String.class); // will be using the cached accessor this time - assertEquals("hello",name); + name = expr.getValue(eContext, String.class); + assertEquals("hello", name); + name = expr.getValue(eContext, String.class); // will be using the cached accessor + // this time + assertEquals("hello", name); } /** Should be accessing Goo.getKey because 'bar' variable evaluates to "key" */ @Test - public void testIndexingAsAPropertyAccess_SPR6968_2() { + public void indexingAsAPropertyAccess_SPR6968_2() { StandardEvaluationContext eContext = new StandardEvaluationContext(new Goo()); - eContext.setVariable("bar","key"); + eContext.setVariable("bar", "key"); String name = null; Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[#bar]"); - name = expr.getValue(eContext,String.class); - assertEquals("hello",name); - name = expr.getValue(eContext,String.class); // will be using the cached accessor this time - assertEquals("hello",name); + name = expr.getValue(eContext, String.class); + assertEquals("hello", name); + name = expr.getValue(eContext, String.class); // will be using the cached accessor + // this time + assertEquals("hello", name); } /** $ related identifiers */ @Test - public void testDollarPrefixedIdentifier_SPR7100() { + public void dollarPrefixedIdentifier_SPR7100() { Holder h = new Holder(); StandardEvaluationContext eContext = new StandardEvaluationContext(h); eContext.addPropertyAccessor(new MapAccessor()); - h.map.put("$foo","wibble"); - h.map.put("foo$bar","wobble"); - h.map.put("foobar$$","wabble"); - h.map.put("$","wubble"); - h.map.put("$$","webble"); - h.map.put("$_$","tribble"); + h.map.put("$foo", "wibble"); + h.map.put("foo$bar", "wobble"); + h.map.put("foobar$$", "wabble"); + h.map.put("$", "wubble"); + h.map.put("$$", "webble"); + h.map.put("$_$", "tribble"); String name = null; Expression expr = null; expr = new SpelExpressionParser().parseRaw("map.$foo"); - name = expr.getValue(eContext,String.class); - assertEquals("wibble",name); + name = expr.getValue(eContext, String.class); + assertEquals("wibble", name); expr = new SpelExpressionParser().parseRaw("map.foo$bar"); - name = expr.getValue(eContext,String.class); - assertEquals("wobble",name); + name = expr.getValue(eContext, String.class); + assertEquals("wobble", name); expr = new SpelExpressionParser().parseRaw("map.foobar$$"); - name = expr.getValue(eContext,String.class); - assertEquals("wabble",name); + name = expr.getValue(eContext, String.class); + assertEquals("wabble", name); expr = new SpelExpressionParser().parseRaw("map.$"); - name = expr.getValue(eContext,String.class); - assertEquals("wubble",name); + name = expr.getValue(eContext, String.class); + assertEquals("wubble", name); expr = new SpelExpressionParser().parseRaw("map.$$"); - name = expr.getValue(eContext,String.class); - assertEquals("webble",name); + name = expr.getValue(eContext, String.class); + assertEquals("webble", name); expr = new SpelExpressionParser().parseRaw("map.$_$"); - name = expr.getValue(eContext,String.class); - assertEquals("tribble",name); + name = expr.getValue(eContext, String.class); + assertEquals("tribble", name); } /** Should be accessing Goo.wibble field because 'bar' variable evaluates to "wibble" */ @Test - public void testIndexingAsAPropertyAccess_SPR6968_3() { + public void indexingAsAPropertyAccess_SPR6968_3() { StandardEvaluationContext eContext = new StandardEvaluationContext(new Goo()); - eContext.setVariable("bar","wibble"); + eContext.setVariable("bar", "wibble"); String name = null; Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[#bar]"); // will access the field 'wibble' and not use a getter - name = expr.getValue(eContext,String.class); - assertEquals("wobble",name); - name = expr.getValue(eContext,String.class); // will be using the cached accessor this time - assertEquals("wobble",name); + name = expr.getValue(eContext, String.class); + assertEquals("wobble", name); + name = expr.getValue(eContext, String.class); // will be using the cached accessor + // this time + assertEquals("wobble", name); } /** @@ -480,60 +510,64 @@ public class SpelReproTests extends ExpressionTestCase { * "wibble" */ @Test - public void testIndexingAsAPropertyAccess_SPR6968_4() { + public void indexingAsAPropertyAccess_SPR6968_4() { Goo g = Goo.instance; StandardEvaluationContext eContext = new StandardEvaluationContext(g); - eContext.setVariable("bar","wibble"); + eContext.setVariable("bar", "wibble"); Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[#bar]='world'"); // will access the field 'wibble' and not use a getter - expr.getValue(eContext,String.class); - assertEquals("world",g.wibble); - expr.getValue(eContext,String.class); // will be using the cached accessor this time - assertEquals("world",g.wibble); + expr.getValue(eContext, String.class); + assertEquals("world", g.wibble); + expr.getValue(eContext, String.class); // will be using the cached accessor this + // time + assertEquals("world", g.wibble); } /** Should be accessing Goo.setKey field because 'bar' variable evaluates to "key" */ @Test - public void testIndexingAsAPropertyAccess_SPR6968_5() { + public void indexingAsAPropertyAccess_SPR6968_5() { Goo g = Goo.instance; StandardEvaluationContext eContext = new StandardEvaluationContext(g); Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[bar]='world'"); - expr.getValue(eContext,String.class); - assertEquals("world",g.value); - expr.getValue(eContext,String.class); // will be using the cached accessor this time - assertEquals("world",g.value); + expr.getValue(eContext, String.class); + assertEquals("world", g.value); + expr.getValue(eContext, String.class); // will be using the cached accessor this + // time + assertEquals("world", g.value); } @Test - public void testDollars() { + public void dollars() { StandardEvaluationContext eContext = new StandardEvaluationContext(new XX()); Expression expr = null; expr = new SpelExpressionParser().parseRaw("m['$foo']"); - eContext.setVariable("file_name","$foo"); - assertEquals("wibble",expr.getValue(eContext,String.class)); + eContext.setVariable("file_name", "$foo"); + assertEquals("wibble", expr.getValue(eContext, String.class)); } @Test - public void testDollars2() { + public void dollars2() { StandardEvaluationContext eContext = new StandardEvaluationContext(new XX()); Expression expr = null; expr = new SpelExpressionParser().parseRaw("m[$foo]"); - eContext.setVariable("file_name","$foo"); - assertEquals("wibble",expr.getValue(eContext,String.class)); + eContext.setVariable("file_name", "$foo"); + assertEquals("wibble", expr.getValue(eContext, String.class)); } + static class XX { - public Map m; + public Map m; + + public String floo = "bar"; - public String floo ="bar"; public XX() { - m = new HashMap(); - m.put("$foo","wibble"); - m.put("bar","siddle"); + m = new HashMap(); + m.put("$foo", "wibble"); + m.put("bar", "siddle"); } } @@ -547,6 +581,7 @@ public class SpelReproTests extends ExpressionTestCase { public String wibble = "wobble"; + public String getKey() { return "hello"; } @@ -558,9 +593,10 @@ public class SpelReproTests extends ExpressionTestCase { static class Holder { - public Map map = new HashMap(); + public Map map = new HashMap(); } + // --- private void checkTemplateParsing(String expression, String expectedValue) throws Exception { @@ -569,15 +605,17 @@ public class SpelReproTests extends ExpressionTestCase { private void checkTemplateParsing(String expression, ParserContext context, String expectedValue) throws Exception { SpelExpressionParser parser = new SpelExpressionParser(); - Expression expr = parser.parseExpression(expression,context); + Expression expr = parser.parseExpression(expression, context); assertEquals(expectedValue, expr.getValue(TestScenarioCreator.getTestEvaluationContext())); } private void checkTemplateParsingError(String expression, String expectedMessage) throws Exception { - checkTemplateParsingError(expression, TemplateExpressionParsingTests.DEFAULT_TEMPLATE_PARSER_CONTEXT, expectedMessage); + checkTemplateParsingError(expression, TemplateExpressionParsingTests.DEFAULT_TEMPLATE_PARSER_CONTEXT, + expectedMessage); } - private void checkTemplateParsingError(String expression, ParserContext context, String expectedMessage) throws Exception { + private void checkTemplateParsingError(String expression, ParserContext context, String expectedMessage) + throws Exception { SpelExpressionParser parser = new SpelExpressionParser(); try { parser.parseExpression(expression, context); @@ -595,32 +633,38 @@ public class SpelReproTests extends ExpressionTestCase { } } + private static final ParserContext DOLLARSQUARE_TEMPLATE_PARSER_CONTEXT = new ParserContext() { + @Override public String getExpressionPrefix() { return "$["; } + @Override public String getExpressionSuffix() { return "]"; } + @Override public boolean isTemplate() { return true; } }; + static class Foo2 { - public void execute(String str){ + public void execute(String str) { System.out.println("Value: " + str); } } - static class Message{ + static class Message { private String payload; + public String getPayload() { return payload; } @@ -630,6 +674,7 @@ public class SpelReproTests extends ExpressionTestCase { } } + // bean resolver tests @Test @@ -640,49 +685,50 @@ public class SpelReproTests extends ExpressionTestCase { // no resolver registered == exception try { expr = new SpelExpressionParser().parseRaw("@foo"); - assertEquals("custard",expr.getValue(eContext,String.class)); + assertEquals("custard", expr.getValue(eContext, String.class)); } catch (SpelEvaluationException see) { - assertEquals(SpelMessage.NO_BEAN_RESOLVER_REGISTERED,see.getMessageCode()); - assertEquals("foo",see.getInserts()[0]); + assertEquals(SpelMessage.NO_BEAN_RESOLVER_REGISTERED, see.getMessageCode()); + assertEquals("foo", see.getInserts()[0]); } eContext.setBeanResolver(new MyBeanResolver()); // bean exists expr = new SpelExpressionParser().parseRaw("@foo"); - assertEquals("custard",expr.getValue(eContext,String.class)); + assertEquals("custard", expr.getValue(eContext, String.class)); // bean does not exist expr = new SpelExpressionParser().parseRaw("@bar"); - assertEquals(null,expr.getValue(eContext,String.class)); + assertEquals(null, expr.getValue(eContext, String.class)); // bean name will cause AccessException expr = new SpelExpressionParser().parseRaw("@goo"); try { - assertEquals(null,expr.getValue(eContext,String.class)); + assertEquals(null, expr.getValue(eContext, String.class)); } catch (SpelEvaluationException see) { - assertEquals(SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION,see.getMessageCode()); - assertEquals("goo",see.getInserts()[0]); + assertEquals(SpelMessage.EXCEPTION_DURING_BEAN_RESOLUTION, see.getMessageCode()); + assertEquals("goo", see.getInserts()[0]); assertTrue(see.getCause() instanceof AccessException); - assertTrue(((AccessException)see.getCause()).getMessage().startsWith("DONT")); + assertTrue(((AccessException) see.getCause()).getMessage().startsWith("DONT")); } // bean exists expr = new SpelExpressionParser().parseRaw("@'foo.bar'"); - assertEquals("trouble",expr.getValue(eContext,String.class)); + assertEquals("trouble", expr.getValue(eContext, String.class)); // bean exists try { expr = new SpelExpressionParser().parseRaw("@378"); - assertEquals("trouble",expr.getValue(eContext,String.class)); + assertEquals("trouble", expr.getValue(eContext, String.class)); } catch (SpelParseException spe) { - assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode()); + assertEquals(SpelMessage.INVALID_BEAN_REFERENCE, spe.getMessageCode()); } } + static class MyBeanResolver implements BeanResolver { @Override @@ -700,6 +746,7 @@ public class SpelReproTests extends ExpressionTestCase { } } + // end bean resolver tests @Test @@ -721,8 +768,8 @@ public class SpelReproTests extends ExpressionTestCase { expr.getValue(eContext); fail(); } - catch (SpelEvaluationException see ) { - assertEquals(SpelMessage.TYPE_CONVERSION_ERROR,see.getMessageCode()); + catch (SpelEvaluationException see) { + assertEquals(SpelMessage.TYPE_CONVERSION_ERROR, see.getMessageCode()); } expr = new SpelExpressionParser().parseRaw("(false?'abc':null)"); assertEquals(null, expr.getValue()); @@ -733,8 +780,8 @@ public class SpelReproTests extends ExpressionTestCase { expr.getValue(eContext); fail(); } - catch (SpelEvaluationException see ) { - assertEquals(SpelMessage.SETVALUE_NOT_SUPPORTED,see.getMessageCode()); + catch (SpelEvaluationException see) { + assertEquals(SpelMessage.SETVALUE_NOT_SUPPORTED, see.getMessageCode()); } } @@ -751,10 +798,10 @@ public class SpelReproTests extends ExpressionTestCase { } @Test - public void testMapOfMap_SPR7244() throws Exception { - Map map = new LinkedHashMap(); + public void mapOfMap_SPR7244() throws Exception { + Map map = new LinkedHashMap(); map.put("uri", "http:"); - Map nameMap = new LinkedHashMap(); + Map nameMap = new LinkedHashMap(); nameMap.put("givenName", "Arthur"); map.put("value", nameMap); @@ -768,78 +815,85 @@ public class SpelReproTests extends ExpressionTestCase { String el2 = "#root['value']['givenName']"; exp = parser.parseExpression(el2); evaluated = exp.getValue(ctx); - assertEquals("Arthur",evaluated); + assertEquals("Arthur", evaluated); } @Test - public void testProjectionTypeDescriptors_1() throws Exception { + public void projectionTypeDescriptors_1() throws Exception { StandardEvaluationContext ctx = new StandardEvaluationContext(new C()); SpelExpressionParser parser = new SpelExpressionParser(); String el1 = "ls.![#this.equals('abc')]"; SpelExpression exp = parser.parseRaw(el1); - List value = (List)exp.getValue(ctx); + List value = (List) exp.getValue(ctx); // value is list containing [true,false] - assertEquals(Boolean.class,value.get(0).getClass()); + assertEquals(Boolean.class, value.get(0).getClass()); TypeDescriptor evaluated = exp.getValueTypeDescriptor(ctx); assertEquals(null, evaluated.getElementTypeDescriptor()); } @Test - public void testProjectionTypeDescriptors_2() throws Exception { + public void projectionTypeDescriptors_2() throws Exception { StandardEvaluationContext ctx = new StandardEvaluationContext(new C()); SpelExpressionParser parser = new SpelExpressionParser(); String el1 = "as.![#this.equals('abc')]"; SpelExpression exp = parser.parseRaw(el1); - Object[] value = (Object[])exp.getValue(ctx); + Object[] value = (Object[]) exp.getValue(ctx); // value is array containing [true,false] - assertEquals(Boolean.class,value[0].getClass()); + assertEquals(Boolean.class, value[0].getClass()); TypeDescriptor evaluated = exp.getValueTypeDescriptor(ctx); assertEquals(Boolean.class, evaluated.getElementTypeDescriptor().getType()); } @Test - public void testProjectionTypeDescriptors_3() throws Exception { + public void projectionTypeDescriptors_3() throws Exception { StandardEvaluationContext ctx = new StandardEvaluationContext(new C()); SpelExpressionParser parser = new SpelExpressionParser(); String el1 = "ms.![key.equals('abc')]"; SpelExpression exp = parser.parseRaw(el1); - List value = (List)exp.getValue(ctx); + List value = (List) exp.getValue(ctx); // value is list containing [true,false] - assertEquals(Boolean.class,value.get(0).getClass()); + assertEquals(Boolean.class, value.get(0).getClass()); TypeDescriptor evaluated = exp.getValueTypeDescriptor(ctx); assertEquals(null, evaluated.getElementTypeDescriptor()); } + static class C { + public List ls; public String[] as; - public Map ms; + public Map ms; + + C() { ls = new ArrayList(); ls.add("abc"); ls.add("def"); - as = new String[]{"abc","def"}; - ms = new HashMap(); - ms.put("abc","xyz"); - ms.put("def","pqr"); + as = new String[] { "abc", "def" }; + ms = new HashMap(); + ms.put("abc", "xyz"); + ms.put("def", "pqr"); } } static class D { + public String a; + private D(String s) { - a=s; + a = s; } @Override public String toString() { - return "D("+a+")"; + return "D(" + a + ")"; } } + @Test - public void testGreaterThanWithNulls_SPR7840() throws Exception { + public void greaterThanWithNulls_SPR7840() throws Exception { List list = new ArrayList(); list.add(new D("aaa")); list.add(new D("bbb")); @@ -854,18 +908,18 @@ public class SpelReproTests extends ExpressionTestCase { String el1 = "#root.?[a < 'hhh']"; SpelExpression exp = parser.parseRaw(el1); Object value = exp.getValue(ctx); - assertEquals("[D(aaa), D(bbb), D(null), D(ccc), D(null)]",value.toString()); + assertEquals("[D(aaa), D(bbb), D(null), D(ccc), D(null)]", value.toString()); String el2 = "#root.?[a > 'hhh']"; SpelExpression exp2 = parser.parseRaw(el2); Object value2 = exp2.getValue(ctx); - assertEquals("[D(zzz)]",value2.toString()); + assertEquals("[D(zzz)]", value2.toString()); // trim out the nulls first String el3 = "#root.?[a!=null].?[a < 'hhh']"; SpelExpression exp3 = parser.parseRaw(el3); Object value3 = exp3.getValue(ctx); - assertEquals("[D(aaa), D(bbb), D(ccc)]",value3.toString()); + assertEquals("[D(aaa), D(bbb), D(ccc)]", value3.toString()); } /** @@ -874,10 +928,11 @@ public class SpelReproTests extends ExpressionTestCase { * than a unboxing conversion. */ @Test - public void testConversionPriority_8224() throws Exception { + public void conversionPriority_8224() throws Exception { @SuppressWarnings("unused") class ConversionPriority1 { + public int getX(Number i) { return 20; } @@ -889,6 +944,7 @@ public class SpelReproTests extends ExpressionTestCase { @SuppressWarnings("unused") class ConversionPriority2 { + public int getX(int i) { return 10; } @@ -930,7 +986,7 @@ public class SpelReproTests extends ExpressionTestCase { * method accepting 'long' is ok. */ @Test - public void testWideningPrimitiveConversion_8224() throws Exception { + public void wideningPrimitiveConversion_8224() throws Exception { class WideningPrimitiveConversion { @@ -957,60 +1013,59 @@ public class SpelReproTests extends ExpressionTestCase { assertEquals(compiler, actual); } - @Test - public void varargsAndPrimitives_SPR8174() throws Exception { + public void varargsAndPrimitives_SPR8174() throws Exception { EvaluationContext emptyEvalContext = new StandardEvaluationContext(); List args = new ArrayList(); args.add(TypeDescriptor.forObject(34L)); ReflectionUtil ru = new ReflectionUtil(); - MethodExecutor me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"methodToCall",args); + MethodExecutor me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "methodToCall", args); - args.set(0,TypeDescriptor.forObject(23)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); + args.set(0, TypeDescriptor.forObject(23)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); me.execute(emptyEvalContext, ru, 45); - args.set(0,TypeDescriptor.forObject(23f)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); + args.set(0, TypeDescriptor.forObject(23f)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); me.execute(emptyEvalContext, ru, 45f); - args.set(0,TypeDescriptor.forObject(23d)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); + args.set(0, TypeDescriptor.forObject(23d)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); me.execute(emptyEvalContext, ru, 23d); - args.set(0,TypeDescriptor.forObject((short)23)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); - me.execute(emptyEvalContext, ru, (short)23); + args.set(0, TypeDescriptor.forObject((short) 23)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); + me.execute(emptyEvalContext, ru, (short) 23); - args.set(0,TypeDescriptor.forObject(23L)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); + args.set(0, TypeDescriptor.forObject(23L)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); me.execute(emptyEvalContext, ru, 23L); - args.set(0,TypeDescriptor.forObject((char)65)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); - me.execute(emptyEvalContext, ru, (char)65); + args.set(0, TypeDescriptor.forObject((char) 65)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); + me.execute(emptyEvalContext, ru, (char) 65); - args.set(0,TypeDescriptor.forObject((byte)23)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); - me.execute(emptyEvalContext, ru, (byte)23); + args.set(0, TypeDescriptor.forObject((byte) 23)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); + me.execute(emptyEvalContext, ru, (byte) 23); - args.set(0,TypeDescriptor.forObject(true)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"foo",args); + args.set(0, TypeDescriptor.forObject(true)); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "foo", args); me.execute(emptyEvalContext, ru, true); // trickier: - args.set(0,TypeDescriptor.forObject(12)); + args.set(0, TypeDescriptor.forObject(12)); args.add(TypeDescriptor.forObject(23f)); - me = new ReflectiveMethodResolver().resolve(emptyEvalContext,ru,"bar",args); - me.execute(emptyEvalContext, ru, 12,23f); + me = new ReflectiveMethodResolver().resolve(emptyEvalContext, ru, "bar", args); + me.execute(emptyEvalContext, ru, 12, 23f); } public class ReflectionUtil { public Object methodToCall(T param) { - System.out.println(param+" "+param.getClass()); + System.out.println(param + " " + param.getClass()); return "Object methodToCall(T param)"; } @@ -1019,37 +1074,44 @@ public class SpelReproTests extends ExpressionTestCase { throw new RuntimeException(); } } - public void foo(float...array) { + + public void foo(float... array) { if (array.length == 0) { throw new RuntimeException(); } } - public void foo(double...array) { + + public void foo(double... array) { if (array.length == 0) { throw new RuntimeException(); } } - public void foo(short...array) { + + public void foo(short... array) { if (array.length == 0) { throw new RuntimeException(); } } - public void foo(long...array) { + + public void foo(long... array) { if (array.length == 0) { throw new RuntimeException(); } } - public void foo(boolean...array) { + + public void foo(boolean... array) { if (array.length == 0) { throw new RuntimeException(); } } - public void foo(char...array) { + + public void foo(char... array) { if (array.length == 0) { throw new RuntimeException(); } } - public void foo(byte...array) { + + public void foo(byte... array) { if (array.length == 0) { throw new RuntimeException(); } @@ -1064,23 +1126,27 @@ public class SpelReproTests extends ExpressionTestCase { @Test - public void testReservedWords_8228() throws Exception { + public void reservedWords_8228() throws Exception { // "DIV","EQ","GE","GT","LE","LT","MOD","NE","NOT" @SuppressWarnings("unused") class Reserver { + public Reserver getReserver() { return this; } + + public String NE = "abc"; public String ne = "def"; public int DIV = 1; public int div = 3; - public Map m = new HashMap(); + public Map m = new HashMap(); + Reserver() { - m.put("NE","xyz"); + m.put("NE", "xyz"); } } @@ -1114,11 +1180,10 @@ public class SpelReproTests extends ExpressionTestCase { } @Test - public void testReservedWordProperties_9862() throws Exception { + public void reservedWordProperties_9862() throws Exception { StandardEvaluationContext ctx = new StandardEvaluationContext(); SpelExpressionParser parser = new SpelExpressionParser(); - SpelExpression expression = parser.parseRaw( - "T(org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver).CONST"); + SpelExpression expression = parser.parseRaw("T(org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver).CONST"); Object value = expression.getValue(ctx); assertEquals(value, Reserver.CONST); } @@ -1130,30 +1195,27 @@ public class SpelReproTests extends ExpressionTestCase { * in evaluation of SPEL expressions for a given context. */ @Test - public void testPropertyAccessorOrder_8211() { + public void propertyAccessorOrder_8211() { ExpressionParser expressionParser = new SpelExpressionParser(); - StandardEvaluationContext evaluationContext = - new StandardEvaluationContext(new ContextObject()); + StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new ContextObject()); evaluationContext.addPropertyAccessor(new TestPropertyAccessor("firstContext")); evaluationContext.addPropertyAccessor(new TestPropertyAccessor("secondContext")); evaluationContext.addPropertyAccessor(new TestPropertyAccessor("thirdContext")); evaluationContext.addPropertyAccessor(new TestPropertyAccessor("fourthContext")); - assertEquals("first", - expressionParser.parseExpression("shouldBeFirst").getValue(evaluationContext)); - assertEquals("second", - expressionParser.parseExpression("shouldBeSecond").getValue(evaluationContext)); - assertEquals("third", - expressionParser.parseExpression("shouldBeThird").getValue(evaluationContext)); - assertEquals("fourth", - expressionParser.parseExpression("shouldBeFourth").getValue(evaluationContext)); + assertEquals("first", expressionParser.parseExpression("shouldBeFirst").getValue(evaluationContext)); + assertEquals("second", expressionParser.parseExpression("shouldBeSecond").getValue(evaluationContext)); + assertEquals("third", expressionParser.parseExpression("shouldBeThird").getValue(evaluationContext)); + assertEquals("fourth", expressionParser.parseExpression("shouldBeFourth").getValue(evaluationContext)); } + class TestPropertyAccessor implements PropertyAccessor { private String mapName; + public TestPropertyAccessor(String mapName) { this.mapName = mapName; } @@ -1162,7 +1224,7 @@ public class SpelReproTests extends ExpressionTestCase { public Map getMap(Object target) { try { Field f = target.getClass().getDeclaredField(mapName); - return (Map) f.get(target); + return (Map) f.get(target); } catch (Exception ex) { } @@ -1181,7 +1243,7 @@ public class SpelReproTests extends ExpressionTestCase { @Override public Class[] getSpecificTargetClasses() { - return new Class[] {ContextObject.class}; + return new Class[] { ContextObject.class }; } @Override @@ -1191,7 +1253,7 @@ public class SpelReproTests extends ExpressionTestCase { @Override public void write(EvaluationContext context, Object target, String name, Object newValue) - throws AccessException { + throws AccessException { getMap(target).put(name, (String) newValue); } } @@ -1203,6 +1265,7 @@ public class SpelReproTests extends ExpressionTestCase { public Map thirdContext = new HashMap(); public Map fourthContext = new HashMap(); + public ContextObject() { firstContext.put("shouldBeFirst", "first"); secondContext.put("shouldBeFirst", "second"); @@ -1219,27 +1282,40 @@ public class SpelReproTests extends ExpressionTestCase { fourthContext.put("shouldBeFourth", "fourth"); } - public Map getFirstContext() {return firstContext;} - public Map getSecondContext() {return secondContext;} - public Map getThirdContext() {return thirdContext;} - public Map getFourthContext() {return fourthContext;} + public Map getFirstContext() { + return firstContext; + } + + public Map getSecondContext() { + return secondContext; + } + + public Map getThirdContext() { + return thirdContext; + } + + public Map getFourthContext() { + return fourthContext; + } } + /** * Test the ability to subclass the ReflectiveMethodResolver and change how it * determines the set of methods for a type. */ @Test - public void testCustomStaticFunctions_SPR9038() { + public void customStaticFunctions_SPR9038() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); List methodResolvers = new ArrayList(); methodResolvers.add(new ReflectiveMethodResolver() { + @Override protected Method[] getMethods(Class type) { try { - return new Method[] {Integer.class.getDeclaredMethod("parseInt", - new Class[] {String.class, Integer.TYPE })}; + return new Method[] { Integer.class.getDeclaredMethod("parseInt", new Class[] { String.class, + Integer.TYPE }) }; } catch (NoSuchMethodException ex) { return new Method[0]; @@ -1248,15 +1324,14 @@ public class SpelReproTests extends ExpressionTestCase { }); context.setMethodResolvers(methodResolvers); - org.springframework.expression.Expression expression = - parser.parseExpression("parseInt('-FF', 16)"); + Expression expression = parser.parseExpression("parseInt('-FF', 16)"); Integer result = expression.getValue(context, "", Integer.class); - assertEquals("Equal assertion failed: ", -255, result.intValue()); + assertEquals(-255, result.intValue()); } @Test - public void testArray() { + public void array() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = null; @@ -1273,7 +1348,7 @@ public class SpelReproTests extends ExpressionTestCase { expression = parser.parseExpression("T(java.lang.String[][][])"); result = expression.getValue(context, ""); assertEquals("Equal assertion failed: ", "class [[[Ljava.lang.String;", result.toString()); - assertEquals("T(java.lang.String[][][])",((SpelExpression)expression).toStringAST()); + assertEquals("T(java.lang.String[][][])", ((SpelExpression) expression).toStringAST()); expression = parser.parseExpression("new int[0].class"); result = expression.getValue(context, ""); @@ -1281,21 +1356,22 @@ public class SpelReproTests extends ExpressionTestCase { expression = parser.parseExpression("T(int[][])"); result = expression.getValue(context, ""); - assertEquals("Equal assertion failed: ", "class [[I", result.toString()); + assertEquals("class [[I", result.toString()); } @Test - public void SPR_9486_floatFunctionResolverTest() throws Exception { + public void SPR_9486_floatFunctionResolver() throws Exception { Number expectedResult = Math.abs(-10.2f); ExpressionParser parser = new SpelExpressionParser(); SPR_9486_FunctionsClass testObject = new SPR_9486_FunctionsClass(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("abs(-10.2f)"); + Expression expression = parser.parseExpression("abs(-10.2f)"); Number result = expression.getValue(context, testObject, Number.class); - assertEquals("Equal assertion failed for SPR_9486_floatFunctionResolverTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } + class SPR_9486_FunctionsClass { public int abs(int value) { @@ -1307,270 +1383,269 @@ public class SpelReproTests extends ExpressionTestCase { } } + @Test - public void SPR_9486_addFloatWithDoubleTest() { + public void SPR_9486_addFloatWithDouble() { Number expectedNumber = 10.21f + 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f + 10.2"); + Expression expression = parser.parseExpression("10.21f + 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_addFloatWithDoubleTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_addFloatWithFloatTest() { + public void SPR_9486_addFloatWithFloat() { Number expectedNumber = 10.21f + 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f + 10.2f"); + Expression expression = parser.parseExpression("10.21f + 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_addFloatWithFloatTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_subtractFloatWithDoubleTest() { + public void SPR_9486_subtractFloatWithDouble() { Number expectedNumber = 10.21f - 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f - 10.2"); + Expression expression = parser.parseExpression("10.21f - 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_subtractFloatWithDoubleTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_subtractFloatWithFloatTest() { + public void SPR_9486_subtractFloatWithFloat() { Number expectedNumber = 10.21f - 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f - 10.2f"); + Expression expression = parser.parseExpression("10.21f - 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_subtractFloatWithFloatTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_multiplyFloatWithDoubleTest() { + public void SPR_9486_multiplyFloatWithDouble() { Number expectedNumber = 10.21f * 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f * 10.2"); + Expression expression = parser.parseExpression("10.21f * 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for float multiplied by double Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_multiplyFloatWithFloatTest() { + public void SPR_9486_multiplyFloatWithFloat() { Number expectedNumber = 10.21f * 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f * 10.2f"); + Expression expression = parser.parseExpression("10.21f * 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for float multiply by another float Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatDivideByFloatTest() { - Number expectedNumber = -10.21f/-10.2f; + public void SPR_9486_floatDivideByFloat() { + Number expectedNumber = -10.21f / -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f / -10.2f"); + Expression expression = parser.parseExpression("-10.21f / -10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for float divide Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatDivideByDoubleTest() { - Number expectedNumber = -10.21f/-10.2; + public void SPR_9486_floatDivideByDouble() { + Number expectedNumber = -10.21f / -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f / -10.2"); + Expression expression = parser.parseExpression("-10.21f / -10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for float divide Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatEqFloatUnaryMinusTest() { - Boolean expectedResult = -10.21f == -10.2f; + public void SPR_9486_floatEqFloatUnaryMinus() { + Boolean expectedResult = -10.21f == -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f == -10.2f"); + Expression expression = parser.parseExpression("-10.21f == -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatEqFloatUnaryMinusTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatEqDoubleUnaryMinusTest() { - Boolean expectedResult = -10.21f == -10.2; + public void SPR_9486_floatEqDoubleUnaryMinus() { + Boolean expectedResult = -10.21f == -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f == -10.2"); + Expression expression = parser.parseExpression("-10.21f == -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatEqDoubleUnaryMinusTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatEqFloatTest() { - Boolean expectedResult = 10.215f == 10.2109f; + public void SPR_9486_floatEqFloat() { + Boolean expectedResult = 10.215f == 10.2109f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.215f == 10.2109f"); + Expression expression = parser.parseExpression("10.215f == 10.2109f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatEqFloatTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatEqDoubleTest() { - Boolean expectedResult = 10.215f == 10.2109; + public void SPR_9486_floatEqDouble() { + Boolean expectedResult = 10.215f == 10.2109; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.215f == 10.2109"); + Expression expression = parser.parseExpression("10.215f == 10.2109"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatEqDoubleTest() Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatNotEqFloatTest() { - Boolean expectedResult = 10.215f != 10.2109f; + public void SPR_9486_floatNotEqFloat() { + Boolean expectedResult = 10.215f != 10.2109f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.215f != 10.2109f"); + Expression expression = parser.parseExpression("10.215f != 10.2109f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatEqFloatTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatNotEqDoubleTest() { - Boolean expectedResult = 10.215f != 10.2109; + public void SPR_9486_floatNotEqDouble() { + Boolean expectedResult = 10.215f != 10.2109; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.215f != 10.2109"); + Expression expression = parser.parseExpression("10.215f != 10.2109"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatNotEqDoubleTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } - - @Test - public void SPR_9486_floatLessThanFloatTest() { + public void SPR_9486_floatLessThanFloat() { Boolean expectedNumber = -10.21f < -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f < -10.2f"); + Expression expression = parser.parseExpression("-10.21f < -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatLessThanFloatTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatLessThanDoubleTest() { + public void SPR_9486_floatLessThanDouble() { Boolean expectedNumber = -10.21f < -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f < -10.2"); + Expression expression = parser.parseExpression("-10.21f < -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatLessThanDoubleTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatLessThanOrEqualFloatTest() { + public void SPR_9486_floatLessThanOrEqualFloat() { Boolean expectedNumber = -10.21f <= -10.22f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f <= -10.22f"); + Expression expression = parser.parseExpression("-10.21f <= -10.22f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatLessThanOrEqualFloatTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatLessThanOrEqualDoubleTest() { + public void SPR_9486_floatLessThanOrEqualDouble() { Boolean expectedNumber = -10.21f <= -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f <= -10.2"); + Expression expression = parser.parseExpression("-10.21f <= -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatLessThanOrEqualDoubleTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatGreaterThanFloatTest() { + public void SPR_9486_floatGreaterThanFloat() { Boolean expectedNumber = -10.21f > -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f > -10.2f"); + Expression expression = parser.parseExpression("-10.21f > -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanFloatTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatGreaterThanDoubleTest() { + public void SPR_9486_floatGreaterThanDouble() { Boolean expectedResult = -10.21f > -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f > -10.2"); + Expression expression = parser.parseExpression("-10.21f > -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanDoubleTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatGreaterThanOrEqualFloatTest() { + public void SPR_9486_floatGreaterThanOrEqualFloat() { Boolean expectedNumber = -10.21f >= -10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f >= -10.2f"); + Expression expression = parser.parseExpression("-10.21f >= -10.2f"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanFloatTest Test: ", expectedNumber, result); + assertEquals(expectedNumber, result); } @Test - public void SPR_9486_floatGreaterThanEqualDoubleTest() { + public void SPR_9486_floatGreaterThanEqualDouble() { Boolean expectedResult = -10.21f >= -10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("-10.21f >= -10.2"); + Expression expression = parser.parseExpression("-10.21f >= -10.2"); Boolean result = expression.getValue(context, null, Boolean.class); - assertEquals("Equal assertion failed for SPR_9486_floatGreaterThanDoubleTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatModulusFloatTest() { + public void SPR_9486_floatModulusFloat() { Number expectedResult = 10.21f % 10.2f; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f % 10.2f"); + Expression expression = parser.parseExpression("10.21f % 10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_floatModulusFloatTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatModulusDoubleTest() { + public void SPR_9486_floatModulusDouble() { Number expectedResult = 10.21f % 10.2; ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f % 10.2"); + Expression expression = parser.parseExpression("10.21f % 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_floatModulusDoubleTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatPowerFloatTest() { + public void SPR_9486_floatPowerFloat() { Number expectedResult = Math.pow(10.21f, -10.2f); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f ^ -10.2f"); + Expression expression = parser.parseExpression("10.21f ^ -10.2f"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_floatPowerFloatTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9486_floatPowerDoubleTest() { + public void SPR_9486_floatPowerDouble() { Number expectedResult = Math.pow(10.21f, 10.2); ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); - org.springframework.expression.Expression expression = parser.parseExpression("10.21f ^ 10.2"); + Expression expression = parser.parseExpression("10.21f ^ 10.2"); Number result = expression.getValue(context, null, Number.class); - assertEquals("Equal assertion failed for SPR_9486_floatPowerDoubleTest Test: ", expectedResult, result); + assertEquals(expectedResult, result); } @Test - public void SPR_9994_bridgeMethodsTest() throws Exception { + public void SPR_9994_bridgeMethods() throws Exception { ReflectivePropertyAccessor accessor = new ReflectivePropertyAccessor(); StandardEvaluationContext context = new StandardEvaluationContext(); Object target = new GenericImplementation(); @@ -1579,11 +1654,11 @@ public class SpelReproTests extends ExpressionTestCase { } @Test - public void SPR_10162_onlyBridgeMethodTest() throws Exception { + public void SPR_10162_onlyBridgeMethod() throws Exception { ReflectivePropertyAccessor accessor = new ReflectivePropertyAccessor(); StandardEvaluationContext context = new StandardEvaluationContext(); Object target = new OnlyBridgeMethod(); - TypedValue value = accessor.read(context, target , "property"); + TypedValue value = accessor.read(context, target, "property"); assertEquals(Integer.class, value.getTypeDescriptor().getType()); } @@ -1641,9 +1716,11 @@ public class SpelReproTests extends ExpressionTestCase { @Test public void SPR_10125() throws Exception { StandardEvaluationContext context = new StandardEvaluationContext(); - String fromInterface = parser.parseExpression("T("+StaticFinalImpl1.class.getName()+").VALUE").getValue(context, String.class); + String fromInterface = parser.parseExpression("T(" + StaticFinalImpl1.class.getName() + ").VALUE").getValue( + context, String.class); assertThat(fromInterface, is("interfaceValue")); - String fromClass = parser.parseExpression("T("+StaticFinalImpl2.class.getName()+").VALUE").getValue(context, String.class); + String fromClass = parser.parseExpression("T(" + StaticFinalImpl2.class.getName() + ").VALUE").getValue( + context, String.class); assertThat(fromClass, is("interfaceValue")); } @@ -1705,16 +1782,22 @@ public class SpelReproTests extends ExpressionTestCase { assertEquals(ABC.C, Array.get(result, 2)); context.addMethodResolver(new MethodResolver() { + @Override - public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, List argumentTypes) throws AccessException { + public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, + List argumentTypes) throws AccessException { return new MethodExecutor() { + @Override - public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException { + public TypedValue execute(EvaluationContext context, Object target, Object... arguments) + throws AccessException { try { Method method = XYZ.class.getMethod("values"); Object value = method.invoke(target, arguments); - return new TypedValue(value, new TypeDescriptor(new MethodParameter(method, -1)).narrow(value)); - } catch (Exception ex) { + return new TypedValue(value, + new TypeDescriptor(new MethodParameter(method, -1)).narrow(value)); + } + catch (Exception ex) { throw new AccessException(ex.getMessage(), ex); } } @@ -1736,10 +1819,8 @@ public class SpelReproTests extends ExpressionTestCase { SPR10486 rootObject = new SPR10486(); Expression classNameExpression = parser.parseExpression("class.name"); Expression nameExpression = parser.parseExpression("name"); - assertThat(classNameExpression.getValue(context, rootObject), - equalTo((Object) SPR10486.class.getName())); - assertThat(nameExpression.getValue(context, rootObject), - equalTo((Object) "name")); + assertThat(classNameExpression.getValue(context, rootObject), equalTo((Object) SPR10486.class.getName())); + assertThat(nameExpression.getValue(context, rootObject), equalTo((Object) "name")); } @Test @@ -1777,16 +1858,20 @@ public class SpelReproTests extends ExpressionTestCase { Expression expr = parser.parseExpression("new java.util.ArrayList(#root)"); Object value = expr.getValue(coll); assertTrue(value instanceof ArrayList); + @SuppressWarnings("rawtypes") ArrayList list = (ArrayList) value; assertEquals("one", list.get(0)); assertEquals("two", list.get(1)); } - private static enum ABC {A, B, C} - - private static enum XYZ {X, Y, Z} + private static enum ABC { + A, B, C + } + private static enum XYZ { + X, Y, Z + } public static class BooleanHolder { @@ -1794,6 +1879,7 @@ public class SpelReproTests extends ExpressionTestCase { private boolean primitiveProperty = true; + public Boolean isSimpleProperty() { return simpleProperty; } @@ -1811,13 +1897,11 @@ public class SpelReproTests extends ExpressionTestCase { } } - private static interface GenericInterface { public T getProperty(); } - private static class GenericImplementation implements GenericInterface { @Override @@ -1826,7 +1910,6 @@ public class SpelReproTests extends ExpressionTestCase { } } - static class PackagePrivateClassWithGetter { public Integer getProperty() { @@ -1834,33 +1917,28 @@ public class SpelReproTests extends ExpressionTestCase { } } - public static class OnlyBridgeMethod extends PackagePrivateClassWithGetter { } - public static interface StaticFinal { public static final String VALUE = "interfaceValue"; } - public abstract static class AbstractStaticFinal implements StaticFinal { } - public static class StaticFinalImpl1 extends AbstractStaticFinal implements StaticFinal { } - public static class StaticFinalImpl2 extends AbstractStaticFinal { } - public static class SPR10486 { private String name = "name"; + public String getName() { return name; } @@ -1870,7 +1948,6 @@ public class SpelReproTests extends ExpressionTestCase { } } - static class SPR11142 { public String isSomething() { @@ -1878,11 +1955,11 @@ public class SpelReproTests extends ExpressionTestCase { } } - static class TestClass2 { // SPR-9194 String string; + public TestClass2(String string) { this.string = string; } @@ -1894,7 +1971,7 @@ public class SpelReproTests extends ExpressionTestCase { public boolean equals(Object o) { if (o instanceof TestClass2) { - return string.equals(((TestClass2)o).string); + return string.equals(((TestClass2) o).string); } return false; } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java index 165aecdf055..ec147ea4faf 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/TemplateExpressionParsingTests.java @@ -34,7 +34,7 @@ import static org.junit.Assert.*; * @author Andy Clement * @author Juergen Hoeller */ -public class TemplateExpressionParsingTests extends ExpressionTestCase { +public class TemplateExpressionParsingTests extends AbstractExpressionTests { public static final ParserContext DEFAULT_TEMPLATE_PARSER_CONTEXT = new ParserContext() { @Override diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java index 65007ab5679..f50fad15cfb 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/VariableAndFunctionTests.java @@ -27,7 +27,7 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; * * @author Andy Clement */ -public class VariableAndFunctionTests extends ExpressionTestCase { +public class VariableAndFunctionTests extends AbstractExpressionTests { @Test public void testVariableAccess01() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java index dcf02b11f9f..32447dda910 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java @@ -29,7 +29,7 @@ import org.springframework.expression.EvaluationContext; import org.springframework.expression.ParseException; import org.springframework.expression.PropertyAccessor; import org.springframework.expression.TypedValue; -import org.springframework.expression.spel.ExpressionTestCase; +import org.springframework.expression.spel.AbstractExpressionTests; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; import org.springframework.expression.spel.SpelUtilities; @@ -44,7 +44,7 @@ import static org.junit.Assert.*; * * @author Andy Clement */ -public class ReflectionHelperTests extends ExpressionTestCase { +public class ReflectionHelperTests extends AbstractExpressionTests { @Test public void testFormatHelperForClassName() { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java index 737b074ff3e..02c8982af54 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/support/StandardComponentsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * 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. @@ -18,8 +18,8 @@ package org.springframework.expression.spel.support; import java.util.List; -import org.junit.Assert; import org.junit.Test; + import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.EvaluationException; import org.springframework.expression.Operation; @@ -28,45 +28,42 @@ import org.springframework.expression.TypeComparator; import org.springframework.expression.TypeConverter; import org.springframework.expression.TypeLocator; +import static org.junit.Assert.*; + public class StandardComponentsTests { @Test public void testStandardEvaluationContext() { StandardEvaluationContext context = new StandardEvaluationContext(); - Assert.assertNotNull(context.getTypeComparator()); + assertNotNull(context.getTypeComparator()); TypeComparator tc = new StandardTypeComparator(); context.setTypeComparator(tc); - Assert.assertEquals(tc,context.getTypeComparator()); + assertEquals(tc, context.getTypeComparator()); TypeLocator tl = new StandardTypeLocator(); context.setTypeLocator(tl); - Assert.assertEquals(tl,context.getTypeLocator()); + assertEquals(tl, context.getTypeLocator()); } - @Test + @Test(expected = EvaluationException.class) public void testStandardOperatorOverloader() throws EvaluationException { OperatorOverloader oo = new StandardOperatorOverloader(); - Assert.assertFalse(oo.overridesOperation(Operation.ADD, null, null)); - try { - oo.operate(Operation.ADD, 2, 3); - Assert.fail("should have failed"); - } catch (EvaluationException e) { - // success - } + assertFalse(oo.overridesOperation(Operation.ADD, null, null)); + oo.operate(Operation.ADD, 2, 3); } @Test public void testStandardTypeLocator() { StandardTypeLocator tl = new StandardTypeLocator(); List prefixes = tl.getImportPrefixes(); - Assert.assertEquals(1,prefixes.size()); + assertEquals(1, prefixes.size()); tl.registerImport("java.util"); prefixes = tl.getImportPrefixes(); - Assert.assertEquals(2,prefixes.size()); + assertEquals(2, prefixes.size()); tl.removeImport("java.util"); prefixes = tl.getImportPrefixes(); - Assert.assertEquals(1,prefixes.size()); + assertEquals(1, prefixes.size()); } @Test @@ -76,4 +73,3 @@ public class StandardComponentsTests { } } - 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 8178d704522..33fd19b36e0 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -28,7 +28,6 @@ import org.custommonkey.xmlunit.NamespaceContext; import org.custommonkey.xmlunit.SimpleNamespaceContext; import org.custommonkey.xmlunit.XMLUnit; import org.custommonkey.xmlunit.XpathEngine; -import org.junit.Assert; import org.junit.Test; import org.mockito.InOrder; import org.springframework.core.io.ClassPathResource; @@ -42,7 +41,7 @@ import org.xml.sax.ContentHandler; import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.junit.Assert.*; import static org.mockito.Matchers.*; -import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.*; /** * Tests the {@link CastorMarshaller} class. @@ -55,53 +54,53 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { /** * Represents the expected result that doesn't contain the xml declaration. */ - private static final String DOCUMENT_EXPECTED_STRING = "" + - "" + - "42"; + private static final String DOCUMENT_EXPECTED_STRING = "" + + "" + + "42"; /** * Represents the expected result that doesn't contain the xml namespaces. */ - private static final String SUPPRESSED_NAMESPACE_EXPECTED_STRING = - "42"; + private static final String SUPPRESSED_NAMESPACE_EXPECTED_STRING = "42"; /** * Represents the expected result with modified root element name. */ - private static final String ROOT_ELEMENT_EXPECTED_STRING = "" + - "" + - "42"; + private static final String ROOT_ELEMENT_EXPECTED_STRING = "" + + "" + + "42"; /** * Represents the expected result with 'xsi:type' attribute. */ - private static final String XSI_EXPECTED_STRING = "" + - "" + - "test8"; + private static final String XSI_EXPECTED_STRING = "" + + "" + + "test8"; /** * Represents the expected result with suppressed 'xsi:type' attribute. */ - private static final String SUPPRESSED_XSI_EXPECTED_STRING = "" + - "test8"; + private static final String SUPPRESSED_XSI_EXPECTED_STRING = "" + + "test8"; /** * Represents the expected result with 'xsi:type' attribute for root element. */ - private static final String ROOT_WITH_XSI_EXPECTED_STRING = "" + - "" + - "" + - "test8"; + private static final String ROOT_WITH_XSI_EXPECTED_STRING = "" + + "" + + "" + + "test8"; /** * Represents the expected result without 'xsi:type' attribute for root element. */ - private static final String ROOT_WITHOUT_XSI_EXPECTED_STRING = "" + - "" + - "test8"; + private static final String ROOT_WITHOUT_XSI_EXPECTED_STRING = "" + + "" + + "test8"; + @Override protected Marshaller createMarshaller() throws Exception { @@ -129,10 +128,13 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { InOrder ordered = inOrder(contentHandler); ordered.verify(contentHandler).startDocument(); ordered.verify(contentHandler).startPrefixMapping("tns", "http://samples.springframework.org/flight"); - ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), eq("tns:flights"), isA(Attributes.class)); - ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), eq("tns:flight"), isA(Attributes.class)); - ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), eq("tns:number"), isA(Attributes.class)); - ordered.verify(contentHandler).characters(eq(new char[]{'4', '2'}), eq(0), eq(2)); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flights"), + eq("tns:flights"), isA(Attributes.class)); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("flight"), + eq("tns:flight"), isA(Attributes.class)); + ordered.verify(contentHandler).startElement(eq("http://samples.springframework.org/flight"), eq("number"), + eq("tns:number"), isA(Attributes.class)); + ordered.verify(contentHandler).characters(eq(new char[] { '4', '2' }), eq(0), eq(2)); ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "number", "tns:number"); ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flight", "tns:flight"); ordered.verify(contentHandler).endElement("http://samples.springframework.org/flight", "flights", "tns:flights"); @@ -142,8 +144,8 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { @Test public void supports() throws Exception { - Assert.assertTrue("CastorMarshaller does not support Flights", marshaller.supports(Flights.class)); - Assert.assertTrue("CastorMarshaller does not support Flight", marshaller.supports(Flight.class)); + assertTrue("CastorMarshaller does not support Flights", marshaller.supports(Flights.class)); + assertTrue("CastorMarshaller does not support Flight", marshaller.supports(Flight.class)); } @Test @@ -186,8 +188,8 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { getCastorMarshaller().setMarshalAsDocument(true); String result = marshalFlights(); assertXMLEqual("Marshaller wrote invalid result", DOCUMENT_EXPECTED_STRING, result); - Assert.assertTrue("Result doesn't contain xml declaration.", - result.contains("")); + assertTrue("Result doesn't contain xml declaration.", + result.contains("")); } @Test @@ -196,7 +198,7 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { getCastorMarshaller().setMarshalAsDocument(true); String result = marshalFlights(); assertXMLEqual("Marshaller wrote invalid result", EXPECTED_STRING, result); - Assert.assertFalse("Result contains xml declaration.", result.matches("<\\?\\s*xml")); + assertFalse("Result contains xml declaration.", result.matches("<\\?\\s*xml")); } @Test @@ -215,7 +217,7 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { String result = marshalFlights(); assertXpathEvaluatesTo("The xsi:noNamespaceSchemaLocation hasn't been written or has invalid value.", - noNamespaceSchemaLocation, "/tns:flights/@xsi:noNamespaceSchemaLocation", result); + noNamespaceSchemaLocation, "/tns:flights/@xsi:noNamespaceSchemaLocation", result); assertXMLEqual("Marshaller wrote invalid result", EXPECTED_STRING, result); } @@ -227,7 +229,7 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { String result = marshalFlights(); assertXpathEvaluatesTo("The xsi:noNamespaceSchemaLocation hasn't been written or has invalid value.", - schemaLocation, "/tns:flights/@xsi:schemaLocation", result); + schemaLocation, "/tns:flights/@xsi:schemaLocation", result); assertXMLEqual("Marshaller wrote invalid result", EXPECTED_STRING, result); } @@ -253,7 +255,6 @@ public class CastorMarshallerTests extends AbstractMarshallerTests { assertXMLEqual("Marshaller wrote invalid result", ROOT_WITHOUT_XSI_EXPECTED_STRING, result); } - private CastorMarshaller getCastorMarshaller() { return (CastorMarshaller) marshaller; } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10025Tests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10025Tests.java index 9091ecde490..c715e6b1802 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10025Tests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10025Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * 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. @@ -13,16 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.test.web.servlet; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; - -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -39,6 +36,11 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; + /** * Test for SPR-10025. * @@ -57,6 +59,7 @@ public class Spr10025Tests { private MockMvc mockMvc; + @Before public void setup() { this.mockMvc = webAppContextSetup(this.wac).build(); @@ -86,8 +89,8 @@ public class Spr10025Tests { @ResponseBody public void handle() { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); - Assert.assertNull(attributes.getAttribute("foo1", RequestAttributes.SCOPE_REQUEST)); - Assert.assertNotNull(attributes.getAttribute("foo2", RequestAttributes.SCOPE_REQUEST)); + assertNull(attributes.getAttribute("foo1", RequestAttributes.SCOPE_REQUEST)); + assertNotNull(attributes.getAttribute("foo2", RequestAttributes.SCOPE_REQUEST)); } } diff --git a/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java b/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java index 32713e951c7..1f4d919e096 100644 --- a/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java +++ b/spring-test/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -13,18 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.test.web.servlet; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; +package org.springframework.test.web.servlet; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -39,8 +36,14 @@ import org.springframework.web.context.WebApplicationContext; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import static org.junit.Assert.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; + /** * Tests for SPR-10093 (support for OPTIONS requests). + * * @author Arnaud Cogoluègnes */ @RunWith(SpringJUnit4ClassRunner.class) @@ -48,47 +51,48 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @ContextConfiguration public class Spr10093Tests { - @Autowired - private WebApplicationContext wac; + @Autowired + private WebApplicationContext wac; - private MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = webAppContextSetup(this.wac).dispatchOptions(true).build(); - } - - @Test - public void test() throws Exception { - MyController controller = this.wac.getBean(MyController.class); - int initialCount = controller.counter.get(); - this.mockMvc.perform(options("/myUrl")).andExpect(status().isOk()); - - Assert.assertEquals(initialCount+1,controller.counter.get()); - } + private MockMvc mockMvc; - @Configuration - @EnableWebMvc - static class WebConfig extends WebMvcConfigurerAdapter { + @Before + public void setup() { + this.mockMvc = webAppContextSetup(this.wac).dispatchOptions(true).build(); + } - @Bean - public MyController myController() { - return new MyController(); - } - } + @Test + public void test() throws Exception { + MyController controller = this.wac.getBean(MyController.class); + int initialCount = controller.counter.get(); + this.mockMvc.perform(options("/myUrl")).andExpect(status().isOk()); - @Controller - private static class MyController { + assertEquals(initialCount + 1, controller.counter.get()); + } - private AtomicInteger counter = new AtomicInteger(0); - @RequestMapping(value="/myUrl",method=RequestMethod.OPTIONS) - @ResponseBody - public void handle() { - counter.incrementAndGet(); - } - } + @Configuration + @EnableWebMvc + static class WebConfig extends WebMvcConfigurerAdapter { + @Bean + public MyController myController() { + return new MyController(); + } + } + + @Controller + private static class MyController { + + private AtomicInteger counter = new AtomicInteger(0); + + + @RequestMapping(value = "/myUrl", method = RequestMethod.OPTIONS) + @ResponseBody + public void handle() { + counter.incrementAndGet(); + } + } } diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java index 472812b63d8..a587687c06f 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractAsyncHttpRequestFactoryTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -23,8 +23,6 @@ import java.util.Arrays; import java.util.Locale; import java.util.concurrent.Future; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; @@ -37,6 +35,8 @@ import org.springframework.util.StreamUtils; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; +import static org.junit.Assert.*; + public abstract class AbstractAsyncHttpRequestFactoryTestCase extends AbstractJettyServerTestCase { diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractJettyServerTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractJettyServerTestCase.java index f0d5e8292e5..4694869d6d9 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractJettyServerTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractJettyServerTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * 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. @@ -19,6 +19,7 @@ package org.springframework.http.client; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; + import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; @@ -30,13 +31,15 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; + import org.junit.AfterClass; -import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.springframework.util.FileCopyUtils; import org.springframework.util.SocketUtils; +import static org.junit.Assert.*; + /** @author Arjen Poutsma */ public class AbstractJettyServerTestCase { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AbstractFlashMapManagerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AbstractFlashMapManagerTests.java index 98564ae6c1f..7385f52da8b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AbstractFlashMapManagerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/AbstractFlashMapManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * 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. @@ -17,12 +17,6 @@ package org.springframework.web.servlet.support; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -33,11 +27,14 @@ import javax.servlet.http.HttpServletResponse; 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.web.servlet.FlashMap; import org.springframework.web.util.WebUtils; +import static org.junit.Assert.*; + /** * Test fixture for testing {@link AbstractFlashMapManager} methods. *