JBuilder2005单元测试之JUnit框架

文思都 人气:2.97W

为了便于讲解,拟通过两个简单的业务类引出测试用例,一个是分段函数类,另一个是字符串处理类,在这节里我们先来熟悉这两个业务类。

分段函数类

分段函数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行)。