对个人项目词频统计进行单元测试,使用工具是vs2015中的MS Test。
代码及单元测试版本控制:
HTTPS:https://git.coding.net/li_yuhuan/WordFrequency.git
SSH:[email protected]:li_yuhuan/WordFrequency.git
GIT:git://git.coding.net/li_yuhuan/WordFrequency.git
单元测试:
1.对一段字符串进行分割并将分割后的单词及其对应的频次存入Dictionary。
输入:
“My English is very very pool.”
期待输出:
{"my", 1},
{"english", 1},
{"is", 1},
{"very", 2},
{"pool", 1}
(1)对应单元代码片段
static public void Frequency(string line) { List<string> words = new List<string>(); string word = string.Empty; char[] split = { ‘ ‘, ‘,‘, ‘?‘, ‘?‘, ‘.‘, ‘。‘, ‘-‘, ‘—‘, ‘"‘, ‘:‘, ‘:‘, ‘\r‘, ‘\n‘, ‘(‘, ‘)‘, ‘“‘, ‘”‘ }; words.AddRange(line.Split(split)); foreach (string str in words) { if (str != "" && str != null) { word = str.ToLower(); if (m_wordList.ContainsKey(word)) { m_wordList[word] += 1; } else { m_wordList.Add(word, 1); } } } }
(2)对应测试用例代码
[TestMethod()] public void FrequencyTest() { string input = "My English is very very pool"; Dictionary<string, int> expected = new Dictionary<string, int>() { {"my", 1}, {"english", 1}, {"is", 1}, {"very", 2}, {"pool", 1} }; Program.Frequency(input); Dictionary<string, int> actual = Program.m_wordList; CollectionAssert.AreEqual(expected, actual); }
2.将传入的Dictionary进行排序,返回排序后的List
输入:
{"my", 1},
{"english", 1},
{"is", 1},
{"very", 2},
{"pool", 1}
期待输出:
{"very", 2},
{"my", 1},
{"english", 1},
{"is", 1},
{"pool", 1}
(1)对应单元代码片段
static public List<KeyValuePair<string, int>> DictionarySort(Dictionary<string, int> dictionary) { List<KeyValuePair<string, int>> lst = new List<KeyValuePair<string, int>>(dictionary); if (dictionary.Count > 0) { lst.Sort(delegate (KeyValuePair<string, int> s1, KeyValuePair<string, int> s2) { return s2.Value.CompareTo(s1.Value); }); dictionary.Clear(); Console.WriteLine("total " + lst.Count + " words\n"); int k = 0; foreach (KeyValuePair<string, int> kvp in lst) { if (k < m_top) { Console.WriteLine(kvp.Key + ":" + kvp.Value); k++; } } Console.WriteLine("----------------------------\n"); } return lst; }
(2)对应测试用例代码
[TestMethod()] public void DictionarySortTest() { Dictionary<string, int> input = new Dictionary<string, int>() { {"my", 1}, {"english", 1}, {"is", 1}, {"very", 2}, {"pool", 1} }; List<KeyValuePair<string, int>> expected = new List<KeyValuePair<string, int>>(new Dictionary<string, int>() { {"very", 2}, {"my", 1}, {"english", 1}, {"is", 1}, {"pool", 1} }); List<KeyValuePair<string, int>> actual = Program.DictionarySort(input); CollectionAssert.AreEqual(expected, actual); }
运行测试后的结果:
原有的代码有些并没有显示的返回值,所以有些方法增加了返回值便于与预期输出进行比较检验是否通过测试。
PSP:
日期 | 类别 | 内容 | 开始时间 | 结束时间 | 中断时间 | 净时间 |
9.27 | 学习 | 查询学习单元测试资料 | 13:32 | 14:40 | 16 | 52 |
9.27 | 修改函数 | 给一些没有返回值的函数增加返回值等 | 14:50 | 15:13 | 0 | 23 |
9.27 | 单元测试编码 | 编写单元测试代码 | 15:26 | 16:55 | 13 | 76 |
9.27 | 运行测试 | 运行单元测试 | 17:00 | 17:03 | 0 | 3 |
时间: 2024-10-24 19:15:50