With Junit Jupiter:
https://www.petrikainulainen.net/programming/testing/junit-5-tutorial-writing-parameterized-tests/
import intf.ICalculator;
public class Calculator implements ICalculator {
@Override
public int plus(int a, int b) {return a + b; }
@Override
public int minuis(int a, int b) {return a - b;}
@Override
public int multy(int a, int b) {return a * b;}
@Override // check in junit byZero
public int divide(int a, int b) {return a / b;}
}
Test class:
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class CalculatorJupiter5Test {
Calculator calculator = new Calculator();
@DisplayName("Should calculate the correct sum")
@ParameterizedTest(name = "{index} => a={0}, b={1}, sum={2}")
@CsvSource({
"5, 3, 8",
"1, 3, 4",
"6, 6, 12",
"2, 3, 5"
})
void sum(int a, int b, int sum) {
assertEquals(sum, calculator.plus(a, b) );
}
@DisplayName("Should calculate the correct multy")
@ParameterizedTest(name = "{index} => a={0}, b={1}, multy={2}")
@CsvSource({
"5, 3, 15",
"1, 3, 3",
"6, 6, 36",
"2, 3, 6"
})
void multy(int a, int b, int multy) {
assertEquals(multy, calculator.multy(a, b) );
}
@DisplayName("Should calculate the correct divide")
@ParameterizedTest(name = "{index} => a={0}, b={1}, divide={2}")
@CsvSource({
"5, 3, 1",
"14, 3, 4",
"6, 6, 1",
"36, 2, 18"
})
void divide(int a, int b, int divide) {
assertEquals(divide, calculator.divide(a, b) );
}
@DisplayName("Should calculate the correct divide by zero")
@ParameterizedTest(name = "{index} => a={0}, b={1}, divide={2}")
@CsvSource({
"5, 0, 0",
})
void divideByZero(int a, int b, int divide) {
assertThrows(ArithmeticException.class,
() -> calculator.divide(a , b),
() -> "divide by zero");
}
@DisplayName("Should calculate the correct minuis")
@ParameterizedTest(name = "{index} => a={0}, b={1}, minuis={2}")
@CsvSource({
"5, 3, 2",
"1, 3, -2",
"6, 6, 0",
"2, 3, -1"
})
void minuis(int a, int b, int minuis) {
assertEquals(minuis, calculator.minuis(a, b) );
}
}
@DataProvider
. – Penholder