}
public void testSetExpression()
{
ExpressionParser parser = null;
Integer intResult = null;
Boolean boolResult = null;
boolean status = false;
//initial state
parser = new ExpressionParser();
Assert.assertEquals(false, parser.isValid());
Assert.assertEquals(false, parser.isInitialized());
//default to integer value
try
{
intResult = (Integer)parser.evaluate();
Assert.assertNull(intResult);
}
catch(Exception ex)
{
Assert.fail(ex.toString());
}
//set the expression (use simple addition with variable)
parser.setExpression("var1 + var2", Integer.class);
parser.createVariable("var1", Integer.class, new Integer(0));
parser.createVariable("var2", Integer.class, new Integer(0));
try
{
//set the variable (using variable name)
status = parser.set("var1", new Integer(1));
Assert.assertTrue(status);
status = parser.set("var2", new Integer(5));
Assert.assertTrue(status);
//set invalid variable name
status = parser.set("var3", new Integer(3));
Assert.assertFalse(status);
//evaluate
intResult = (Integer)parser.evaluate();
Assert.assertNotNull(intResult);
Assert.assertEquals(6, intResult.intValue());
//set the variable (using index)
status = parser.set(0, new Integer(2));
Assert.assertTrue(status);
status = parser.set(1, new Integer(7));
Assert.assertTrue(status);
//set invalid variable index
status = parser.set(2, new Integer(3));
Assert.assertFalse(status);
//evaluate
intResult = (Integer)parser.evaluate();
Assert.assertNotNull(intResult);
Assert.assertEquals(9, intResult.intValue());
}
catch(Exception ex)
{
Assert.fail(ex.toString());
}
//reset the expression. use simple boolean operation
parser.setExpression("bool1 || bool2", Boolean.class);
parser.createVariable("bool1", Boolean.class, Boolean.FALSE);
parser.createVariable("bool2", Boolean.class, Boolean.FALSE);
try
{
//set the variable (using variable name)
status = parser.set("bool1", Boolean.FALSE);
Assert.assertTrue(status);
status = parser.set("bool2", Boolean.TRUE);
Assert.assertTrue(status);
//set invalid variable name
status = parser.set("var1", Boolean.TRUE);
Assert.assertFalse(status);
status = parser.set("var2", Boolean.TRUE);
Assert.assertFalse(status);
//evaluate (false || true)
boolResult = (Boolean)parser.evaluate();
Assert.assertNotNull(boolResult);
Assert.assertEquals(true, boolResult.booleanValue());
//set the variable (using index)
status = parser.set(0, Boolean.TRUE);
Assert.assertTrue(status);
status = parser.set(1, Boolean.FALSE);
Assert.assertTrue(status);
//set invalid variable name
status = parser.set(3, Boolean.TRUE);
Assert.assertFalse(status);
//evaluate (false || true)
boolResult = (Boolean)parser.evaluate();
Assert.assertNotNull(boolResult);
Assert.assertEquals(true, boolResult.booleanValue());
}
catch(Exception ex)
{