KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > percederberg > grammatica > test > TestArithmeticCalculator


1 /*
2  * TestArithmeticCalculator.java
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public License
6  * as published by the Free Software Foundation; either version 2.1
7  * of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free
16  * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
17  * MA 02111-1307, USA.
18  *
19  * Copyright (c) 2003-2005 Per Cederberg. All rights reserved.
20  */

21
22 package net.percederberg.grammatica.test;
23
24 import java.util.HashMap JavaDoc;
25
26 import junit.framework.TestCase;
27
28 /**
29  * A test case for the ArithmeticCalculator class.
30  *
31  * @author Per Cederberg, <per at percederberg dot net>
32  * @version 1.0
33  */

34 public class TestArithmeticCalculator extends TestCase {
35
36     /**
37      * The valid input string.
38      */

39     private static final String JavaDoc VALID_INPUT =
40         "1 + 2*a\n" +
41         " + 345";
42
43     /**
44      * The variable bindings.
45      */

46     private HashMap JavaDoc variables = new HashMap JavaDoc();
47
48     /**
49      * Creates a new test case.
50      *
51      * @param name the test case name
52      */

53     public TestArithmeticCalculator(String JavaDoc name) {
54         super(name);
55         variables.put("a", new Integer JavaDoc(2));
56     }
57
58     /**
59      * Tests the calculator with a valid expression.
60      */

61     public void testValidExpression() {
62         calculate(VALID_INPUT, 350);
63     }
64
65     /**
66      * Calculates an expression and checks the result. If the
67      * calculation failed or if the result didn't match the specified
68      * one, a test failure will be reported.
69      *
70      * @param expr the expression to use
71      * @param result the result to expect
72      */

73     private void calculate(String JavaDoc expr, int result) {
74         ArithmeticCalculator calc;
75
76         try {
77             calc = new ArithmeticCalculator(variables);
78             assertEquals("expression result", result, calc.calculate(expr));
79         } catch (Exception JavaDoc e) {
80             fail(e.getMessage());
81         }
82     }
83 }
84
Popular Tags