Migrate exception checking tests to use AssertJ

Migrate tests that use `@Test(expectedException=...)` or
`try...fail...catch` to use AssertJ's `assertThatException`
instead.
This commit is contained in:
Phillip Webb
2019-05-20 10:34:51 -07:00
parent fb26fc3f94
commit 02850f357f
561 changed files with 6592 additions and 10389 deletions

View File

@@ -19,17 +19,17 @@ package org.springframework.expression.spel;
import java.util.Arrays;
import java.util.List;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Common superclass for expression tests.
@@ -59,9 +59,7 @@ public abstract class AbstractExpressionTests {
*/
public void evaluate(String expression, Object expectedValue, Class<?> expectedResultType) {
Expression expr = parser.parseExpression(expression);
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).as("expression").isNotNull();
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
}
@@ -91,9 +89,7 @@ public abstract class AbstractExpressionTests {
public void evaluateAndAskForReturnType(String expression, Object expectedValue, Class<?> expectedResultType) {
Expression expr = parser.parseExpression(expression);
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).as("expression").isNotNull();
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
}
@@ -124,9 +120,7 @@ public abstract class AbstractExpressionTests {
*/
public void evaluate(String expression, Object expectedValue, Class<?> expectedClassOfResult, boolean shouldBeWritable) {
Expression expr = parser.parseExpression(expression);
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).as("expression").isNotNull();
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
}
@@ -148,13 +142,7 @@ public abstract class AbstractExpressionTests {
assertTrue("Type of the result was not as expected. Expected '" + expectedClassOfResult +
"' but result was of type '" + resultType + "'", expectedClassOfResult.equals(resultType));
boolean isWritable = expr.isWritable(context);
if (isWritable != shouldBeWritable) {
if (shouldBeWritable)
fail("Expected the expression to be writable but it is not");
else
fail("Expected the expression to be readonly but it is not");
}
assertThat(expr.isWritable(context)).as("isWritable").isEqualTo(shouldBeWritable);
}
/**
@@ -181,59 +169,31 @@ public abstract class AbstractExpressionTests {
*/
protected void evaluateAndCheckError(String expression, Class<?> expectedReturnType, SpelMessage expectedMessage,
Object... otherProperties) {
try {
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> {
Expression expr = parser.parseExpression(expression);
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).as("expression").isNotNull();
if (expectedReturnType != null) {
expr.getValue(context, expectedReturnType);
}
else {
expr.getValue(context);
}
fail("Should have failed with message " + expectedMessage);
}
catch (EvaluationException ee) {
SpelEvaluationException ex = (SpelEvaluationException) ee;
if (ex.getMessageCode() != expectedMessage) {
assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode());
}
if (otherProperties != null && otherProperties.length != 0) {
}).satisfies(ex -> {
assertThat(ex.getMessageCode()).isEqualTo(expectedMessage);
if (!ObjectUtils.isEmpty(otherProperties)) {
// first one is expected position of the error within the string
int pos = ((Integer) otherProperties[0]).intValue();
assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
assertThat(ex.getPosition()).as("position").isEqualTo(pos);
if (otherProperties.length > 1) {
// Check inserts match
Object[] inserts = ex.getInserts();
if (inserts == null) {
inserts = new Object[0];
}
if (inserts.length < otherProperties.length - 1) {
fail("Cannot check " + (otherProperties.length - 1) +
" properties of the exception, it only has " + inserts.length + " inserts");
}
for (int i = 1; i < otherProperties.length; i++) {
if (otherProperties[i] == null) {
if (inserts[i - 1] != null) {
fail("Insert does not match, expected 'null' but insert value was '" +
inserts[i - 1] + "'");
}
}
else if (inserts[i - 1] == null) {
if (otherProperties[i] != null) {
fail("Insert does not match, expected '" + otherProperties[i] +
"' but insert value was 'null'");
}
}
else if (!inserts[i - 1].equals(otherProperties[i])) {
fail("Insert does not match, expected '" + otherProperties[i] +
"' but insert value was '" + inserts[i - 1] + "'");
}
}
assertThat(inserts).as("inserts").hasSizeGreaterThanOrEqualTo(otherProperties.length - 1);
Object[] expectedInserts = new Object[inserts.length];
System.arraycopy(otherProperties, 1, expectedInserts, 0, expectedInserts.length);
assertThat(inserts).as("inserts").containsExactly(expectedInserts);
}
}
}
});
}
/**
@@ -245,39 +205,25 @@ public abstract class AbstractExpressionTests {
* @param otherProperties the expected inserts within the message
*/
protected void parseAndCheckError(String expression, SpelMessage expectedMessage, Object... otherProperties) {
try {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
Expression expr = parser.parseExpression(expression);
SpelUtilities.printAbstractSyntaxTree(System.out, expr);
fail("Parsing should have failed!");
}
catch (ParseException pe) {
SpelParseException ex = (SpelParseException)pe;
if (ex.getMessageCode() != expectedMessage) {
assertEquals("Failed to get expected message", expectedMessage, ex.getMessageCode());
}
}).satisfies(ex -> {
assertThat(ex.getMessageCode()).isEqualTo(expectedMessage);
if (otherProperties != null && otherProperties.length != 0) {
// first one is expected position of the error within the string
int pos = ((Integer) otherProperties[0]).intValue();
assertEquals("Did not get correct position reported in error ", pos, ex.getPosition());
assertThat(pos).as("reported position").isEqualTo(pos);
if (otherProperties.length > 1) {
// Check inserts match
Object[] inserts = ex.getInserts();
if (inserts == null) {
inserts = new Object[0];
}
if (inserts.length < otherProperties.length - 1) {
fail("Cannot check " + (otherProperties.length - 1) +
" properties of the exception, it only has " + inserts.length + " inserts");
}
for (int i = 1; i < otherProperties.length; i++) {
if (!inserts[i - 1].equals(otherProperties[i])) {
fail("Insert does not match, expected '" + otherProperties[i] +
"' but insert value was '" + inserts[i - 1] + "'");
}
}
assertThat(inserts).as("inserts").hasSizeGreaterThanOrEqualTo(otherProperties.length - 1);
Object[] expectedInserts = new Object[inserts.length];
System.arraycopy(otherProperties, 1, expectedInserts, 0, expectedInserts.length);
assertThat(inserts).as("inserts").containsExactly(expectedInserts);
}
}
}
});
}

View File

@@ -24,7 +24,6 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Test construction of arrays.
@@ -199,7 +198,7 @@ public class ArrayConstructorTests extends AbstractExpressionTests {
}
}
else {
fail("Not supported " + o.getClass());
throw new IllegalStateException("Not supported " + o.getClass());
}
s.append(']');
assertEquals(expectedToString, s.toString());

View File

@@ -32,10 +32,11 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.PlaceOfBirth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests invocation of constructors.
@@ -129,38 +130,25 @@ public class ConstructorInvocationTests extends AbstractExpressionTests {
// 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);
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) {
fail("Expected reference to Tester in :" + e.getMessage());
}
// normal
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
expr.getValue(eContext))
.withMessageContaining("Tester");
// A problem occurred whilst attempting to construct an object of type
// 'org.springframework.expression.spel.ConstructorInvocationTests$Tester'
// using arguments '(java.lang.Integer)'
// If counter is 4 then the method got called twice!
assertEquals(3, parser.parseExpression("counter").getValue(eContext));
// 1 will make it throw a RuntimeException - SpEL will let this through
eContext.setVariable("bar", 1);
try {
o = expr.getValue(eContext);
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();
fail("Should not have been wrapped");
}
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
expr.getValue(eContext))
.satisfies(ex -> assertThat(ex).isNotInstanceOf(SpelEvaluationException.class));
// A problem occurred whilst attempting to construct an object of type
// 'org.springframework.expression.spel.ConstructorInvocationTests$Tester'
// using arguments '(java.lang.Integer)'
// If counter is 5 then the method got called twice!
assertEquals(4, parser.parseExpression("counter").getValue(eContext));
}

View File

