Commit 55051834 authored by Robert Zenz's avatar Robert Zenz

#70 Fixed that the expression "4^" would throw a NumberFormatException.

It now throws an IllegalExpressionException, as it should.
parent 0161ea2c
......@@ -272,8 +272,14 @@ public class UnitConverter {
int exponentIndex = unitNameOrAlias.indexOf("^");
if (exponentIndex >= 0) {
exponent = Integer.parseInt(unitNameOrAlias.substring(exponentIndex + 1));
unitNameOrAlias = unitNameOrAlias.substring(0, exponentIndex);
try {
exponent = Integer.parseInt(unitNameOrAlias.substring(exponentIndex + 1));
unitNameOrAlias = unitNameOrAlias.substring(0, exponentIndex);
} catch (NumberFormatException e) {
// The exponent is not well-formed, so we assume that this is
// not a unit.
return null;
}
} else if (unitNameOrAlias.toLowerCase().startsWith("square")) {
exponent = 2;
unitNameOrAlias = unitNameOrAlias.substring(6);
......
......@@ -36,6 +36,16 @@ public abstract class AbstractExpressionTest {
}
}
protected void assertException(Class<? extends Exception> expectedException, String expression, Evaluator evaluator) throws Exception {
try {
evaluator.evaluate(expression);
} catch (Exception e) {
if (!expectedException.isAssignableFrom(e.getClass())) {
throw e;
}
}
}
protected void assertExpression(
String expectedId,
boolean expectedResult,
......
......@@ -163,6 +163,13 @@ public class TestEvaluator extends AbstractExpressionTest {
assertResult("75", "add(25, 00)", evaluator);
}
@Test
public void testMalformedExpressions() throws Exception {
Evaluator evaluator = new Evaluator();
assertException(InvalidExpressionException.class, "4^", evaluator);
}
@Test
public void testNullAndEmpty() throws InvalidExpressionException {
assertResult("0", (String)null);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment