01: /*
02: * Copyright 2003-2006 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
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: * @since 1.0
35: * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
36: * @version $Revision: 398153 $
37: */
38: public class Asserter extends Assert {
39:
40: /** variables used during asserts. */
41: private final Map variables = new HashMap();
42: /** context to use during asserts. */
43: private final JexlContext context = JexlHelper.createContext();
44:
45: /**
46: *
47: * Create an asserter.
48: */
49: public Asserter() {
50:
51: }
52:
53: /**
54: * This constructor will register the given variableValue as the
55: * "this" variable.
56: *
57: * @param variableValue 'this'.
58: */
59: public Asserter(Object variableValue) {
60: setVariable("this", variableValue);
61: }
62:
63: /**
64: * Performs an assertion that the value of the given Jexl expression
65: * evaluates to the given expected value.
66: *
67: * @param expression is the Jexl expression to evaluate
68: * @param expected is the expected value of the expression
69: * @throws Exception if the expression could not be evaluationed or an assertion
70: * fails
71: */
72: public void assertExpression(String expression, Object expected)
73: 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: }
|