1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jexl.junit;
18
19 import java.util.HashMap;
20 import java.util.Map;
21
22 import junit.framework.Assert;
23
24 import org.apache.commons.jexl.Expression;
25 import org.apache.commons.jexl.ExpressionFactory;
26 import org.apache.commons.jexl.JexlContext;
27 import org.apache.commons.jexl.JexlHelper;
28
29 /***
30 * A utility class for performing JUnit based assertions using Jexl
31 * expressions. This class can make it easier to do unit tests using
32 * Jexl navigation expressions.
33 *
34 * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
35 * @version $Revision: 1.4 $
36 */
37 public class Asserter extends Assert {
38
39 private Map variables = new HashMap();
40 private JexlContext context = JexlHelper.createContext();
41
42 public Asserter() {}
43
44 /***
45 * This constructor will register the given variableValue as the
46 * "this" variable.
47 *
48 * @param variableValue
49 */
50 public Asserter(Object variableValue) {
51 setVariable("this", variableValue);
52 }
53
54 /***
55 * Performs an assertion that the value of the given Jexl expression
56 * evaluates to the given expected value
57 *
58 * @param expression is the Jexl expression to evaluate
59 * @param expected is the expected value of the expression
60 * @throws Exception if the expression could not be evaluationed or an assertion
61 * fails
62 */
63 public void assertExpression(String expression, Object expected) throws Exception {
64 Expression exp = ExpressionFactory.createExpression(expression);
65
66 context.setVars(variables);
67 Object value = exp.evaluate(context);
68
69 assertEquals("expression: " + expression, expected, value);
70 }
71
72 /***
73 * Puts a variable of a certain name in the context so that it can be used from
74 * assertion expressions.
75 *
76 * @param name
77 * @param value
78 */
79 public void setVariable(String name, Object value) {
80 variables.put(name, value);
81 }
82
83 }