3137102440_曹庆发。单元测试和代码覆盖率工具的使用

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<String, Integer> map = new HashMap<String, Integer>();
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<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
34         for (Entry<String, Integer> entry : map.entrySet()) {
35             list.add(entry);
36         }
37         Collections.sort(list, new EntryComparator());
38 
39         for (Entry<String, Integer> obj : list) {
40             System.out.println(obj.getKey() + "	" + obj.getValue());
41         }
42     }
43 }
44 
45 class EntryComparator implements Comparator<Entry<String, Integer>> {
46     public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
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”;

import java.util.HashMap;
import java.util.Map;
public class test2_2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = "how are you";
String[] b = a.split(" ");
String c = "";
for(int d=b.length;d>0;d--)
{
c=c+b[d-1]+" ";
}
System.out.println(c);
}
}

(3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。

原文地址:https://www.cnblogs.com/cqfa/p/5323547.html