Write a class in Java that has two methods The first method
Write a class in Java that has two methods. The first method, subtract, takes in two parameters as input and returns the value of the first parameter minus the second parameter. The second method, divide, returns the value of the first parameter divided by the second parameter except for cases where the second parameter is equal to zero. If the second parameter is equal to zero, an error message will be reported.
Write the following test cases using JUnit.
Test that subtract returns the expected result of the subtraction.
Test that divide returns the expected result of the division.
Test that divide produces the expected error for the division by zero.
Create an automated test suite for the above three test cases.
Solution
ArithmeticCalculationsTest.java
import junit.framework.Assert;
public class ArithmeticCalculationsTest {
public static void main(String a[]){
ArithmeticCalculations calc = new ArithmeticCalculations();
Assert.assertEquals(3, calc.subtract(6, 3));
Assert.assertEquals(-3, calc.subtract(3, 6));
Assert.assertEquals(2.5, calc.divide(5, 2));
Assert.assertEquals(0.4, calc.divide(2, 5));
try {
calc.divide(2, 0);
assert false;
} catch (ArithmeticException e) {
assert true;
}
}
}
ArithmeticCalculations.java
public class ArithmeticCalculations {
public ArithmeticCalculations(){
}
public int subtract(int a, int b){
return a-b;
}
public double divide(int a, int b){
if(b== 0){
throw new ArithmeticException();
}
else{
return a/(double)b;
}
}
}
