如何用JUnit单元测试List

问题

JUnit测试List时差强人意。

解法

引入依赖

hamcrest-library包含许多有用方法来测试List数据类型。

<dependencies>
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
		<exclusions>
			<exclusion>
				<groupId>org.hamcrest</groupId>
				<artifactId>hamcrest-core</artifactId>
			</exclusion>
		</exclusions>
	</dependency>

	<!-- This will get hamcrest-core automatically -->
	<dependency>
		<groupId>org.hamcrest</groupId>
		<artifactId>hamcrest-library</artifactId>
		<version>1.3</version>
		<scope>test</scope>
	</dependency>
	...

断言含有String的List

查阅org.hamcrest.collection包,它包含许多有用方法来测试CollectionList

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.hamcrest.collection.IsEmptyCollection;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.MatcherAssert
### JUnit 单元测试练习题示例 以下是几个常见的 JUnit 单元测试练习题及其说明: #### 1. 基础加法计算器功能测试 编一个简单的 `Calculator` 类,其中包含一个方法 `add(int a, int b)` 来计算两个整数的和。创建一个 JUnit 测试类来验证该方法的功能。 ```java public class Calculator { public int add(int a, int b) { return a + b; } } ``` 对应的 JUnit 测试代码如下所示[^4]: ```java import static org.junit.Assert.*; import org.junit.Test; public class CalculatorTest { @Test public void testAdd() { Calculator calculator = new Calculator(); assertEquals(5, calculator.add(2, 3)); // 验证正常情况下的加法运算 assertEquals(-1, calculator.add(-5, 4)); // 验证负数相加的情况 assertEquals(0, calculator.add(0, 0)); // 验证零值输入的结果 } } ``` --- #### 2. 字符串反转功能测试 设计一个字符串处理工具类 `StringUtils`,其内部有一个静态方法 `reverse(String str)` 可以返回给定字符串的逆序形式。通过 JUnit测试用例来验证此方法的行为。 ```java public class StringUtils { public static String reverse(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } } ``` JUnit 测试代码如下: ```java import static org.junit.Assert.*; import org.junit.Test; public class StringUtilsTest { @Test public void testReverse() { assertEquals("ti tahW", StringUtils.reverse("What it")); // 正常字符串反转 assertEquals("", StringUtils.reverse("")); // 空字符串测试 assertEquals(null, StringUtils.reverse(null)); // null 输入测试 } } ``` --- #### 3. 数组最大值查找器测试 定义一个名为 `ArrayUtils` 的工具类,它具有一个静态方法 `findMax(int[] array)`,可以找出数组中的最大值。使用 JUnit 进行单元测试以确认其实现正确无误。 ```java public class ArrayUtils { public static Integer findMax(Integer[] array) { if (array == null || array.length == 0) { return null; } int max = array[0]; for (int num : array) { if (num > max) { max = num; } } return max; } } ``` JUnit 测试代码如下: ```java import static org.junit.Assert.*; import org.junit.Test; public class ArrayUtilsTest { @Test public void testFindMax() { Integer[] numbers = {1, 5, 8, 9}; assertEquals((Integer) 9, ArrayUtils.findMax(numbers)); // 正常数据集的最大值检测 Integer[] emptyArray = {}; assertNull(ArrayUtils.findMax(emptyArray)); // 空数组测试 Integer[] arrayWithNegatives = {-1, -5, -7}; assertEquals((Integer)(-1), ArrayUtils.findMax(arrayWithNegatives)); // 负数值集合的最大值检测 } } ``` --- #### 4. 文件读取异常捕获测试 假设我们有这样一个场景:需要从文件中读取内容并将其转换成字符串列表。如果文件不存在,则抛出特定类型的自定义异常 `FileNotFoundExceptionWrapper`。我们需要针对这个逻辑编 JUnit 测试案例。 ```java import java.io.File; import java.util.ArrayList; import java.util.List; public class FileReaderUtil { public List<String> readFileContent(File file) throws FileNotFoundExceptionWrapper { if (!file.exists()) { throw new FileNotFoundExceptionWrapper(file.getName()); } List<String> contentList = new ArrayList<>(); // 模拟实际读取操作... return contentList; } } class FileNotFoundExceptionWrapper extends Exception { public FileNotFoundExceptionWrapper(String message) { super(message); } } ``` JUnit 测试代码如下: ```java import static org.junit.Assert.*; import org.junit.Test; import java.io.File; public class FileReaderUtilTest { @Test(expected = FileNotFoundExceptionWrapper.class) public void testReadFileContent_FileNotFound() throws Exception { File nonExistentFile = new File("non_existent_file.txt"); FileReaderUtil util = new FileReaderUtil(); util.readFileContent(nonExistentFile); // 应当触发异常 } } ``` --- #### 5. GoLang 中类似的单元测试对比 虽然本问题是围绕 Java 和 JUnit 展开的讨论,但也可以提及其他编程语言如何实现相似的目标。例如,在 Golang 中可以通过内置的 `testing` 包完成类似的任务。Golang 使用 `go test` 自动发现所有 `_test.go` 文件内的测试函数,并按照指定规则执行这些测试[^3]。 ```go package main import ( "testing" ) func TestAdd(t *testing.T) { result := Add(2, 3) if result != 5 { t.Errorf("Expected %d but got %d", 5, result) } } func Add(a, b int) int { return a + b } ``` 以上展示了不同语言环境下单元测试的设计思路以及实践方式之间的异同之处。 --- ###
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值