@@ -42,6 +42,9 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.support.StandardTypeLocator;
import org.springframework.expression.spel.testresources.TestPerson;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
@@ -49,7 +52,6 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests the evaluation of real expressions in a real context.
@@ -75,21 +77,15 @@ public class EvaluationTests extends AbstractExpressionTests {
assertEquals("", o);
assertEquals(4, testClass.list.size());
try {
o = parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass));
fail();
}
catch (EvaluationException ee) {
ee.printStackTrace();
// success!
}
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
parser.parseExpression("list2[3]").getValue(new StandardEvaluationContext(testClass)));
o = parser.parseExpression("foo[3]").getValue(new StandardEvaluationContext(testClass));
assertEquals("", o);
assertEquals(4, testClass.getFoo().size());
}
@Test(expected = SpelEvaluationException.class)
@Test
public void testCreateMapsOnAttemptToIndexNull01() {
TestClass testClass = new TestClass();
StandardEvaluationContext ctx = new StandardEvaluationContext(testClass);
@@ -100,12 +96,13 @@ public class EvaluationTests extends AbstractExpressionTests {
o = parser.parseExpression("map").getValue(ctx);
assertNotNull(o);
o = parser.parseExpression("map2['a']").getValue(ctx);
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("map2['a']").getValue(ctx));
// map2 should be null, there is no setter
}
// wibble2 should be null (cannot be initialized dynamically), there is no setter
@Test(expected = SpelEvaluationException.class)
@Test
public void testCreateObjectsOnAttemptToReferenceNull() {
TestClass testClass = new TestClass();
StandardEvaluationContext ctx = new StandardEvaluationContext(testClass);
@@ -116,7 +113,8 @@ public class EvaluationTests extends AbstractExpressionTests {
o = parser.parseExpression("wibble").getValue(ctx);
assertNotNull(o);
o = parser.parseExpression("wibble2.bar").getValue(ctx);
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("wibble2.bar").getValue(ctx));
}
@Test
@@ -205,15 +203,10 @@ public class EvaluationTests extends AbstractExpressionTests {
String pattern = "^(?=[a-z0-9-]{1,47})([a-z0-9]+[-]{0,1}){1,47}[a-z0-9]{1}$";
String expression = "'abcde-fghijklmn-o42pasdfasdfasdf.qrstuvwxyz10x.xx.yyy.zasdfasfd' matches \'" + pattern + "\'";
Expression expr = parser.parseExpression(expression);
try {
expr.getValue();
fail("Should have exceeded threshold");
}
catch (EvaluationException ee) {
SpelEvaluationException see = (SpelEvaluationException) ee;
assertEquals(SpelMessage.FLAWED_PATTERN, see.getMessageCode());
assertTrue(see.getCause() instanceof IllegalStateException);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(
expr::getValue)
.withCauseInstanceOf(IllegalStateException.class)
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.FLAWED_PATTERN));
}
// mixing operators
@@ -239,14 +232,12 @@ public class EvaluationTests extends AbstractExpressionTests {
@Test
public void testRogueTrailingDotCausesNPE_SPR6866() {
try {
new SpelExpressionParser().parseExpression("placeOfBirth.foo.");
fail("Should have failed to parse");
}
catch (SpelParseException ex) {
assertEquals(SpelMessage.OOD, ex.getMessageCode());
assertEquals(16, ex.getPosition());
}
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
new SpelExpressionParser().parseExpression("placeOfBirth.foo."))
.satisfies(ex -> {
assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OOD);
assertThat(ex.getPosition()).isEqualTo(16);
});
}
// nested properties
@@ -262,14 +253,12 @@ public class EvaluationTests extends AbstractExpressionTests {
@Test
public void testPropertiesNested03() throws ParseException {
try {
new SpelExpressionParser().parseRaw("placeOfBirth.23");
fail();
}
catch (SpelParseException spe) {
assertEquals(SpelMessage.UNEXPECTED_DATA_AFTER_DOT, spe.getMessageCode());
assertEquals("23", spe.getInserts()[0]);
}
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
new SpelExpressionParser().parseRaw("placeOfBirth.23"))
.satisfies(ex -> {
assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.UNEXPECTED_DATA_AFTER_DOT);
assertThat(ex.getInserts()[0]).isEqualTo("23");
});
}
// methods
@@ -331,29 +320,34 @@ public class EvaluationTests extends AbstractExpressionTests {
evaluate("!false", "true", Boolean.class);
}
@Test(expected = EvaluationException.class)
@Test
public void testUnaryNotWithNullValue() {
parser.parseExpression("!null").getValue();
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
parser.parseExpression("!null")::getValue);
}
@Test(expected = EvaluationException.class)
@Test
public void testAndWithNullValueOnLeft() {
parser.parseExpression("null and true").getValue();
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
parser.parseExpression("null and true")::getValue);
}
@Test(expected = EvaluationException.class)
@Test
public void testAndWithNullValueOnRight() {
parser.parseExpression("true and null").getValue();
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
parser.parseExpression("true and null")::getValue);
}
@Test(expected = EvaluationException.class)
@Test
public void testOrWithNullValueOnLeft() {
parser.parseExpression("null or false").getValue();
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
parser.parseExpression("null or false")::getValue);
}
@Test(expected = EvaluationException.class)
@Test
public void testOrWithNullValueOnRight() {
parser.parseExpression("false or null").getValue();
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
parser.parseExpression("false or null")::getValue);
}
// assignment
@@ -392,9 +386,10 @@ public class EvaluationTests extends AbstractExpressionTests {
evaluate("2>4?(3>2?true:false):(5<3?true:false)", false, Boolean.class);
}
@Test(expected = EvaluationException.class)
@Test
public void testTernaryOperatorWithNullValue() {
parser.parseExpression("null ? 0 : 1").getValue();
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
parser.parseExpression("null ? 0 : 1")::getValue);
}
@Test
@@ -552,13 +547,8 @@ public class EvaluationTests extends AbstractExpressionTests {
@Test
public void testResolvingList() {
StandardEvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
try {
assertFalse(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
fail("should have failed to find List");
}
catch (EvaluationException ee) {
// success - List not found
}
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
((StandardTypeLocator) context.getTypeLocator()).registerImport("java.util");
assertTrue(parser.parseExpression("T(List)!=null").getValue(context, Boolean.class));
}
@@ -631,15 +621,9 @@ public class EvaluationTests extends AbstractExpressionTests {
// Register a custom MethodFilter...
MethodFilter filter = new CustomMethodFilter();
try {
context.registerMethodFilter(String.class, filter);
fail("should have failed");
}
catch (IllegalStateException ise) {
assertEquals(
"Method filter cannot be set as the reflective method resolver is not in use",
ise.getMessage());
}
assertThatIllegalStateException().isThrownBy(() ->
context.registerMethodFilter(String.class, filter))
.withMessage("Method filter cannot be set as the reflective method resolver is not in use");
}
/**
@@ -672,16 +656,12 @@ public class EvaluationTests extends AbstractExpressionTests {
assertEquals("",value);
// Now turn off growing and reference off the end
ctx = new StandardEvaluationContext(instance);
StandardEvaluationContext failCtx = new StandardEvaluationContext(instance);
parser = new SpelExpressionParser(new SpelParserConfiguration(false, false));
e = parser.parseExpression("listOfStrings[3]");
try {
e.getValue(ctx, String.class);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS, see.getMessageCode());
}
Expression failExp = parser.parseExpression("listOfStrings[3]");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
failExp.getValue(failCtx, String.class))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS));
}
@Test
@@ -710,13 +690,9 @@ public class EvaluationTests extends AbstractExpressionTests {
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
Expression e = parser.parseExpression("#this++");
assertEquals(42,i.intValue());
try {
e.getValue(ctx, Integer.class);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e.getValue(ctx, Integer.class))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE));
}
@Test
@@ -831,25 +807,16 @@ public class EvaluationTests extends AbstractExpressionTests {
Spr9751 helper = new Spr9751();
StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
Expression e;
e = parser.parseExpression("m()++");
try {
e.getValue(ctx, Double.TYPE);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE, see.getMessageCode());
}
Expression e1 = parser.parseExpression("m()++");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e1.getValue(ctx, Double.TYPE))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_INCREMENTABLE));
e = parser.parseExpression("++m()");
try {
e.getValue(ctx, Double.TYPE);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_INCREMENTABLE, see.getMessageCode());
}
Expression e2 = parser.parseExpression("++m()");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e2.getValue(ctx, Double.TYPE))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_INCREMENTABLE));
}
@Test
@@ -857,22 +824,14 @@ public class EvaluationTests extends AbstractExpressionTests {
Integer i = 42;
StandardEvaluationContext ctx = new StandardEvaluationContext(i);
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
try {
Expression e = parser.parseExpression("++1");
e.getValue(ctx, Integer.class);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode());
}
try {
Expression e = parser.parseExpression("1++");
e.getValue(ctx, Integer.class);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode());
}
Expression e1 = parser.parseExpression("++1");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e1.getValue(ctx, Double.TYPE))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE));
Expression e2 = parser.parseExpression("1++");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e2.getValue(ctx, Double.TYPE))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE));
}
@Test
@@ -882,13 +841,9 @@ public class EvaluationTests extends AbstractExpressionTests {
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
Expression e = parser.parseExpression("#this--");
assertEquals(42, i.intValue());
try {
e.getValue(ctx, Integer.class);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e.getValue(ctx, Integer.class))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE));
}
@Test
@@ -1002,25 +957,16 @@ public class EvaluationTests extends AbstractExpressionTests {
Spr9751 helper = new Spr9751();
StandardEvaluationContext ctx = new StandardEvaluationContext(helper);
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
Expression e;
e = parser.parseExpression("m()--");
try {
e.getValue(ctx, Double.TYPE);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE, see.getMessageCode());
}
Expression e1 = parser.parseExpression("m()--");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e1.getValue(ctx, Double.TYPE))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_DECREMENTABLE));
e = parser.parseExpression("--m()");
try {
e.getValue(ctx, Double.TYPE);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.OPERAND_NOT_DECREMENTABLE, see.getMessageCode());
}
Expression e2 = parser.parseExpression("--m()");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e2.getValue(ctx, Double.TYPE))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERAND_NOT_DECREMENTABLE));
}
@@ -1029,22 +975,15 @@ public class EvaluationTests extends AbstractExpressionTests {
Integer i = 42;
StandardEvaluationContext ctx = new StandardEvaluationContext(i);
ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
try {
Expression e = parser.parseExpression("--1");
e.getValue(ctx, Integer.class);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode());
}
try {
Expression e = parser.parseExpression("1--");
e.getValue(ctx, Integer.class);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode());
}
Expression e1 = parser.parseExpression("--1");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e1.getValue(ctx, Integer.class))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE));
Expression e2 = parser.parseExpression("1--");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e2.getValue(ctx, Integer.class))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.NOT_ASSIGNABLE));
}
@Test
@@ -1380,19 +1319,6 @@ public class EvaluationTests extends AbstractExpressionTests {
assertEquals(100, helper.iii);
}
private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) {
try {
Expression e = parser.parseExpression(expressionString);
SpelUtilities.printAbstractSyntaxTree(System.out, e);
e.getValue(eContext);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(messageCode, see.getMessageCode());
}
}
private void expectFailNotAssignable(ExpressionParser parser, EvaluationContext eContext, String expressionString) {
expectFail(parser, eContext, expressionString, SpelMessage.NOT_ASSIGNABLE);
}
@@ -1409,6 +1335,13 @@ public class EvaluationTests extends AbstractExpressionTests {
expectFail(parser, eContext, expressionString, SpelMessage.OPERAND_NOT_DECREMENTABLE);
}
private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) {
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() -> {
Expression e = parser.parseExpression(expressionString);
SpelUtilities.printAbstractSyntaxTree(System.out, e);
e.getValue(eContext);
}).satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(messageCode));
}
static class CustomMethodResolver implements MethodResolver {

View File

@@ -35,8 +35,9 @@ import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
///CLOVER:OFF
@@ -82,8 +83,7 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {
assertEquals(String.class, value.getClass());
}
catch (EvaluationException | ParseException ex) {
ex.printStackTrace();
fail("Unexpected Exception: " + ex.getMessage());
throw new AssertionError(ex.getMessage(), ex);
}
}
@@ -187,8 +187,7 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {
}
catch (EvaluationException | ParseException ex) {
ex.printStackTrace();
fail("Unexpected Exception: " + ex.getMessage());
throw new AssertionError(ex.getMessage(), ex);
}
}
@@ -206,14 +205,9 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {
Expression expr = parser.parseRaw("orange");
Object value = expr.getValue(ctx);
assertEquals(Color.orange, value);
try {
expr.setValue(ctx, Color.blue);
fail("Should not be allowed to set oranges to be blue !");
}
catch (SpelEvaluationException ee) {
assertEquals(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ee.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expr.setValue(ctx, Color.blue))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL));
}
@Test
@@ -228,13 +222,9 @@ public class ExpressionLanguageScenarioTests extends AbstractExpressionTests {
Object value = expr.getValue(ctx);
assertEquals(Color.green, value);
try {
expr.setValue(ctx, Color.blue);
fail("Should not be allowed to set peas to be blue !");
}
catch (SpelEvaluationException ee) {
assertEquals(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ee.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expr.setValue(ctx, Color.blue))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL));
}

View File

@@ -29,10 +29,12 @@ import org.springframework.expression.TypedValue;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.Inventor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
/**
* Tests for the expression state object - some features are not yet exploited in the language (eg nested scopes)
@@ -140,13 +142,8 @@ public class ExpressionStateTests extends AbstractExpressionTests {
ExpressionState state = getState();
assertEquals(state.getRootContextObject().getValue(), state.getActiveContextObject().getValue());
try {
state.popActiveContextObject();
fail("stack should be empty...");
}
catch (IllegalStateException ese) {
// success
}
assertThatIllegalStateException().isThrownBy(
state::popActiveContextObject);
state.pushActiveContextObject(new TypedValue(34));
assertEquals(34, state.getActiveContextObject().getValue());
@@ -222,23 +219,13 @@ public class ExpressionStateTests extends AbstractExpressionTests {
@Test
public void testOperators() {
ExpressionState state = getState();
try {
state.operate(Operation.ADD,1,2);
fail("should have failed");
}
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES, sEx.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
state.operate(Operation.ADD,1,2))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES));
try {
state.operate(Operation.ADD,null,null);
fail("should have failed");
}
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES, sEx.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
state.operate(Operation.ADD,null,null))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OPERATOR_NOT_SUPPORTED_BETWEEN_TYPES));
}
@Test
@@ -252,14 +239,10 @@ public class ExpressionStateTests extends AbstractExpressionTests {
ExpressionState state = getState();
assertNotNull(state.getEvaluationContext().getTypeLocator());
assertEquals(Integer.class, state.findType("java.lang.Integer"));
try {
state.findType("someMadeUpName");
fail("Should have failed to find it");
}
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.TYPE_NOT_FOUND, sEx.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
state.findType("someMadeUpName"))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_NOT_FOUND));
}
@Test

View File

@@ -25,6 +25,7 @@ import org.springframework.expression.spel.ast.InlineList;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -156,9 +157,10 @@ public class ListTests extends AbstractExpressionTests {
}
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void testInlineListWriting() {
// list should be unmodifiable
evaluate("{1, 2, 3, 4, 5}[0]=6", "[1, 2, 3, 4, 5]", unmodifiableClass);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
evaluate("{1, 2, 3, 4, 5}[0]=6", "[1, 2, 3, 4, 5]", unmodifiableClass));
}
}

View File

@@ -23,9 +23,10 @@ import org.springframework.expression.EvaluationException;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.fail;
/**
* @author Andy Clement
@@ -35,15 +36,15 @@ public class LiteralExpressionTests {
@Test
public void testGetValue() throws Exception {
LiteralExpression lEx = new LiteralExpression("somevalue");
checkString("somevalue", lEx.getValue());
checkString("somevalue", lEx.getValue(String.class));
assertThat(lEx.getValue()).isInstanceOf(String.class).isEqualTo("somevalue");
assertThat(lEx.getValue(String.class)).isInstanceOf(String.class).isEqualTo("somevalue");
EvaluationContext ctx = new StandardEvaluationContext();
checkString("somevalue", lEx.getValue(ctx));
checkString("somevalue", lEx.getValue(ctx, String.class));
checkString("somevalue", lEx.getValue(new Rooty()));
checkString("somevalue", lEx.getValue(new Rooty(), String.class));
checkString("somevalue", lEx.getValue(ctx, new Rooty()));
checkString("somevalue", lEx.getValue(ctx, new Rooty(),String.class));
assertThat(lEx.getValue(ctx)).isInstanceOf(String.class).isEqualTo("somevalue");
assertThat(lEx.getValue(ctx, String.class)).isInstanceOf(String.class).isEqualTo("somevalue");
assertThat(lEx.getValue(new Rooty())).isInstanceOf(String.class).isEqualTo("somevalue");
assertThat(lEx.getValue(new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("somevalue");
assertThat(lEx.getValue(ctx, new Rooty())).isInstanceOf(String.class).isEqualTo("somevalue");
assertThat(lEx.getValue(ctx, new Rooty(),String.class)).isInstanceOf(String.class).isEqualTo("somevalue");
assertEquals("somevalue", lEx.getExpressionString());
assertFalse(lEx.isWritable(new StandardEvaluationContext()));
assertFalse(lEx.isWritable(new Rooty()));
@@ -54,33 +55,15 @@ public class LiteralExpressionTests {
@Test
public void testSetValue() {
try {
LiteralExpression lEx = new LiteralExpression("somevalue");
lEx.setValue(new StandardEvaluationContext(), "flibble");
fail("Should have got an exception that the value cannot be set");
}
catch (EvaluationException ee) {
// success, not allowed - whilst here, check the expression value in the exception
assertEquals("somevalue", ee.getExpressionString());
}
try {
LiteralExpression lEx = new LiteralExpression("somevalue");
lEx.setValue(new Rooty(), "flibble");
fail("Should have got an exception that the value cannot be set");
}
catch (EvaluationException ee) {
// success, not allowed - whilst here, check the expression value in the exception
assertEquals("somevalue", ee.getExpressionString());
}
try {
LiteralExpression lEx = new LiteralExpression("somevalue");
lEx.setValue(new StandardEvaluationContext(), new Rooty(), "flibble");
fail("Should have got an exception that the value cannot be set");
}
catch (EvaluationException ee) {
// success, not allowed - whilst here, check the expression value in the exception
assertEquals("somevalue", ee.getExpressionString());
}
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
new LiteralExpression("somevalue").setValue(new StandardEvaluationContext(), "flibble"))
.satisfies(ex -> assertThat(ex.getExpressionString()).isEqualTo("somevalue"));
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
new LiteralExpression("somevalue").setValue(new Rooty(), "flibble"))
.satisfies(ex -> assertThat(ex.getExpressionString()).isEqualTo("somevalue"));
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
new LiteralExpression("somevalue").setValue(new StandardEvaluationContext(), new Rooty(), "flibble"))
.satisfies(ex -> assertThat(ex.getExpressionString()).isEqualTo("somevalue"));
}
@Test
@@ -96,13 +79,4 @@ public class LiteralExpressionTests {
assertEquals(String.class, lEx.getValueTypeDescriptor(new StandardEvaluationContext(), new Rooty()).getType());
}
private void checkString(String expectedString, Object value) {
if (!(value instanceof String)) {
fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")");
}
if (!((String) value).equals(expectedString)) {
fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'");
}
}
}

View File

@@ -28,6 +28,7 @@ import org.springframework.expression.spel.ast.InlineMap;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -134,10 +135,11 @@ public class MapTests extends AbstractExpressionTests {
}
}
@Test(expected = UnsupportedOperationException.class)
@Test
public void testInlineMapWriting() {
// list should be unmodifiable
evaluate("{a:1, b:2, c:3, d:4, e:5}[a]=6", "[a:1,b: 2,c: 3,d: 4,e: 5]", unmodifiableClass);
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
evaluate("{a:1, b:2, c:3, d:4, e:5}[a]=6", "[a:1,b: 2,c: 3,d: 4,e: 5]", unmodifiableClass));
}
@Test

View File

@@ -39,11 +39,12 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.PlaceOfBirth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests invocation of methods.
@@ -124,31 +125,17 @@ public class MethodInvocationTests extends AbstractExpressionTests {
// Now cause it to throw an exception:
eContext.setVariable("bar", 1);
try {
o = expr.getValue(eContext);
fail();
}
catch (Exception ex) {
if (ex instanceof SpelEvaluationException) {
fail("Should not be a SpelEvaluationException: " + ex);
}
// normal
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
expr.getValue(eContext))
.isNotInstanceOf(SpelEvaluationException.class);
// If counter is 4 then the method got called twice!
assertEquals(3, parser.parseExpression("counter").getValue(eContext));
eContext.setVariable("bar", 4);
try {
o = expr.getValue(eContext);
fail();
}
catch (Exception ex) {
// 4 means it will throw a checked exception - this will be wrapped
if (!(ex instanceof ExpressionInvocationTargetException)) {
fail("Should have been wrapped: " + ex);
}
// normal
}
assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() ->
expr.getValue(eContext));
// If counter is 5 then the method got called twice!
assertEquals(4, parser.parseExpression("counter").getValue(eContext));
}
@@ -168,16 +155,9 @@ public class MethodInvocationTests extends AbstractExpressionTests {
Expression expr = parser.parseExpression("throwException(#bar)");
context.setVariable("bar", 2);
try {
expr.getValue(context);
fail();
}
catch (Exception ex) {
if (ex instanceof SpelEvaluationException) {
fail("Should not be a SpelEvaluationException: " + ex);
}
// normal
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
expr.getValue(context))
.satisfies(ex -> assertThat(ex).isNotInstanceOf(SpelEvaluationException.class));
}
@Test
@@ -192,15 +172,10 @@ public class MethodInvocationTests extends AbstractExpressionTests {
Expression expr = parser.parseExpression("throwException(#bar)");
context.setVariable("bar", 4);
try {
expr.getValue(context);
fail();
}
catch (ExpressionInvocationTargetException ex) {
Throwable cause = ex.getCause();
assertEquals("org.springframework.expression.spel.testresources.Inventor$TestException",
cause.getClass().getName());
}
assertThatExceptionOfType(ExpressionInvocationTargetException.class).isThrownBy(() ->
expr.getValue(context))
.satisfies(ex -> assertThat(ex.getCause().getClass().getName()).isEqualTo(
"org.springframework.expression.spel.testresources.Inventor$TestException"));
}
@Test

View File

@@ -18,12 +18,10 @@ package org.springframework.expression.spel;
import org.junit.Test;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Parse some expressions and check we get the AST we expect. Rather than inspecting each node in the AST, we ask it to
@@ -454,20 +452,9 @@ public class ParsingTests {
* @param expectedStringFormOfAST the expected string form of the AST
*/
public void parseCheck(String expression, String expectedStringFormOfAST) {
try {
SpelExpression e = parser.parseRaw(expression);
if (e != null && !e.toStringAST().equals(expectedStringFormOfAST)) {
SpelUtilities.printAbstractSyntaxTree(System.err, e);
}
if (e == null) {
fail("Parsed exception was null");
}
assertEquals("String form of AST does not match expected output", expectedStringFormOfAST, e.toStringAST());
}
catch (ParseException ee) {
ee.printStackTrace();
fail("Unexpected Exception: " + ee.getMessage());
}
SpelExpression e = parser.parseRaw(expression);
assertThat(e).isNotNull();
assertThat(e.toStringAST()).isEqualTo(expectedStringFormOfAST);
}
}

View File

@@ -25,6 +25,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
///CLOVER:OFF
@@ -54,18 +55,14 @@ public class PerformanceTests {
// warmup
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("placeOfBirth.city");
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).isNotNull();
expr.getValue(eContext);
}
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("placeOfBirth.city");
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).isNotNull();
expr.getValue(eContext);
}
endtime = System.currentTimeMillis();
@@ -75,9 +72,7 @@ public class PerformanceTests {
}
Expression expr = parser.parseExpression("placeOfBirth.city");
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).isNotNull();
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
expr.getValue(eContext);
@@ -104,18 +99,14 @@ public class PerformanceTests {
// warmup
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()");
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).isNotNull();
expr.getValue(eContext);
}
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()");
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).isNotNull();
expr.getValue(eContext);
}
endtime = System.currentTimeMillis();
@@ -125,9 +116,7 @@ public class PerformanceTests {
}
Expression expr = parser.parseExpression("getPlaceOfBirth().getCity()");
if (expr == null) {
fail("Parser returned null for expression");
}
assertThat(expr).isNotNull();
starttime = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
expr.getValue(eContext);

