JUint 断言
断言是编写测试类的核心实现方法,这些方法给出一个期望值,通过测试某个调用方法的结果值,来判断测试是都通过;
以下是一些常用的断言的核心方法API:
以下一个简单示例:
1
2
public void testAssertArrayEquals(){
3
org.junit.Assert.assertArrayEquals({1,2,3,4},{1,3,4,5});
4
}
5
6
public void testAssertEquals(){
7
org.junit.Assert.assertEquals(12,7+5);
8
}
9
10
public void testAssertTrue(){
11
org.junit.Assert.assertTrue(6>7);
12
}
JUint 注解
JUnit注解用于标记测试方法的顺序,规则等,常用的注解如下:
对于一个测试类的单元测试的执行顺序为: @BeforeClass –> @Before –> @Test –> @After –> @AfterClass
每一个测试方法的调用顺序为: @Before –> @Test –> @After
以下示例,待测试的类 demo/Sort.java 为:
1
public class Sort {
2
//几种基础的排序方法,过程省略
3
public static int[] selectionSort(int[] list) {
4
.......
5
}
6
7
public static int[] insertionSort(int[] list) {
8
.......
9
}
10
11
public static int[] bubbleSort(int[] list) {
12
.........
13
}
14
15
public static int[] shellSort(int[] list){
16
.........
17
}
18
19
}
测试类为 test.demo/SortTest.java:
1
package test.demo;
2
3
import demo.Sort;
4
import org.junit.After;
5
import org.junit.Before;
6
import org.junit.Test;
7
import static org.junit.Assert.assertArrayEquals;
8
9
import java.util.Arrays;
10
import java.util.Random;
11
12
public class SortTest {
13
private static final int SIZE = 500; // 测试数组长度
14
private static final int LIMIT = 1000; //测试数组随机数元素数值的上限
15
private int[] testList = new int[SIZE];
16
private int[] expectedList = new int[SIZE];
17
18
19
public void before() throws Exception {
20
//使用随机数填充testList,expectedList
21
Random rand = new Random();
22
testList = Arrays.stream(testList).map(x -> rand.nextInt(LIMIT)).toArray();
23
expectedList = Arrays.stream(testList).sorted().toArray();
24
25
}
26
27
28
public void after() throws Exception {
29
}
30
31
32
public void testSelectionSort() throws Exception {
33
assertArrayEquals(expectedList, Sort.selectionSort(testList));
34
}
35
36
37
public void testInsertionSort() throws Exception {
38
assertArrayEquals(expectedList,Sort.insertionSort(testList));
39
}
40
41
42
public void testBubbleSort() throws Exception {
43
assertArrayEquals(expectedList,Sort.bubbleSort(testList));
44
}
45
46
47
public void testShellSort() throws Exception {
48
assertArrayEquals(expectedList,Sort.shellSort(testList));
49
}
50
51
}
52