class CalculatorConundrum {
public String calculate(int operand1, int operand2, String operation) {
try {
if (operation == null) {
throw new IllegalArgumentException("Operation cannot be null");
}
if (operation.isEmpty()) {
throw new IllegalArgumentException("Operation cannot be empty");
}
String result;
switch (operation) {
case "+":
result = operand1 + " + " + operand2 + " = " + (operand1 + operand2);
break;
case "*":
result = operand1 + " * " + operand2 + " = " + (operand1 * operand2);
break;
case "/":
if (operand2 == 0) {
throw new IllegalOperationException("Division by zero is not allowed");
}
result = operand1 + " / " + operand2 + " = " + (operand1 / operand2);
break;
default:
throw new IllegalOperationException("Operation '" + operation + "' does not exist");
}
return result;
} catch (IllegalOperationException e) {
return "Error: " + e.getMessage();
} catch (IllegalArgumentException a) {
return "Error: " + a.getMessage();
}
}
}
Handle illegal operation
@Test
@Tag("task:2")
@DisplayName("The calculate method throws IllegalOperationException when passing invalid operation")
public void throwExceptionForUnknownOperation() {
String invalidOperation = "**";
String expectedMessage = "Operation '" + invalidOperation + "' does not exist";
assertThatExceptionOfType(IllegalOperationException.class).isThrownBy(() -> new CalculatorConundrum().calculate(3, 78, invalidOperation)).withMessage(expectedMessage);
}
Test failure
Message:
Expecting code to raise a throwable.
Exception: java.lang.AssertionError:
Expecting code to raise a throwable.
at CalculatorConundrumTest.throwExceptionForUnknownOperation(CalculatorConundrumTest.java:58)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)