View File

@@ -36,12 +36,13 @@ import org.springframework.expression.spel.support.SimpleEvaluationContext;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.Person;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests accessing of properties.
@@ -83,31 +84,13 @@ public class PropertyAccessTests extends AbstractExpressionTests {
public void testAccessingOnNullObject() {
SpelExpression expr = (SpelExpression)parser.parseExpression("madeup");
EvaluationContext context = new StandardEvaluationContext(null);
try {
expr.getValue(context);
fail("Should have failed - default property resolver cannot resolve on null");
}
catch (Exception ex) {
checkException(ex, SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expr.getValue(context))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL));
assertFalse(expr.isWritable(context));
try {
expr.setValue(context, "abc");
fail("Should have failed - default property resolver cannot resolve on null");
}
catch (Exception ex) {
checkException(ex, SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL);
}
}
private void checkException(Exception ex, SpelMessage expectedMessage) {
if (ex instanceof SpelEvaluationException) {
SpelMessage sm = ((SpelEvaluationException) ex).getMessageCode();
assertEquals("Expected exception type did not occur", expectedMessage, sm);
}
else {
fail("Should be a SpelException " + ex);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expr.setValue(context, "abc"))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL));
}
@Test
@@ -129,21 +112,17 @@ public class PropertyAccessTests extends AbstractExpressionTests {
Object o = expr.getValue(ctx);
assertNotNull(o);
expr = parser.parseRaw("new String('hello').flibbles");
expr.setValue(ctx, 99);
i = expr.getValue(ctx, Integer.class);
SpelExpression flibbleexpr = parser.parseRaw("new String('hello').flibbles");
flibbleexpr.setValue(ctx, 99);
i = flibbleexpr.getValue(ctx, Integer.class);
assertEquals(99, (int) i);
// Cannot set it to a string value
try {
expr.setValue(ctx, "not allowed");
fail("Should not have been allowed");
}
catch (EvaluationException ex) {
// success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
// 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
// System.out.println(e.getMessage());
}
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
flibbleexpr.setValue(ctx, "not allowed"));
// message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
// 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
// System.out.println(e.getMessage());
}
@Test
@@ -194,11 +173,11 @@ public class PropertyAccessTests extends AbstractExpressionTests {
assertEquals(String.class.getName(), parser.parseExpression("'a'.class.name").getValue());
}
@Test(expected = SpelEvaluationException.class)
@Test
public void noGetClassAccess() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
parser.parseExpression("'a'.class.name").getValue(context);
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("'a'.class.name").getValue(context));
}
@Test
@@ -211,13 +190,8 @@ public class PropertyAccessTests extends AbstractExpressionTests {
target.setName("p2");
assertEquals("p2", expr.getValue(context, target));
try {
parser.parseExpression("name='p3'").getValue(context, target);
fail("Should have thrown SpelEvaluationException");
}
catch (SpelEvaluationException ex) {
// expected
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("name='p3'").getValue(context, target));
}
@Test
@@ -263,13 +237,8 @@ public class PropertyAccessTests extends AbstractExpressionTests {
public void propertyAccessWithoutMethodResolver() {
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Person target = new Person("p1");
try {
parser.parseExpression("name.substring(1)").getValue(context, target);
fail("Should have thrown SpelEvaluationException");
}
catch (SpelEvaluationException ex) {
// expected
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseExpression("name.substring(1)").getValue(context, target));
}
@Test

View File

@@ -25,7 +25,6 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.MethodExecutor;
import org.springframework.expression.MethodResolver;
@@ -38,7 +37,6 @@ import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
///CLOVER:OFF
/**
@@ -50,24 +48,17 @@ public class ScenariosForSpringSecurity extends AbstractExpressionTests {
@Test
public void testScenario01_Roles() throws Exception {
try {
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
Expression expr = parser.parseRaw("hasAnyRole('MANAGER','TELLER')");
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
Expression expr = parser.parseRaw("hasAnyRole('MANAGER','TELLER')");
ctx.setRootObject(new Person("Ben"));
Boolean value = expr.getValue(ctx,Boolean.class);
assertFalse(value);
ctx.setRootObject(new Person("Ben"));
Boolean value = expr.getValue(ctx,Boolean.class);
assertFalse(value);
ctx.setRootObject(new Manager("Luke"));
value = expr.getValue(ctx,Boolean.class);
assertTrue(value);
}
catch (EvaluationException ee) {
ee.printStackTrace();
fail("Unexpected SpelException: " + ee.getMessage());
}
ctx.setRootObject(new Manager("Luke"));
value = expr.getValue(ctx,Boolean.class);
assertTrue(value);
}
@Test

View File

@@ -27,11 +27,12 @@ import org.springframework.expression.ParseException;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testresources.PlaceOfBirth;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests set value expressions.
@@ -84,53 +85,37 @@ public class SetValueTests extends AbstractExpressionTests {
@Test
public void testIsWritableForInvalidExpressions_SPR10610() {
Expression e = null;
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
// PROPERTYORFIELDREFERENCE
// Non existent field (or property):
e = parser.parseExpression("arrayContainer.wibble");
assertFalse("Should not be writable!",e.isWritable(lContext));
Expression e1 = parser.parseExpression("arrayContainer.wibble");
assertFalse("Should not be writable!", e1.isWritable(lContext));
e = parser.parseExpression("arrayContainer.wibble.foo");
try {
assertFalse("Should not be writable!",e.isWritable(lContext));
fail("Should have had an error because wibble does not really exist");
}
catch (SpelEvaluationException see) {
Expression e2 = parser.parseExpression("arrayContainer.wibble.foo");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e2.isWritable(lContext));
// org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 15): Property or field 'wibble' cannot be found on object of type 'org.springframework.expression.spel.testresources.ArrayContainer' - maybe not public?
// at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:225)
// success!
}
// VARIABLE
// the variable does not exist (but that is OK, we should be writable)
e = parser.parseExpression("#madeup1");
assertTrue("Should be writable!",e.isWritable(lContext));
Expression e3 = parser.parseExpression("#madeup1");
assertTrue("Should be writable!",e3.isWritable(lContext));
e = parser.parseExpression("#madeup2.bar"); // compound expression
assertFalse("Should not be writable!",e.isWritable(lContext));
Expression e4 = parser.parseExpression("#madeup2.bar"); // compound expression
assertFalse("Should not be writable!",e4.isWritable(lContext));
// INDEXER
// non existent indexer (wibble made up)
e = parser.parseExpression("arrayContainer.wibble[99]");
try {
assertFalse("Should not be writable!",e.isWritable(lContext));
fail("Should have had an error because wibble does not really exist");
}
catch (SpelEvaluationException see) {
// success!
}
Expression e5 = parser.parseExpression("arrayContainer.wibble[99]");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e5.isWritable(lContext));
// non existent indexer (index via a string)
e = parser.parseExpression("arrayContainer.ints['abc']");
try {
assertFalse("Should not be writable!",e.isWritable(lContext));
fail("Should have had an error because wibble does not really exist");
}
catch (SpelEvaluationException see) {
// success!
}
Expression e6 = parser.parseExpression("arrayContainer.ints['abc']");
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
e6.isWritable(lContext));
}
@Test
@@ -245,33 +230,20 @@ public class SetValueTests extends AbstractExpressionTests {
* Call setValue() but expect it to fail.
*/
protected void setValueExpectError(String expression, Object value) {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
}
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
e.setValue(lContext, value);
fail("expected an error");
}
catch (ParseException pe) {
pe.printStackTrace();
fail("Unexpected Exception: " + pe.getMessage());
}
catch (EvaluationException ee) {
// success!
Expression e = parser.parseExpression(expression);
assertThat(e).isNotNull();
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
e.setValue(lContext, value));
}
protected void setValue(String expression, Object value) {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
}
assertThat(e).isNotNull();
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
@@ -281,8 +253,7 @@ public class SetValueTests extends AbstractExpressionTests {
assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass()));
}
catch (EvaluationException | ParseException ex) {
ex.printStackTrace();
fail("Unexpected Exception: " + ex.getMessage());
throw new AssertionError("Unexpected Exception: " + ex.getMessage(), ex);
}
}
@@ -293,9 +264,7 @@ public class SetValueTests extends AbstractExpressionTests {
protected void setValue(String expression, Object value, Object expectedValue) {
try {
Expression e = parser.parseExpression(expression);
if (e == null) {
fail("Parser returned null for expression");
}
assertThat(e).isNotNull();
if (DEBUG) {
SpelUtilities.printAbstractSyntaxTree(System.out, e);
}
@@ -304,14 +273,10 @@ public class SetValueTests extends AbstractExpressionTests {
e.setValue(lContext, value);
Object a = expectedValue;
Object b = e.getValue(lContext);
if (!a.equals(b)) {
fail("Not the same: ["+a+"] type="+a.getClass()+" ["+b+"] type="+b.getClass());
// assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
}
assertThat(a).isEqualTo(b);
}
catch (EvaluationException | ParseException ex) {
ex.printStackTrace();
fail("Unexpected Exception: " + ex.getMessage());
throw new AssertionError("Unexpected Exception: " + ex.getMessage(), ex);
}
}

View File

@@ -45,12 +45,12 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.testdata.PersonInOtherPackage;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Checks SpelCompiler behavior. This should cover compilation all compiled node types.
@@ -1251,13 +1251,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
ctx.setVariable("target", "123");
assertEquals("123", expression.getValue(ctx));
ctx.setVariable("target", 42);
try {
assertEquals(42, expression.getValue(ctx));
fail();
}
catch (SpelEvaluationException see) {
assertTrue(see.getCause() instanceof ClassCastException);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expression.getValue(ctx))
.withCauseInstanceOf(ClassCastException.class);
ctx.setVariable("target", "abc");
expression = parser.parseExpression("#target.charAt(0)");
@@ -1267,13 +1263,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
ctx.setVariable("target", "1");
assertEquals('1', expression.getValue(ctx));
ctx.setVariable("target", 42);
try {
assertEquals('4', expression.getValue(ctx));
fail();
}
catch (SpelEvaluationException see) {
assertTrue(see.getCause() instanceof ClassCastException);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expression.getValue(ctx))
.withCauseInstanceOf(ClassCastException.class);
}
@Test
@@ -4004,14 +3996,9 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
assertEquals(2, expression.getValue(is));
assertCanCompile(expression);
assertEquals(2, expression.getValue(is));
try {
assertEquals(2, expression.getValue(strings));
fail();
}
catch (SpelEvaluationException see) {
assertTrue(see.getCause() instanceof ClassCastException);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expression.getValue(strings))
.withCauseInstanceOf(ClassCastException.class);
SpelCompiler.revertToInterpreted(expression);
assertEquals("b", expression.getValue(strings));
assertCanCompile(expression);
@@ -4037,26 +4024,18 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
assertCanCompile(expression);
tc.reset();
tc.obj=new Integer(42);
try {
expression.getValue(tc);
fail();
}
catch (SpelEvaluationException see) {
assertTrue(see.getCause() instanceof ClassCastException);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expression.getValue(tc))
.withCauseInstanceOf(ClassCastException.class);
// method with changing target
expression = parser.parseExpression("#root.charAt(0)");
assertEquals('a', expression.getValue("abc"));
assertCanCompile(expression);
try {
expression.getValue(new Integer(42));
fail();
}
catch (SpelEvaluationException see) {
// java.lang.Integer cannot be cast to java.lang.String
assertTrue(see.getCause() instanceof ClassCastException);
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
expression.getValue(new Integer(42)))
.withCauseInstanceOf(ClassCastException.class);
}
@Test
@@ -5179,13 +5158,8 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
}
private void assertGetValueFail(Expression expression) {
try {
Object o = expression.getValue();
fail("Calling getValue on the expression should have failed but returned "+o);
}
catch (Exception ex) {
// success!
}
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
expression.getValue());
}
private void assertIsCompiled(Expression expression) {
@@ -5196,7 +5170,7 @@ public class SpelCompilationCoverageTests extends AbstractExpressionTests {
assertNotNull(object);
}
catch (Exception ex) {
fail(ex.toString());
throw new AssertionError(ex.getMessage(), ex);
}
}

