1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package org.apache.commons.jexl.junit;
19
20 import java.util.HashMap;
21 import java.util.Map;
22
23 import junit.framework.Assert;
24
25 import org.apache.commons.jexl.Expression;
26 import org.apache.commons.jexl.ExpressionFactory;
27 import org.apache.commons.jexl.JexlContext;
28 import org.apache.commons.jexl.JexlHelper;
29
30 /**
31 * A utility class for performing JUnit based assertions using Jexl
32 * expressions. This class can make it easier to do unit tests using
33 * Jexl navigation expressions.
34 *
35 * @since 1.0
36 * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
37 * @version $Revision: 480412 $
38 */
39 public class Asserter extends Assert {
40
41 /** variables used during asserts. */
42 private final Map variables = new HashMap();
43 /** context to use during asserts. */
44 private final JexlContext context = JexlHelper.createContext();
45
46 /**
47 *
48 * Create an asserter.
49 */
50 public Asserter() {
51
52 }
53
54 /**
55 * This constructor will register the given variableValue as the
56 * "this" variable.
57 *
58 * @param variableValue 'this'.
59 */
60 public Asserter(Object variableValue) {
61 setVariable("this", variableValue);
62 }
63
64 /**
65 * Performs an assertion that the value of the given Jexl expression
66 * evaluates to the given expected value.
67 *
68 * @param expression is the Jexl expression to evaluate
69 * @param expected is the expected value of the expression
70 * @throws Exception if the expression could not be evaluationed or an assertion
71 * fails
72 */
73 public void assertExpression(String expression, Object expected) throws Exception {
74 Expression exp = ExpressionFactory.createExpression(expression);
75
76 context.setVars(variables);
77 Object value = exp.evaluate(context);
78
79 assertEquals("expression: " + expression, expected, value);
80 }
81
82 /**
83 * Puts a variable of a certain name in the context so that it can be used from
84 * assertion expressions.
85 *
86 * @param name variable name
87 * @param value variable value
88 */
89 public void setVariable(String name, Object value) {
90 variables.put(name, value);
91 }
92
93 }