JUnit 断言和注解

来源:互联网 发布:html静态网页源码 编辑:程序博客网 时间:2024/05/19 04:56

JUint 断言

断言是编写测试类的核心实现方法,这些方法给出一个期望值,通过测试某个调用方法的结果值,来判断测试是都通过;
以下是一些常用的断言的核心方法API:
assertArrayEquals(expecteds, actuals)查看两个数组是否相等。assertEquals(expected, actual)查看两个对象是否相等。类似于字符串比较使用的equals()方法assertNotEquals(first, second)查看两个对象是否不相等。assertNull(object)查看对象是否为空。assertNotNull(object)查看对象是否不为空。assertSame(expected, actual)查看两个对象的引用是否相等。类似于使用“==”比较两个对象assertNotSame(unexpected, actual)查看两个对象的引用是否不相等。类似于使用“!=”比较两个对象assertTrue(condition)查看运行结果是否为true。assertFalse(condition)查看运行结果是否为false。assertThat(actual, matcher)查看实际值是否满足指定的条件fail()让测试失败
以下一个简单示例:

JUint 注解

JUnit注解用于标记测试方法的顺序,规则等,常用的注解如下:
@Before初始化方法@After释放资源@Test测试方法,在这里可以测试期望异常和超时时间@Ignore忽略的测试方法@BeforeClass针对所有测试,只执行一次,且必须为static void@AfterClass针对所有测试,只执行一次,且必须为static void@RunWith指定测试类使用某个运行器@Parameters指定测试类的测试数据集合@Rule允许灵活添加或重新定义测试类中的每个测试方法的行为@FixMethodOrder指定测试方法的执行顺序
对于一个测试类的单元测试的执行顺序为: @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
    @Before
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
    @After
28
    public void after() throws Exception {
29
    }
30
31
    @Test
32
    public void testSelectionSort() throws Exception {
33
        assertArrayEquals(expectedList, Sort.selectionSort(testList));
34
    }
35
36
    @Test
37
    public void testInsertionSort() throws Exception {
38
        assertArrayEquals(expectedList,Sort.insertionSort(testList));
39
    }
40
41
    @Test
42
    public void testBubbleSort() throws Exception {
43
        assertArrayEquals(expectedList,Sort.bubbleSort(testList));
44
    }
45
46
    @Test
47
    public void testShellSort() throws Exception {
48
        assertArrayEquals(expectedList,Sort.shellSort(testList));
49
    }
50
51
} 
52


原创粉丝点击