import java.util.StringTokenizer;
import junit.framework.TestCase;
public class StringUtilTest extends TestCase {
protected void setUp() throws Exception {
System.out.println("setUp()");
}
protected void tearDown() {
System.out.println("tearDown()");
}
public void testSplit() {
System.out.println("testSplit");
String[] strs = StringUtil.split("a,b,cc");
assertEquals("a", strs[0]);
assertEquals("b", strs[1]);
assertEquals("ccc", strs[2]);
strs = StringUtil.split("");
assertEquals(0, strs.length);
strs = StringUtil.split(",");
assertEquals(0, strs.length);
strs = StringUtil.split("a");
assertEquals(1, strs.length);
assertEquals("a", strs[0]);
}
public void testSplitExcetion() {
System.out.println("testSplitExcetion");
try {
StringUtil.split(null);
fail("must throw exception,when split string is null");
} catch (Exception e) {
assertTrue(true);
}
}
}
class StringUtil {
public static String[] split(String mainStr) {
if (mainStr == null) {
throw new IllegalArgumentException();
}
StringTokenizer s = new StringTokenizer(mainStr, ",");
int count = s.countTokens();
String[] strs = new String[count];
for (int i = 0; i < count; i++) {
strs[i] = s.nextToken();
}
return strs;
}
}
说明:运行测试类时会自动执行测试方法。另外测试类中还有两个重要的方法setUp(),tearDown(),setUp()用于写一些初始化的代码,每个测试方法在执行之前都会先执行setUp(),tearDown()用于写一些清理代码,每个测试方法在执行之后也会再执行tearDown()。有多少测试方法,这两个方法就要执行多少次。
import junit.framework.TestCase;
public class StringUtilTest extends TestCase {
protected void setUp() throws Exception {
System.out.println("setUp()");
}
protected void tearDown() {
System.out.println("tearDown()");
}
public void testSplit() {
System.out.println("testSplit");
String[] strs = StringUtil.split("a,b,cc");
assertEquals("a", strs[0]);
assertEquals("b", strs[1]);
assertEquals("ccc", strs[2]);
strs = StringUtil.split("");
assertEquals(0, strs.length);
strs = StringUtil.split(",");
assertEquals(0, strs.length);
strs = StringUtil.split("a");
assertEquals(1, strs.length);
assertEquals("a", strs[0]);
}
public void testSplitExcetion() {
System.out.println("testSplitExcetion");
try {
StringUtil.split(null);
fail("must throw exception,when split string is null");
} catch (Exception e) {
assertTrue(true);
}
}
}
class StringUtil {
public static String[] split(String mainStr) {
if (mainStr == null) {
throw new IllegalArgumentException();
}
StringTokenizer s = new StringTokenizer(mainStr, ",");
int count = s.countTokens();
String[] strs = new String[count];
for (int i = 0; i < count; i++) {
strs[i] = s.nextToken();
}
return strs;
}
}
说明:运行测试类时会自动执行测试方法。另外测试类中还有两个重要的方法setUp(),tearDown(),setUp()用于写一些初始化的代码,每个测试方法在执行之前都会先执行setUp(),tearDown()用于写一些清理代码,每个测试方法在执行之后也会再执行tearDown()。有多少测试方法,这两个方法就要执行多少次。