写一个待测试代码和一个测试类
时间: 2024-03-21 20:41:05 浏览: 19
好的,这里是一个待测试的 Java 代码和对应的测试类。
代码:
```java
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return a / b;
}
}
```
测试类:
```java
import org.junit.Test;
import static org.junit.Assert.*;
public class CalculatorTest {
@Test
public void testAddition() {
Calculator calculator = new Calculator();
int a = 2;
int b = 3;
int expectedResult = 5;
int result = calculator.add(a, b);
assertEquals(expectedResult, result);
}
@Test
public void testSubtraction() {
Calculator calculator = new Calculator();
int a = 5;
int b = 3;
int expectedResult = 2;
int result = calculator.subtract(a, b);
assertEquals(expectedResult, result);
}
@Test
public void testMultiplication() {
Calculator calculator = new Calculator();
int a = 5;
int b = 3;
int expectedResult = 15;
int result = calculator.multiply(a, b);
assertEquals(expectedResult, result);
}
@Test
public void testDivision() {
Calculator calculator = new Calculator();
int a = 10;
int b = 2;
int expectedResult = 5;
int result = calculator.divide(a, b);
assertEquals(expectedResult, result);
}
@Test(expected = IllegalArgumentException.class)
public void testDivisionByZero() {
Calculator calculator = new Calculator();
int a = 10;
int b = 0;
calculator.divide(a, b);
}
}
```
在这个例子中,我们测试了一个名为 Calculator 的类的四个方法:add、subtract、multiply 和 divide。在每个测试方法中,我们创建了一个 Calculator 对象,定义了一些输入值和预期结果,然后使用 assertEquals 来验证实际结果是否与预期结果相同。我们还编写了一个特殊测试方法 testDivisionByZero,验证当除数为零时,是否会抛出 IllegalArgumentException 异常。
阅读全文