用java代码创建一个计算类,实现加减乘除运算 并写出JUnit测试类
时间: 2024-02-16 09:03:52 浏览: 85
好的,以下是Java代码实现一个计算类,实现加减乘除运算:
```java
public class Calculator {
public static double add(double num1, double num2) {
return num1 + num2;
}
public static double subtract(double num1, double num2) {
return num1 - num2;
}
public static double multiply(double num1, double num2) {
return num1 * num2;
}
public static double divide(double num1, double num2) {
if (num2 == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return num1 / num2;
}
}
```
以下是JUnit测试类:
```java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CalculatorTest {
@Test
public void testAdd() {
double result = Calculator.add(2.5, 3.5);
assertEquals(6.0, result);
}
@Test
public void testSubtract() {
double result = Calculator.subtract(7.5, 4.5);
assertEquals(3.0, result);
}
@Test
public void testMultiply() {
double result = Calculator.multiply(2.5, 3.0);
assertEquals(7.5, result);
}
@Test
public void testDivide() {
double result = Calculator.divide(10.0, 2.5);
assertEquals(4.0, result);
}
@Test
public void testDivideByZero() {
assertThrows(IllegalArgumentException.class, () -> {
Calculator.divide(10.0, 0.0);
});
}
}
```
在这个JUnit测试类中,我们测试了加、减、乘、除四个方法的正确性,并且还测试了除数为零的情况。如果出现除数为零的情况,我们期望该方法会抛出 `IllegalArgumentException` 异常。
阅读全文