红魔咖啡馆

头发越掉越多,头发越掉越少

0%

【CS61B】Lec6-Testing

Testing

Unit Tests

测试库

可以使用一些库中的语句进行测试,如:Truth库、JUnits库等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package lec6;
import static com.google.common.truth.Truth.assertThat;

public class TestSort {
    public static void testSort(){
        String[] input = {"bob", "luka", "C++"};
        String[] expected = {"bob", "C++", "luka"};
        Sort.sort(input);

        assertThat(input).isEqualTo(expected);
    }
    public static void main(String[] args){
        testSort();
    }
}

@test

使用标识符@test可以实现在文件中直接写入测试,而不需要在main函数中调用

IDEA中,使用该测试可以使用其自带的单元测试框架,可观列出测试结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package lec6;
import org.junit.jupiter.api.Test;

import static com.google.common.truth.Truth.assertThat;

public class TestSort {
    @Test
    public void testSort(){
        String[] input = {"bob", "luka", "C++"};
        String[] expected = {"bob", "C++", "luka"};
        Sort.sort(input);

        assertThat(input).isEqualTo(expected);
    }
}

Example: Building Selection Sort

原理:

  • 选择最小的元素
  • 移至表头
  • 对剩下n-1个元素进行选择排序

思路:

代码:测试部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package lec6;
import org.junit.jupiter.api.Test;

import static com.google.common.truth.Truth.assertThat;

public class TestSort {
    @Test
    public void testFindSmallest(){
        String[] input = {"bob", "luka", "c++"};
        int expected = 0;
        int actual = Sort.findSmallest(input, 0);
        assertThat(actual).isEqualTo(expected);
    }

    @Test
    public void testSwap(){
        String[] input = {"bob", "luka", "c++"};
        String[] expected = {"luka", "bob", "c++"};

        Sort.swap(input, 0, 1);
        assertThat(input).isEqualTo(expected);
    }
}

实现部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package lec6;

public class Sort {
    public static void sort(String[] x){
        sort(x, 0);
    }
    public static void sort(String[] x, int s){
        if (s == x.length){
            return ;
        }
        int smallest = findSmallest(x, s);
        swap(x, s, smallest);
        sort(x,s+1);

    }
    public static int findSmallest(String[] x, int s){
        int smallestIndex = s;
        for (int i = s; i<x.length; i++){
            int cmp = x[i].compareTo(x[smallestIndex]);
            if (cmp<0){
                smallestIndex = i;
            }
        }
        return smallestIndex;

    }
    public static void swap(String[] x, int a, int b){
        String temp = x[a];
        x[a] = x[b];
        x[b] = temp;
    }
}

综上,测试可以增强代码的鲁棒性

  • 在单元测试中增加信心
  • 确保之后的改变不会破坏代码
  • 辅助代码的重构