1、 学习单元测试和代码覆盖率工具的使用
(1)写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);
1 import java.util.ArrayList;
2 import java.util.Collections;
3 import java.util.Comparator;
4 import java.util.HashMap;
5 import java.util.List;
6 import java.util.Map;
7 import java.util.Scanner;
8 import java.util.Map.Entry;
9
10 public class Count {
11 private static String str;
12 public Count (String str){
13 Count.str=str;
14 }
15 public static void main(String[] args) {
16 System.out.print("请输入您要测试的字符串:");
17 Scanner in=new Scanner(System.in);
18 str = in.nextLine();
19 count(str);
20
21 }
22
23 public static void count(String str){
24 String[] items = str.split(" ");
25 Map
26 for (String s : items) {
27 if (map.containsKey(s))
28 map.put(s, map.get(s) + 1);
29 else {
30 map.put(s, 1);
31 }
32 }
33 List
34 for (Entry
35 list.add(entry);
36 }
37 Collections.sort(list, new EntryComparator());
38
39 for (Entry
40 System.out.println(obj.getKey() + " " + obj.getValue());
41 }
42 }
43 }
44
45 class EntryComparator implements Comparator
46 public int compare(Entry
47 return o1.getValue() > o2.getValue() ? 0 : 1;
48 }
49 }
(2)编写单元测试进行测试;
import org.junit.Test;
public class CountTest {
@Test
public void testCount() throws Exception {
String str="i love you! and you? ";
Count.count(str);
}
}
(3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。
(1)把一个英语句子中的单词次序颠倒后输出。例如输入“how are you”,输出“you are how”;
1 import java.util.Scanner;
2
3 public class Reverse{
4
5 public static void main(String[] args) {
6 Scanner input = new Scanner(System.in);
7 System.out.print("请输入您要颠倒的字符串:");
8 String str = input.nextLine();
9 Reverse.reverse(str);
10 }
11 public static void reverse(String str){
12 String[] strArr = str.split("s+|[,]");
13 StringBuffer result = new StringBuffer();
14 for(int i = strArr.length -1;i >=0; i--){
15 result.append(strArr[i] + " ");
16 }
17
18 result.setCharAt(str.length()-0, (char) 0);
19 System.out.println("颠倒后的结果为: "+result.toString());
20
21 }
22 }
(2)编写单元测试进行测试;
1importorg.junit.After;
2importorg.junit.Test;
3publicclassReverseTest{
4
5@Test
6publicvoidtest()throwsException{
7Stringstr="howareyou";
8Reverse.reverse(str);
9}
10
11}
(3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。