package com.example.calculatortest
import org.junit.Test
import org.junit.Assert.*
class Calculator {
fun add(a: Int, b: Int): Int = a + b
fun subtract(a: Int, b: Int): Int = a - b
fun multiply(a: Int, b: Int): Int = a * b
fun divide(a: Int, b: Int): Int {
if (b == 0) throw IllegalArgumentException("Cannot divide by zero")
return a / b
}
}
class CalculatorTest {
private val calculator = Calculator()
@Test
fun testAdd() {
assertEquals(5, calculator.add(2, 3))
}
@Test
fun testSubtract() {
assertEquals(1, calculator.subtract(3, 2))
}
@Test
fun testMultiply() {
assertEquals(6, calculator.multiply(2, 3))
}
@Test
fun testDivide() {
assertEquals(2, calculator.divide(6, 3))
}
@Test(expected = IllegalArgumentException::class)
fun testDivideByZero() {
calculator.divide(5, 0)
}
}We created a simple Calculator class with four methods for basic math operations. Each method returns the expected result.
The divide method checks if the divisor is zero and throws an IllegalArgumentException to prevent division by zero.
The CalculatorTest class uses JUnit 4 annotations. Each test method calls a Calculator method and uses assertEquals to compare the expected and actual results.
The testDivideByZero method expects an exception, verifying that dividing by zero is handled properly.
This setup helps ensure the Calculator works correctly and safely.