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)编写单元测试进行测试;
1 import org.junit.Test; 2 public class CountTest { 3 @Test 4 public void testCount() throws Exception { 5 String str="i love you ! and you ? "; 6 Count.count(str); 7 } 8 }
(3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。
2、 学习单元测试代码覆盖率工具的使用
(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)编写单元测试进行测试;
1 import org.junit.Test; 2 3 public class ReverseTest { 4 5 @Test 6 public void test() throws Exception { 7 String str="how are you"; 8 Reverse.reverse(str); 9 } 10 11 }
(3)用ElcEmma查看代码覆盖率,要求覆盖率达到100%。