《软件测试》实验二 单元测试
1.(1) 写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Demo {
public void wordsCount(String str) {
String[] wordsArray = str.split(" ");
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (String word : wordsArray) {
if (wordsMap.containsKey(word)) {
wordsMap.put(word, wordsMap.get(word) + 1);
}
else {
wordsMap.put(word, 1);
}
}
Set<String> setKey = wordsMap.keySet();
Iterator<String> itKey = setKey.iterator();
while (itKey.hasNext()) {
String word = itKey.next().toString();
int count = wordsMap.get(word);
System.out.println("单词:" + word + " 出现了" + count + "次");
}
}
}
(2) 编写单元测试进行测试;
import static org.junit.Assert.*;
import org.junit.Test;
public class DemoTest {
@Test
public void test() {
Demo demo = new Demo();
demo.wordsCount("Hello This Is A Test Test");
}
}
(3) 用ElcEmma查看代码覆盖率,要求覆盖率达到100%。
2.(1) 把一个英语句子中的单词次序颠倒后输出。例如输入“how are you”,输出“you are how”;
public class Demo {
public void upsideDown(String str) {
String[] wordsArray = str.split(" ");
System.out.print("单词倒序输出: ");
for (int i = wordsArray.length - 1; i >= 0; i--) {
System.out.print(wordsArray[i] + " ");
}
}
}
(2) 编写单元测试进行测试;
import static org.junit.Assert.*;
import org.junit.Test;
public class DemoTest {
@Test
public void test() {
Demo demo = new Demo();
demo.upsideDown("Hello This Is A Test Test");
}
}
(3) 用ElcEmma查看代码覆盖率,要求覆盖率达到100%。