对返回整数的绝对值方法进行错误测试的java代码
时间: 2024-05-10 18:18:47 浏览: 6
以下是一个错误测试的Java代码:
```java
public class AbsTest {
public static void main(String[] args) {
int result = Math.abs("abc"); // 传入字符串,应该报错
System.out.println(result);
}
}
```
当我们运行该代码时,应该会抛出一个 `java.lang.NumberFormatException` 异常,因为 `Math.abs()` 方法只接受数字类型的参数。
相关问题
对返回给定整数的绝对值方法进行错误处理测试的Java代码
以下是一个Java程序,用于测试返回给定整数的绝对值的方法的错误处理:
```java
public class AbsoluteValueTest {
public static void main(String[] args) {
testAbs();
}
public static void testAbs() {
int[] testCases = {0, -5, 10};
int[] expectedResults = {0, 5, 10};
for (int i = 0; i < testCases.length; i++) {
int result = abs(testCases[i]);
if (result != expectedResults[i]) {
System.out.println("Error: abs(" + testCases[i] + ") returned " + result +
", but expected " + expectedResults[i]);
}
}
try {
abs(Integer.MIN_VALUE);
} catch (Exception e) {
System.out.println("Error: abs(Integer.MIN_VALUE) threw an exception");
}
}
public static int abs(int num) {
if (num == Integer.MIN_VALUE) {
throw new IllegalArgumentException("Cannot take absolute value of Integer.MIN_VALUE");
}
return num < 0 ? -num : num;
}
}
```
这个程序首先定义一些测试用例和预期结果,然后使用循环来测试`abs()`方法是否能够正确地计算绝对值。除此之外,它还使用了一个try-catch块来测试当输入为`Integer.MIN_VALUE`时,`abs()`是否会抛出异常。如果程序检测到任何错误,它将输出一条错误消息。
单元测试对返回给定整数的绝对值方法进行出错处理的Java测试代码
以下是一个使用JUnit进行单元测试的Java测试代码示例,测试返回给定整数的绝对值方法是否正确地处理错误情况:
```java
import org.junit.Test;
import static org.junit.Assert.*;
public class AbsoluteValueTest {
@Test
public void testPositiveNumber() {
assertEquals(5, AbsoluteValue.abs(5));
}
@Test
public void testNegativeNumber() {
assertEquals(5, AbsoluteValue.abs(-5));
}
@Test(expected = IllegalArgumentException.class)
public void testExceptionThrown() {
AbsoluteValue.abs(Integer.MIN_VALUE);
}
}
```
在这个示例中,我们使用JUnit的`@Test`注释来标记测试方法。`assertEquals()`方法用于比较实际结果和预期结果是否相等。第一个测试方法测试当传递正数给`abs()`方法时它是否返回正确的值。第二个测试方法测试当传递负数给`abs()`方法时它是否返回正确的值。第三个测试方法测试当传递`Integer.MIN_VALUE`给`abs()`方法时它是否抛出了预期的`IllegalArgumentException`异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)