View File

@@ -373,7 +373,7 @@ public class SpelCompilationPerformanceTests extends AbstractExpressionTests {
assertEquals(interpretedResult,compiledResult);
reportPerformance("method reference", interpretedTotal, compiledTotal);
if (compiledTotal>=interpretedTotal) {
if (compiledTotal >= interpretedTotal) {
fail("Compiled version is slower than interpreted!");
}
}

View File

@@ -26,6 +26,7 @@ import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertTrue;
/**
@@ -36,18 +37,20 @@ import static org.junit.Assert.assertTrue;
*/
public class SpelExceptionTests {
@Test(expected = SpelEvaluationException.class)
@Test
public void spelExpressionMapNullVariables() {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#aMap.containsKey('one')");
spelExpression.getValue();
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(
spelExpression::getValue);
}
@Test(expected = SpelEvaluationException.class)
@Test
public void spelExpressionMapIndexAccessNullVariables() {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1");
spelExpression.getValue();
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(
spelExpression::getValue);
}
@Test
@@ -73,18 +76,20 @@ public class SpelExceptionTests {
}
@Test(expected = SpelEvaluationException.class)
@Test
public void spelExpressionListNullVariables() {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#aList.contains('one')");
spelExpression.getValue();
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(
spelExpression::getValue);
}
@Test(expected = SpelEvaluationException.class)
@Test
public void spelExpressionListIndexAccessNullVariables() {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'");
spelExpression.getValue();
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(
spelExpression::getValue);
}
@Test
@@ -131,11 +136,12 @@ public class SpelExceptionTests {
assertTrue(result);
}
@Test(expected = SpelEvaluationException.class)
@Test
public void spelExpressionArrayIndexAccessNullVariables() {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#anArray[0] eq 1");
spelExpression.getValue();
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(
spelExpression::getValue);
}
@Test

View File

@@ -60,7 +60,9 @@ import org.springframework.expression.spel.support.StandardTypeLocator;
import org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver;
import org.springframework.util.ObjectUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@@ -68,7 +70,6 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Reproduction tests cornering various reported SpEL issues.
@@ -109,14 +110,9 @@ public class SpelReproTests extends AbstractExpressionTests {
assertEquals(12, expr.getValue(context));
expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull(null)");
assertEquals(null, expr.getValue(context));
try {
expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)");
expr.getValue();
fail("Should have failed to find a method to which it could pass null");
}
catch (EvaluationException see) {
// success
}
expr = new SpelExpressionParser().parseRaw("tryToInvokeWithNull2(null)");
assertThatExceptionOfType(EvaluationException.class).isThrownBy(
expr::getValue);
context.setTypeLocator(new MyTypeLocator());
// varargs
@@ -243,22 +239,10 @@ public class SpelReproTests extends AbstractExpressionTests {
EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
assertFalse(accessor.canRead(context, null, "abc"));
assertFalse(accessor.canWrite(context, null, "abc"));
try {
accessor.read(context, null, "abc");
fail("Should have failed with an IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
try {
accessor.write(context, null, "abc", "foo");
fail("Should have failed with an IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
assertThatIllegalStateException().isThrownBy(() ->
accessor.read(context, null, "abc"));
assertThatIllegalStateException().isThrownBy(() ->
accessor.write(context, null, "abc", "foo"));
}
@Test
@@ -416,20 +400,15 @@ public class SpelReproTests extends AbstractExpressionTests {
private void checkTemplateParsingError(String expression, ParserContext context, String expectedMessage) {
SpelExpressionParser parser = new SpelExpressionParser();
try {
parser.parseExpression(expression, context);
fail("Should have failed with message: " + expectedMessage);
}
catch (Exception ex) {
assertThatExceptionOfType(Exception.class).isThrownBy(() ->
parser.parseExpression(expression, context))
.satisfies(ex -> {
String message = ex.getMessage();
if (ex instanceof ExpressionException) {
message = ((ExpressionException) ex).getSimpleMessage();
}
if (!message.equals(expectedMessage)) {
ex.printStackTrace();
}
assertThat(expectedMessage, equalTo(message));
}
assertThat(message).isEqualTo(expectedMessage);
});
}
@@ -513,26 +492,16 @@ public class SpelReproTests extends AbstractExpressionTests {
assertEquals(null, expr.getValue());
// Different parts of ternary expression are null
try {
expr = new SpelExpressionParser().parseRaw("(?'abc':'default')");
expr.getValue(context);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.TYPE_CONVERSION_ERROR, see.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
new SpelExpressionParser().parseRaw("(?'abc':'default')").getValue(context))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_CONVERSION_ERROR));
expr = new SpelExpressionParser().parseRaw("(false?'abc':null)");
assertEquals(null, expr.getValue());
// Assignment
try {
expr = new SpelExpressionParser().parseRaw("(='default')");
expr.getValue(context);
fail();
}
catch (SpelEvaluationException see) {
assertEquals(SpelMessage.SETVALUE_NOT_SUPPORTED, see.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
new SpelExpressionParser().parseRaw("(='default')").getValue(context))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.SETVALUE_NOT_SUPPORTED));
}
@Test
@@ -1265,14 +1234,8 @@ public class SpelReproTests extends AbstractExpressionTests {
public void SPR16123() {
ExpressionParser parser = new SpelExpressionParser();
parser.parseExpression("simpleProperty").setValue(new BooleanHolder(), null);
try {
parser.parseExpression("primitiveProperty").setValue(new BooleanHolder(), null);
fail("Should have thrown EvaluationException");
}
catch (EvaluationException ex) {
// expected
}
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
parser.parseExpression("primitiveProperty").setValue(new BooleanHolder(), null));
}
@Test
@@ -1578,23 +1541,19 @@ public class SpelReproTests extends AbstractExpressionTests {
expr = new SpelExpressionParser().parseRaw("&foo");
assertEquals("foo factory",expr.getValue(context));
try {
expr = new SpelExpressionParser().parseRaw("&@foo");
fail("Illegal syntax, error expected");
}
catch (SpelParseException spe) {
assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode());
assertEquals(0,spe.getPosition());
}
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
new SpelExpressionParser().parseRaw("&@foo"))
.satisfies(ex -> {
assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.INVALID_BEAN_REFERENCE);
assertThat(ex.getPosition()).isEqualTo(0);
});
try {
expr = new SpelExpressionParser().parseRaw("@&foo");
fail("Illegal syntax, error expected");
}
catch (SpelParseException spe) {
assertEquals(SpelMessage.INVALID_BEAN_REFERENCE,spe.getMessageCode());
assertEquals(0,spe.getPosition());
}
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
new SpelExpressionParser().parseRaw("@&foo"))
.satisfies(ex -> {
assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.INVALID_BEAN_REFERENCE);
assertThat(ex.getPosition()).isEqualTo(0);
});
}
@Test

