Search code examples
javaregexexceptionjunit4

Understand failing JUnit4 test?


The following is supposed to throw an InvalidExpression exeption if the string "what" doesn't contain an operation (+, -, *, /).

//Check if the input contains at least one operation
else if(!what.matches(".*[+ \\- * \\/].*")) {
    throw new InvalidExpression("No operation in the expression");
}

However if I run the following JUnit4 Test I don't get correct exception. The evaluate method calculates the math expression, and in theory should contain an operation.

@Test (expected = InvalidExpression.class)
public void test() throws InvalidExpression {
    testCalc.evaluate("5 5");
}

Solution

  • You have spaces inside the brackets. So a space is a valid operator.

    Your regex should be

    ".*[+\\-*/].*"