博文谷

位置:首頁 > 教師之家 > 練習題

JBuilder2005單元測試之JUnit框架

練習題3.02W

爲了便於講解,擬透過兩個簡單的業務類引出測試用例,一個是分段函數類,另一個是字元串處理類,在這節裏我們先來熟悉這兩個業務類。

分段函數類

分段函數Subsection類有兩個函數,sign()是一個符號函數,而getValue(int d)函數功能如下:

當d < -2時,值爲abs(d);

當-2≤d<2 且d!=0時,值爲d*d;

當d=0時,值爲100;

當2≤d時,值爲d*d*d。

其代碼如下圖所示:

代碼清單 錯誤!文檔中沒有指定樣式的文字。分段函數

1. package chapter25;

2.

3. public class Subsection

4. {

5. public static int getValue(int d) {

6. if (d == 0) {

7. return 100;

8. } else if (d < -2) {

9. return (d);

10.} else if (d >= -2 && d < 2) {

rn d * d;

12.} else { //d >= 2

13.// if (d > 32) {

14.// return _VALUE;

15.// }

16. return d * d * d;

17. }

18. }

19.

20. public static int sign(double d) {

21. if (d < 0) {

22. return -1;

23. } else if (d > 0) {

24. return 1;

25. } else {

26. return 0;

27. }

28. }

29. }

在getValue()方法中,當d>32時,d*d*d的值將超過int數據類型的.最大值(32768),所以當d>32時,理應做特殊的處理,這裏我們特意將這個特殊處理的代碼註釋掉(第13~15行),模擬一個潛在的Bug。

字元串處理類

由於標準JDK中所提供的String類對字元串操作功能有限,而字元串處理是非常常用的操作,所以一般的系統都提供了一個自己的字元串處理類。下面就是一個字元串處理類,爲了簡單,我們僅提供了一個將字元串轉換成數組的方法string2Array(),其代碼如下所示:

代碼清單 錯誤!文檔中沒有指定樣式的文字。字元串處理類

1. package chapter25;

2. public class StringUtils

3. {

4. public static String[] string2Array(String str, char splitChar, boolean trim) {

5. if (str == null) {

6. return null;

7. } else {

8. String tempStr = str;

9. int arraySize = 0; //數組大小

ng[] resultArr = null;

(trim) { //如果需要刪除頭尾多餘的分隔符

Str = trim(str, splitChar);

13.}

ySize = getCharCount(tempStr, splitChar) + 1;

ltArr = new String[arraySize];

fromIndex = 0, endIndex = 0;

(int i = 0; i < th; i++) {

ndex = xOf(splitChar, fromIndex);

(endIndex == -1) {

ltArr[i] = tring(fromIndex);

k;

22.}

ltArr[i] = tring(fromIndex, endIndex);

Index = endIndex + 1;

25.}

rn resultArr;

27.}

28.}

29.

30. //將字元串前面和後面的多餘分隔符去除掉。

ate static String trim(String str, char splitChar) {

beginIndex = 0, endIndex = th();

(int i = 0; i < th(); i++) {

(At(i) != splitChar) {

nIndex = i;

k;

37.}

38.}

(int i = th(); i > 0; i--) {

(At(i - 1) != splitChar) {

ndex = i;

k;

43.}

44.}

rn tring(beginIndex, endIndex);

46.}

47.

48.//計算字元串中分隔符中個數

ate static int getCharCount(String str, char splitChar) {

count = 0;

(int i = 0; i < th(); i++) {

(At(i) == splitChar) {

t++;

54.}

55.}

rn count;

57.}

58. }

除對外API string2Array()外,類中還包含了兩個支援方法。trim()負責將字元前導和尾部的多餘分隔符刪除掉(第31~46行);而getCharCount()方法獲取字元中包含分隔符的數目,以得到目標字元串數組的大小(第49~57行)。