View File

@@ -22,10 +22,11 @@ import org.junit.Test;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.spel.support.StandardTypeLocator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Unit tests for type comparison
@@ -49,14 +50,9 @@ public class StandardTypeLocatorTests {
// currently does not know about java.util by default
// assertEquals(java.util.List.class,locator.findType("List"));
try {
locator.findType("URL");
fail("Should have failed");
}
catch (EvaluationException ee) {
SpelEvaluationException sEx = (SpelEvaluationException)ee;
assertEquals(SpelMessage.TYPE_NOT_FOUND,sEx.getMessageCode());
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
locator.findType("URL"))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.TYPE_NOT_FOUND));
locator.registerImport("java.net");
assertEquals(java.net.URL.class,locator.findType("URL"));
}

View File

@@ -28,10 +28,11 @@ import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Andy Clement
@@ -119,19 +120,19 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests {
public void testCompositeStringExpression() throws Exception {
SpelExpressionParser parser = new SpelExpressionParser();
Expression ex = parser.parseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);
checkString("hello world", ex.getValue());
checkString("hello world", ex.getValue(String.class));
checkString("hello world", ex.getValue((Object)null, String.class));
checkString("hello world", ex.getValue(new Rooty()));
checkString("hello world", ex.getValue(new Rooty(), String.class));
assertThat(ex.getValue()).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(String.class)).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue((Object)null, String.class)).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(new Rooty())).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world");
EvaluationContext ctx = new StandardEvaluationContext();
checkString("hello world", ex.getValue(ctx));
checkString("hello world", ex.getValue(ctx, String.class));
checkString("hello world", ex.getValue(ctx, null, String.class));
checkString("hello world", ex.getValue(ctx, new Rooty()));
checkString("hello world", ex.getValue(ctx, new Rooty(), String.class));
checkString("hello world", ex.getValue(ctx, new Rooty(), String.class));
assertThat(ex.getValue(ctx)).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(ctx, String.class)).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(ctx, null, String.class)).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(ctx, new Rooty())).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(ctx, new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world");
assertThat(ex.getValue(ctx, new Rooty(), String.class)).isInstanceOf(String.class).isEqualTo("hello world");
assertEquals("hello ${'world'}", ex.getExpressionString());
assertFalse(ex.isWritable(new StandardEvaluationContext()));
assertFalse(ex.isWritable(new Rooty()));
@@ -145,28 +146,12 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests {
assertEquals(String.class,ex.getValueType(ctx, new Rooty()));
assertEquals(String.class,ex.getValueTypeDescriptor(new Rooty()).getType());
assertEquals(String.class,ex.getValueTypeDescriptor(ctx, new Rooty()).getType());
try {
ex.setValue(ctx, null);
fail();
}
catch (EvaluationException ee) {
// success
}
try {
ex.setValue((Object)null, null);
fail();
}
catch (EvaluationException ee) {
// success
}
try {
ex.setValue(ctx, null, null);
fail();
}
catch (EvaluationException ee) {
// success
}
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
ex.setValue(ctx, null));
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
ex.setValue((Object)null, null));
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
ex.setValue(ctx, null, null));
}
static class Rooty {}
@@ -193,21 +178,13 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests {
s = ex.getValue(TestScenarioCreator.getTestEvaluationContext(),String.class);
assertEquals("hello 4 10 world",s);
try {
ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5] world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
}
catch (ParseException pe) {
assertEquals("No ending suffix '}' for expression starting at character 41: ${listOfNumbersUpToTen.$[#this>5] world", pe.getSimpleMessage());
}
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
parser.parseExpression("hello ${listOfNumbersUpToTen.$[#this<5]} ${listOfNumbersUpToTen.$[#this>5] world",DEFAULT_TEMPLATE_PARSER_CONTEXT))
.satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("No ending suffix '}' for expression starting at character 41: ${listOfNumbersUpToTen.$[#this>5] world"));
try {
ex = parser.parseExpression("hello ${listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1==3]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
}
catch (ParseException pe) {
assertEquals("Found closing '}' at position 74 but most recent opening is '[' at position 30", pe.getSimpleMessage());
}
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
parser.parseExpression("hello ${listOfNumbersUpToTen.$[#root.listOfNumbersUpToTen.$[#this%2==1==3]} world",DEFAULT_TEMPLATE_PARSER_CONTEXT))
.satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("Found closing '}' at position 74 but most recent opening is '[' at position 30"));
}
@Test
@@ -235,28 +212,18 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests {
@Test
public void testErrorCases() throws Exception {
try {
parser.parseExpression("hello ${'world'", DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
}
catch (ParseException pe) {
assertEquals("No ending suffix '}' for expression starting at character 6: ${'world'", pe.getSimpleMessage());
assertEquals("hello ${'world'", pe.getExpressionString());
}
try {
parser.parseExpression("hello ${'wibble'${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
}
catch (ParseException pe) {
assertEquals("No ending suffix '}' for expression starting at character 6: ${'wibble'${'world'}", pe.getSimpleMessage());
}
try {
parser.parseExpression("hello ${} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
fail("Should have failed");
}
catch (ParseException pe) {
assertEquals("No expression defined within delimiter '${}' at character 6", pe.getSimpleMessage());
}
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
parser.parseExpression("hello ${'world'", DEFAULT_TEMPLATE_PARSER_CONTEXT))
.satisfies(pex -> {
assertThat(pex.getSimpleMessage()).isEqualTo("No ending suffix '}' for expression starting at character 6: ${'world'");
assertThat(pex.getExpressionString()).isEqualTo("hello ${'world'");
});
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
parser.parseExpression("hello ${'wibble'${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT))
.satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("No ending suffix '}' for expression starting at character 6: ${'wibble'${'world'}"));
assertThatExceptionOfType(ParseException.class).isThrownBy(() ->
parser.parseExpression("hello ${} world", DEFAULT_TEMPLATE_PARSER_CONTEXT))
.satisfies(pex -> assertThat(pex.getSimpleMessage()).isEqualTo("No expression defined within delimiter '${}' at character 6"));
}
@Test
@@ -277,15 +244,4 @@ public class TemplateExpressionParsingTests extends AbstractExpressionTests {
assertTrue(pc.isTemplate());
}
// ---
private void checkString(String expectedString, Object value) {
if (!(value instanceof String)) {
fail("Result was not a string, it was of type " + value.getClass() + " (value=" + value + ")");
}
if (!value.equals(expectedString)) {
fail("Did not get expected result. Should have been '" + expectedString + "' but was '" + value + "'");
}
}
}

View File

@@ -21,7 +21,8 @@ import org.junit.Test;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests the evaluation of expressions that access variables and functions (lambda/java).
@@ -74,18 +75,9 @@ public class VariableAndFunctionTests extends AbstractExpressionTests {
SpelExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("notStatic", this.getClass().getMethod("nonStatic"));
try {
@SuppressWarnings("unused")
Object v = parser.parseRaw("#notStatic()").getValue(ctx);
fail("Should have failed with exception - cannot call non static method that way");
}
catch (SpelEvaluationException se) {
if (se.getMessageCode() != SpelMessage.FUNCTION_MUST_BE_STATIC) {
se.printStackTrace();
fail("Should have failed a message about the function needing to be static, not: "
+ se.getMessageCode());
}
}
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
parser.parseRaw("#notStatic()").getValue(ctx)).
satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.FUNCTION_MUST_BE_STATIC));
}

View File

@@ -30,6 +30,8 @@ import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.expression.spel.support.StandardTypeConverter;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.Assert.assertEquals;
/**
@@ -42,19 +44,21 @@ import static org.junit.Assert.assertEquals;
*/
public class OpPlusTests {
@Test(expected = IllegalArgumentException.class)
@Test
public void test_emptyOperands() {
new OpPlus(-1, -1);
assertThatIllegalArgumentException().isThrownBy(() ->
new OpPlus(-1, -1));
}
@Test(expected = SpelEvaluationException.class)
@Test
public void test_unaryPlusWithStringLiteral() {
ExpressionState expressionState = new ExpressionState(new StandardEvaluationContext());
StringLiteral str = new StringLiteral("word", -1, -1, "word");
OpPlus o = new OpPlus(-1, -1, str);
o.getValueInternal(expressionState);
assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy(() ->
o.getValueInternal(expressionState));
}
@Test

View File

@@ -16,11 +16,12 @@
package org.springframework.expression.spel.standard;
import java.util.function.Consumer;
import org.junit.Test;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionException;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.SpelMessage;
import org.springframework.expression.spel.SpelNode;
import org.springframework.expression.spel.SpelParseException;
@@ -28,12 +29,13 @@ import org.springframework.expression.spel.ast.OpAnd;
import org.springframework.expression.spel.ast.OpOr;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* @author Andy Clement
@@ -116,86 +118,53 @@ public class SpelParserTests {
@Test
public void generalExpressions() {
try {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String");
fail();
}
catch (ParseException ex) {
assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.MISSING_CONSTRUCTOR_ARGS, spe.getMessageCode());
assertEquals(10, spe.getPosition());
assertTrue(ex.getMessage().contains(ex.getExpressionString()));
}
})
.satisfies(ex -> parseExceptionRequirements(SpelMessage.MISSING_CONSTRUCTOR_ARGS, 10));
try {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String(3,");
fail();
}
catch (ParseException ex) {
assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode());
assertEquals(10, spe.getPosition());
assertTrue(ex.getMessage().contains(ex.getExpressionString()));
}
})
.satisfies(ex -> parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10));
try {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String(3");
fail();
}
catch (ParseException ex) {
assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode());
assertEquals(10, spe.getPosition());
assertTrue(ex.getMessage().contains(ex.getExpressionString()));
}
})
.satisfies(ex -> parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10));
try {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("new String(");
fail();
}
catch (ParseException ex) {
assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.RUN_OUT_OF_ARGUMENTS, spe.getMessageCode());
assertEquals(10, spe.getPosition());
assertTrue(ex.getMessage().contains(ex.getExpressionString()));
}
})
.satisfies(ex -> parseExceptionRequirements(SpelMessage.RUN_OUT_OF_ARGUMENTS, 10));
try {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("\"abc");
fail();
}
catch (ParseException ex) {
assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, spe.getMessageCode());
assertEquals(0, spe.getPosition());
assertTrue(ex.getMessage().contains(ex.getExpressionString()));
}
})
.satisfies(ex -> parseExceptionRequirements(SpelMessage.NON_TERMINATING_DOUBLE_QUOTED_STRING, 0));
try {
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() -> {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw("'abc");
fail();
}
catch (ParseException ex) {
assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(SpelMessage.NON_TERMINATING_QUOTED_STRING, spe.getMessageCode());
assertEquals(0, spe.getPosition());
assertTrue(ex.getMessage().contains(ex.getExpressionString()));
}
})
.satisfies(ex -> parseExceptionRequirements(SpelMessage.NON_TERMINATING_QUOTED_STRING, 0));
}
private <E extends SpelParseException> Consumer<E> parseExceptionRequirements(
SpelMessage expectedMessage, int expectedPosition) {
return ex -> {
assertThat(ex.getMessageCode()).isEqualTo(expectedMessage);
assertThat(ex.getPosition()).isEqualTo(expectedPosition);
assertThat(ex.getMessage()).contains(ex.getExpressionString());
};
}
@Test
public void arithmeticPrecedence2() {
SpelExpressionParser parser = new SpelExpressionParser();
@@ -287,14 +256,12 @@ public class SpelParserTests {
@Test
public void testStringLiterals_DoubleQuotes_spr9620_2() {
try {
new SpelExpressionParser().parseRaw("\"double quote: \\\"\\\".\"");
fail("Should have failed");
}
catch (SpelParseException spe) {
assertEquals(17, spe.getPosition());
assertEquals(SpelMessage.UNEXPECTED_ESCAPE_CHAR, spe.getMessageCode());
}
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
new SpelExpressionParser().parseRaw("\"double quote: \\\"\\\".\""))
.satisfies(ex -> {
assertThat(ex.getPosition()).isEqualTo(17);
assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.UNEXPECTED_ESCAPE_CHAR);
});
}
@Test
@@ -417,21 +384,15 @@ public class SpelParserTests {
assertEquals(type, exprVal.getClass());
}
catch (Exception ex) {
fail(ex.getMessage());
throw new AssertionError(ex.getMessage(), ex);
}
}
private void checkNumberError(String expression, SpelMessage expectedMessage) {
try {
SpelExpressionParser parser = new SpelExpressionParser();
parser.parseRaw(expression);
fail();
}
catch (ParseException ex) {
assertTrue(ex instanceof SpelParseException);
SpelParseException spe = (SpelParseException) ex;
assertEquals(expectedMessage, spe.getMessageCode());
}
SpelExpressionParser parser = new SpelExpressionParser();
assertThatExceptionOfType(SpelParseException.class).isThrownBy(() ->
parser.parseRaw(expression))
.satisfies(ex -> assertThat(ex.getMessageCode()).isEqualTo(expectedMessage));
}
}

