单元测试和代码覆盖率工具的使用

1、 学习单元测试和代码覆盖率工具的使用

(1)写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Map.Entry;

public class Count {
    private static String str;
    public  Count (String str){
        Count.str=str;
    }
    public static void main(String[] args) {
        System.out.print("请输入您要测试的字符串:");
        Scanner in=new Scanner(System.in);
        str = in.nextLine();
        count(str);
        
    }
    
    public static void count(String str){
        String[] items = str.split(" ");
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (String s : items) {
            if (map.containsKey(s))
                map.put(s, map.get(s) + 1);
            else {
                map.put(s, 1);
            }
        }
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
        for (Entry<String, Integer> entry : map.entrySet()) {
            list.add(entry);
        }
        Collections.sort(list, new EntryComparator());

        for (Entry<String, Integer> obj : list) {
            System.out.println(obj.getKey() + "	" + obj.getValue());
        }
    }
}

class EntryComparator implements Comparator<Entry<String, Integer>> {
    public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
        return o1.getValue() > o2.getValue() ? 0 : 1;
    }
}

(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%。

2.(1)把一个英语句子中的单词次序颠倒后输出。例如输入“how are you”,输出“you are how”;

import java.util.Scanner;

public class Reverse{

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入您要颠倒的字符串:");
String str = input.nextLine();
Reverse.reverse(str);
}
public static void reverse(String str){
String[] strArr = str.split("\s+|[,]");
StringBuffer result = new StringBuffer();
for(int i = strArr.length -1;i >=0; i--){
result.append(strArr[i] + " ");
}

result.setCharAt(str.length()-0, (char) 0);
System.out.println("颠倒后的结果为: "+result.toString());
}
}

 (2)编写单元测试进行测试;

import org.junit.After;
import org.junit.Test;
public class ReverseTest {
    
    @Test
    public void test() throws Exception {
        String str="how are you";
         Reverse.reverse(str);
    }

}
原文地址:https://www.cnblogs.com/jiangrt/p/5395899.html