1. /*
  2. * Copyright 2003,2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  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. package org.apache.commons.jexl.junit;
  17. import java.util.HashMap;
  18. import java.util.Map;
  19. import junit.framework.Assert;
  20. import org.apache.commons.jexl.Expression;
  21. import org.apache.commons.jexl.ExpressionFactory;
  22. import org.apache.commons.jexl.JexlContext;
  23. import org.apache.commons.jexl.JexlHelper;
  24. /**
  25. * A utility class for performing JUnit based assertions using Jexl
  26. * expressions. This class can make it easier to do unit tests using
  27. * Jexl navigation expressions.
  28. *
  29. * @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
  30. * @version $Revision: 1.4 $
  31. */
  32. public class Asserter extends Assert {
  33. private Map variables = new HashMap();
  34. private JexlContext context = JexlHelper.createContext();
  35. public Asserter() {}
  36. /**
  37. * This constructor will register the given variableValue as the
  38. * "this" variable.
  39. *
  40. * @param variableValue
  41. */
  42. public Asserter(Object variableValue) {
  43. setVariable("this", variableValue);
  44. }
  45. /**
  46. * Performs an assertion that the value of the given Jexl expression
  47. * evaluates to the given expected value
  48. *
  49. * @param expression is the Jexl expression to evaluate
  50. * @param expected is the expected value of the expression
  51. * @throws Exception if the expression could not be evaluationed or an assertion
  52. * fails
  53. */
  54. public void assertExpression(String expression, Object expected) throws Exception {
  55. Expression exp = ExpressionFactory.createExpression(expression);
  56. context.setVars(variables);
  57. Object value = exp.evaluate(context);
  58. assertEquals("expression: " + expression, expected, value);
  59. }
  60. /**
  61. * Puts a variable of a certain name in the context so that it can be used from
  62. * assertion expressions.
  63. *
  64. * @param name
  65. * @param value
  66. */
  67. public void setVariable(String name, Object value) {
  68. variables.put(name, value);
  69. }
  70. }