View File

@@ -34,13 +34,13 @@ import org.springframework.expression.spel.SpelUtilities;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.support.ReflectionHelper.ArgumentsMatchKind;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/**
* Tests for reflection helper code.
@@ -329,83 +329,41 @@ public class ReflectionHelperTests extends AbstractExpressionTests {
@Test
public void testOptimalReflectivePropertyAccessor() throws Exception {
ReflectivePropertyAccessor rpa = new ReflectivePropertyAccessor();
Tester t = new Tester();
t.setProperty("hello");
EvaluationContext ctx = new StandardEvaluationContext(t);
assertTrue(rpa.canRead(ctx, t, "property"));
assertEquals("hello", rpa.read(ctx, t, "property").getValue());
assertEquals("hello", rpa.read(ctx, t, "property").getValue()); // cached accessor used
ReflectivePropertyAccessor reflective = new ReflectivePropertyAccessor();
Tester tester = new Tester();
tester.setProperty("hello");
EvaluationContext ctx = new StandardEvaluationContext(tester);
assertTrue(reflective.canRead(ctx, tester, "property"));
assertEquals("hello", reflective.read(ctx, tester, "property").getValue());
assertEquals("hello", reflective.read(ctx, tester, "property").getValue()); // cached accessor used
PropertyAccessor optA = rpa.createOptimalAccessor(ctx, t, "property");
assertTrue(optA.canRead(ctx, t, "property"));
assertFalse(optA.canRead(ctx, t, "property2"));
try {
optA.canWrite(ctx, t, "property");
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
try {
optA.canWrite(ctx, t, "property2");
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
assertEquals("hello",optA.read(ctx, t, "property").getValue());
assertEquals("hello",optA.read(ctx, t, "property").getValue()); // cached accessor used
PropertyAccessor property = reflective.createOptimalAccessor(ctx, tester, "property");
assertTrue(property.canRead(ctx, tester, "property"));
assertFalse(property.canRead(ctx, tester, "property2"));
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
property.canWrite(ctx, tester, "property"));
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
property.canWrite(ctx, tester, "property2"));
assertEquals("hello",property.read(ctx, tester, "property").getValue());
assertEquals("hello",property.read(ctx, tester, "property").getValue()); // cached accessor used
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
property.getSpecificTargetClasses());
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
property.write(ctx, tester, "property", null));
try {
optA.getSpecificTargetClasses();
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
try {
optA.write(ctx, t, "property", null);
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
optA = rpa.createOptimalAccessor(ctx, t, "field");
assertTrue(optA.canRead(ctx, t, "field"));
assertFalse(optA.canRead(ctx, t, "field2"));
try {
optA.canWrite(ctx, t, "field");
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
try {
optA.canWrite(ctx, t, "field2");
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
assertEquals(3,optA.read(ctx, t, "field").getValue());
assertEquals(3,optA.read(ctx, t, "field").getValue()); // cached accessor used
try {
optA.getSpecificTargetClasses();
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
try {
optA.write(ctx, t, "field", null);
fail();
}
catch (UnsupportedOperationException uoe) {
// success
}
PropertyAccessor field = reflective.createOptimalAccessor(ctx, tester, "field");
assertTrue(field.canRead(ctx, tester, "field"));
assertFalse(field.canRead(ctx, tester, "field2"));
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
field.canWrite(ctx, tester, "field"));
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
field.canWrite(ctx, tester, "field2"));
assertEquals(3,field.read(ctx, tester, "field").getValue());
assertEquals(3,field.read(ctx, tester, "field").getValue()); // cached accessor used
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
field.getSpecificTargetClasses());
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() ->
field.write(ctx, tester, "field", null));
}

View File

@@ -28,6 +28,7 @@ import org.springframework.expression.TypeComparator;
import org.springframework.expression.TypeConverter;
import org.springframework.expression.TypeLocator;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -48,11 +49,12 @@ public class StandardComponentsTests {
assertEquals(tl, context.getTypeLocator());
}
@Test(expected = EvaluationException.class)
@Test
public void testStandardOperatorOverloader() throws EvaluationException {
OperatorOverloader oo = new StandardOperatorOverloader();
assertFalse(oo.overridesOperation(Operation.ADD, null, null));
oo.operate(Operation.ADD, 2, 3);
assertThatExceptionOfType(EvaluationException.class).isThrownBy(() ->
oo.operate(Operation.ADD, 2, 3));
}
@Test