Last active
April 15, 2025 17:45
-
-
Save leonard84/437e9026ff86d2d709c2c56eb7e2eef1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CalculatorSpec.groovy | |
import spock.lang.Specification | |
class CalculatorSpec extends Specification { | |
def "Test calculate method: #a #operation #b = #expectedResult"() { | |
given: "A calculator instance" | |
def calculator = new Calculator() | |
expect: "The calculation should match the expected value" | |
calculator.calculate(a, b, operation) == expectedResult | |
where: "Define test data" | |
a | b | operation || expectedResult | |
1 | 2 | "+" || 3 | |
5 | 3 | "-" || 2 | |
4 | 2 | "*" || 8 | |
10 | 2 | "/" || 5 | |
-1 | 1 | "+" || 0 | |
1 | -1 | "-" || 2 | |
-2 | -2 | "*" || 4 | |
-4 | -2 | "/" || 2 | |
1 | 1 | "+" || 42 | |
} | |
def "Test calculate method with division by zero"() { | |
given: "A calculator instance" | |
def calculator = new Calculator() | |
when: "Perform division by zero" | |
calculator.calculate(10, 0, "/") | |
then: "An IllegalArgumentException is thrown" | |
def exception = thrown(IllegalArgumentException) | |
and: "The exception message is correct" | |
exception.message == "Cannot divide by zero" | |
} | |
def "Test calculate method with invalid operation"() { | |
given: "A calculator instance" | |
def calculator = new Calculator() | |
when: "Perform calculation with invalid operation" | |
calculator.calculate(1, 2, "**") | |
then: "An IllegalArgumentException is thrown" | |
def exception = thrown(IllegalArgumentException) | |
and: "The exception message is correct" | |
exception.message == "Invalid operation: **" | |
} | |
} | |
// Calculator.groovy | |
class Calculator { | |
/** | |
* Performs arithmetic operations on two integers. | |
* | |
* @param a The first integer. | |
* @param b The second integer. | |
* @param operation The operation to perform (+, -, *, /). | |
* @return The result of the operation. | |
* @throws IllegalArgumentException if the operation is invalid or division by zero is attempted. | |
*/ | |
int calculate(int a, int b, String operation) { | |
switch (operation) { | |
case "+": return a + b | |
case "-": return a - b | |
case "*": return a * b | |
case "/": | |
if (b == 0) { | |
throw new IllegalArgumentException("Cannot divide by zero") | |
} | |
return a / b | |
default: | |
throw new IllegalArgumentException("Invalid operation: " + operation) | |
} | |
} | |
String toString() { | |
"Calc" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment