如何在Java中分别创建一个加法类(Addition)、减法类(Subtraction)、乘法类(Multiplication)和除法类(Division),并为每个类设计对应的单元测试用例来验证其功能是否正确?
时间: 2024-10-20 15:08:50 浏览: 15
高考英语单词分类记忆.doc
在Java中,为了实现这种结构,我们可以创建四个单独的类,每个类代表一种数学运算。这里我将展示如何创建和测试每个类:
1. **Addition类**:
```java
public class Addition {
public int add(int a, int b) {
return a + b;
}
}
```
**单元测试**:
```java
@Test
public void testAddition() {
Addition addition = new Addition();
assertEquals(5, addition.add(2, 3));
assertEquals(0, addition.add(0, 0));
assertNotEquals(-1, addition.add(1, -1)); // 验证负数加法
}
```
2. **Subtraction类**:
```java
public class Subtraction {
public int subtract(int a, int b) {
return a - b;
}
}
```
**单元测试**:
```java
@Test
public void testSubtraction() {
Subtraction subtraction = new Subtraction();
assertEquals(1, subtraction.subtract(3, 2));
assertEquals(0, subtraction.subtract(0, 0));
assertNotEquals(5, subtraction.subtract(2, 3)); // 验证正负数减法
}
```
3. **Multiplication类**:
```java
public class Multiplication {
public int multiply(int a, int b) {
return a * b;
}
}
```
**单元测试**:
```java
@Test
public void testMultiplication() {
Multiplication multiplication = new Multiplication();
assertEquals(8, multiplication.multiply(2, 4));
assertEquals(0, multiplication.multiply(0, 5));
assertNotEquals(-10, multiplication.multiply(2, -5)); // 验证负数乘法
}
```
4. **Division类** (注意这里是Java 7及以后版本,因为Java 6及更早版本没有`BigDecimal`用于精确除法):
```java
import java.math.BigDecimal;
public class Division {
public BigDecimal divide(int a, int b) {
return BigDecimal.valueOf(a).divide(BigDecimal.valueOf(b));
}
}
```
**单元测试**:
```java
@Test
public void testDivision() {
Division division = new Division();
assertEquals(new BigDecimal("2"), division.divide(4, 2));
assertEquals(BigDecimal.ZERO, division.divide(0, 5));
try {
division.divide(4, 0);
fail("Should throw an exception when dividing by zero");
} catch (ArithmeticException expected) {}
}
```
阅读全文