根据VS2015的提示,仅支持在共有类或共有方法中支持创建单元测试。所以,如果我们要测试私有或是保护的类和方法,是要先将他们暂时设定成公有类型。

在VS2015中创建单元测试,只要在我们想测试的地方点击右键,就会出现 “创建单元测试” 选项。

如果菜单没有显示 测试,可以参照这篇博客进行设置。http://www.bubuko.com/infodetail-1370830.html

单击 “创建单元测试” 后,会出项如下对话框。不用修改,保持默认选项就可以。

点击“确定”

创建完成后,会出项一个名为 “WCTests” 的文件,代码:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using wc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace wc.Tests
{
[TestClass()]
public class WCTests
{
[TestMethod()]
public void WCTest()
{
Assert.Fail();
} [TestMethod()]
public void OperatorTest()
{
Assert.Fail();
}
}
}

在进行单元测试时,主要使用的是 Assert 类,他的用发有很多,详细用法可以参照 https://msdn.microsoft.com/zh-cn/library/microsoft.visualstudio.testtools.unittesting.assert.aspx

下面给出我们要进行测试的代码,为了方便测试,我们对其中代码输出的部分进行了修改,将原先控制台输出的部分改成了函数返回。

public class WC
{
private string sFilename; // 文件名
private string[] sParameter; // 参数数组
private int iCharcount; // 字符数
private int iWordcount; // 单词数
private int iLinecount; // 行 数
private int iNullLinecount; // 空行数
private int iCodeLinecount; // 代码行数
private int iNoteLinecount; // 注释行数 // 初始化
public WC()
{
this.iCharcount = ;
this.iWordcount = ;
this.iLinecount = ;
this.iNullLinecount = ;
this.iCodeLinecount = ;
this.iNoteLinecount = ;
}
// 控制信息
public string Operator(string[] sParameter, string sFilename)
{
this.sParameter = sParameter;
this.sFilename = sFilename; string retrun_str = ""; foreach (string s in sParameter)
{
if(s == "-x")
{
string resultFile = "";
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "D:\\Patch";
fd.Filter = "All files (*.*)|*.*|txt files (*.txt)|*.txt";
fd.FilterIndex = ;
fd.RestoreDirectory = true;
if (fd.ShowDialog() == DialogResult.OK)
{
resultFile = fd.FileName;
//Console.WriteLine("文件名:{0}", resultFile);
SuperCount(resultFile);
BaseCount(resultFile);
retrun_str = DisplayAll();
}
break;
}
// 遍历文件
else if (s == "-s")
{
try
{
string[] arrPaths = sFilename.Split('\\');
int pathsLength = arrPaths.Length;
string path = ""; // 获取输入路径
for (int i = ; i < pathsLength - ; i++)
{
arrPaths[i] = arrPaths[i] + '\\'; path += arrPaths[i];
} // 获取通配符
string filename = arrPaths[pathsLength - ]; // 获取符合条件的文件名
string[] files = Directory.GetFiles(path, filename); foreach (string file in files)
{
//Console.WriteLine("文件名:{0}", file);
SuperCount(file);
BaseCount(file);
retrun_str = Display();
}
break;
}
catch (IOException ex)
{
//Console.WriteLine(ex.Message);
return "";
}
}
// 高级选项
else if (s == "-a")
{
//Console.WriteLine("文件名:{0}", sFilename);
SuperCount(sFilename);
BaseCount(sFilename);
retrun_str = Display();
break;
}
// 基本功能
else if (s == "-c" || s == "-w" || s == "-l")
{
//Console.WriteLine("文件名:{0}", sFilename);
BaseCount(sFilename);
retrun_str = Display();
break;
}
else
{
//Console.WriteLine("参数 {0} 不存在", s);
break;
}
}
Console.WriteLine("{0}", retrun_str);
return retrun_str;
} // 统计基本信息:字符数 单词数 行数
private void BaseCount(string filename)
{
try
{
// 打开文件
FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(file);
int nChar;
int charcount = ;
int wordcount = ;
int linecount = ;
//定义一个字符数组
char[] symbol = { ' ', ',', '.', '?', '!', ':', ';', '\'', '\"', '\t', '{', '}', '(', ')', '+' ,'-',
'*', '='};
while ((nChar = sr.Read()) != -)
{
charcount++; // 统计字符数 foreach (char c in symbol)
{
if(nChar == (int)c)
{
wordcount++; // 统计单词数
}
}
if (nChar == '\n')
{
linecount++; // 统计行数
}
}
iCharcount = charcount;
iWordcount = wordcount + ;
iLinecount = linecount + ;
sr.Close();
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return;
}
} // 统计高级信息:空行数 代码行数 注释行数
private void SuperCount(string filename)
{
try
{
// 打开文件
FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
StreamReader sr = new StreamReader(file);
String line;
int nulllinecount = ;
int codelinecount = ;
int notelinecount = ;
while ((line = sr.ReadLine()) != null)
{
line = line.Trim(' ');
line = line.Trim('\t');
// 空行
if (line == "" || line.Length <= )
{
nulllinecount++;
}
// 注释行
else if(line.Substring(, ) == "//" || line.Substring(, ) == "//")
{
notelinecount++;
}
// 代码行
else
{
codelinecount++;
}
}
iNullLinecount = nulllinecount;
iCodeLinecount = codelinecount;
iNoteLinecount = notelinecount;
sr.Close();
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
return;
}
}
// 打印信息
private string Display()
{
string return_str = ""; foreach (string s in sParameter)
{
if (s == "-c")
{
//Console.WriteLine("字 符 数:{0}", iCharcount);
return_str += "字符数:"+iCharcount.ToString();
}
else if (s == "-w")
{
//Console.WriteLine("单 词 数:{0}", iWordcount);
return_str += "单词数:" + iWordcount.ToString();
}
else if (s == "-l")
{
//Console.WriteLine("总 行 数:{0}", iLinecount);
return_str += "总行数:" + iLinecount.ToString();
}
else if(s == "-a")
{
//Console.WriteLine("空 行 数:{0}", iNullLinecount);
//Console.WriteLine("代码行数:{0}", iCodeLinecount);
//Console.WriteLine("注释行数:{0}", iNoteLinecount);
return_str += "空行数:" + iNullLinecount.ToString();
return_str += "代码行数:" + iCodeLinecount.ToString();
return_str += "注释行数:" + iNoteLinecount.ToString();
}
}
//Console.WriteLine();
return return_str;
}
private string DisplayAll()
{
string return_str = "";
foreach (string s in sParameter)
{
//Console.WriteLine("字 符 数:{0}", iCharcount);
//Console.WriteLine("单 词 数:{0}", iWordcount);
//Console.WriteLine("总 行 数:{0}", iLinecount);
//Console.WriteLine("空 行 数:{0}", iNullLinecount);
//Console.WriteLine("代码行数:{0}", iCodeLinecount);
//Console.WriteLine("注释行数:{0}", iNoteLinecount);
return_str += "字符数:" + iCharcount.ToString();
return_str += "单词数:" + iWordcount.ToString();
return_str += "总行数:" + iLinecount.ToString();
return_str += "空行数:" + iNullLinecount.ToString();
return_str += "代码行数:" + iCodeLinecount.ToString();
return_str += "注释行数:" + iNoteLinecount.ToString();
}
//Console.WriteLine();
return return_str;
}
}

接下来,我们对测试代码进行修改,在我们进行单元测试时,某种程度上就是将我们人工给出的程序运行结果与程序实际输出结果进行比较,所以单元测试的过程一般分为 3 步:

  • 给出我们期望的结果 expected
  • 执行需测试代码,返回结果 actual
  • 比较 actual 和 expected

下面以 WC 程序执行 -c 参数对 123.txt 文件进行统计的功能为例进行测试,我们将测试代码修改如下,其中 AreEqual 方法用于对期望值与实际值进行比较。

using Microsoft.VisualStudio.TestTools.UnitTesting;
using wc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace wc.Tests
{
[TestClass()]
public class WCTests
{
[TestMethod()]
public void WCTest()
{
// arrange
string expected = "字符数:138";
WC testwc = new WC(); // act
string[] opar = new string[];
opar[] = "-c"; string actual = testwc.Operator(opar, @"D:\学习\我的工程\软件工程\wc\wc\wc\123.txt"); // assert
Assert.AreEqual(expected, actual);
}
}
}

"123.txt" 文件:

我们预期的测试结果是此文件有138个字符,所以会输出 “字符数:138” ;我们来看看测试的结果,点击右键,选择 “运行测试” ,选项测试通过了。

我们现在给出一个错误的预期来看看结果会如何,我们现在认为 "123.txt" 文件有50个字符。

系统会提示出错,并且给出实际值与期望值分别是多少。

编写测试方法

单元测试的基本方法是调用被测代码的函数,输入函数的参数值,获取返回结果,然后与预期测试结果进行比较,如果相等则认为测试通过,否则认为测试不通过。

1、Assert类的使用

Assert.Inconclusive()    表示一个未验证的测试;

Assert.AreEqual()         测试指定的值是否相等,如果相等,则测试通过;

AreSame()            用于验证指定的两个对象变量是指向相同的对象,否则认为是错误

AreNotSame()        用于验证指定的两个对象变量是指向不同的对象,否则认为是错误

Assert.IsTrue()              测试指定的条件是否为True,如果为True,则测试通过;

Assert.IsFalse()             测试指定的条件是否为False,如果为False,则测试通过;

Assert.IsNull()               测试指定的对象是否为空引用,如果为空,则测试通过;

Assert.IsNotNull()          测试指定的对象是否为非空,如果不为空,则测试通过;

2、CollectionAssert类的使用

用于验证对象集合是否满足条件

StringAssert类的使用

用于比较字符串。

StringAssert.Contains

StringAssert.Matches

StringAssert.tartWith

C#:单元测试(VS2015)的更多相关文章

  1. VS2015安装&简单的C#单元测试

    <软件工程>开课已经三周了,三周的上课感觉就是老师教授的概念性东西少了不少,基本就是贯穿“做中学”的教学理念,三周的时间让我学到了挺多东西,很多东西都是课本没有的. 这周的任务就是安装VS ...

  2. 使用VS2015(c#)进行单元测试,显示测试结果与查看代码覆盖率

    创建测试的过程可参考如下链接 http://www.cnblogs.com/libaoquan/p/5296384.html (一)如何使用VS2015查看测试结果 问题描述:使用VS2010执行单元 ...

  3. vs2015数据驱动的单元测试

    今天在做测试的时候boss让我这个菜鸟做vs2015下c#的单元测试,并且给了我参考http://www.cnblogs.com/kingmoon/archive/2011/05/13/2045278 ...

  4. VS2015安装与C++进行简单单元测试

    1:VS2015是微软最新发布的编译器,http://www.itellyou.cn/这是我们的北航大神助教提供的下载网址,以前我们都是自己在网上找,找到的总不是那么如意,这下大神助教提供的网址就好好 ...

  5. 基于C#的单元测试(VS2015)

    这次来联系怎么用VS2015来进行C#代码的单元测试管理,首先,正好上次写了一个C#的WordCount程序,就用它来进行单元测试联系吧. 首先,根据VS2015的提示,仅支持在共有类或共有方法中支持 ...

  6. VS2015安装及单元测试

    今天跟大家分享一下我的VS2015的安装过程以及对单元测试的操作步骤.VS2015是一款非常好用的编程软件,内容很多很广泛,是深受欢迎的一款软件,较之于VC++6.0有着一些好处,对VC6.0++来说 ...

  7. C# vs2015单元测试测试资源管理器不显示测试方法

    问题描述:在用VS2015用测试框架NUnit单元测试的时候,测试资源管理器死活不出现测试方法,无法运行单元测试模块 现象如下图: 原因:nunit版本不对应 解决方案:下载nunit3.0及往上的版 ...

  8. VS2015 C#的单元测试

    1.安装visual studio 2015过程 visual studio 会对windows系统兼容性有很高的要求,没有达到win7 sp1以上的就不给安装,贴一张官方的系统的要求吧. 很不幸的是 ...

  9. VS2015安装与单元测试

    很久之前就听说微软有一款强大的编程软件——Visual Stdio系列,也许是满足于VC和CB的小巧一直都没有去尝试,借这次软件工程的机会终于可以一睹其真容,第一感觉是高大上,一改VC和CB的简洁,看 ...

随机推荐

  1. python2和Python3的区别(长期更新)

    1.在Python2中无需将打印的内容放在括号内,但是Python3中必须将打印的内容放在括号内,从技术上看Python3中的print是函数. 2.对于用户交互终点额输入input,在python2 ...

  2. JetBrains PyCharm 专业版激活

    激活码获取:http://idea.lanyus.com/ JetbrainsCrack-release-enc.jar下载:提取码为1391

  3. HDU 2058:The sum problem(数学)

    The sum problem Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  4. java-Date类

    1.Date类的概述和方法使用 * A:Date类的概述 * 类 Date 表示特定的瞬间,精确到毫秒. * B:构造方法 * public Date() * public Date(long dat ...

  5. Python字符集

    字符集: 美国:ASCII      需要8bit表示     英文字母一个字节,不支持中文中国:GBK                           英文字母一个字节,汉字占两个字节万国:un ...

  6. crontab 例子

    一个简单的 crontab 示例 0,20,40 22-23 * 7 fri-sat /home/ian/mycrontest.sh 在这个示例中,我们的命令在 7 月的每个星期五和星期六晚上 10 ...

  7. ios-UITableView无内容时,不显示多余的分隔线

    效果如上. 只要补上以下方法: //设置多于的分割线 -(void)setExtraCellLineHidden: (UITableView *)tableView { UIView *view = ...

  8. vue全家桶+Koa2开发笔记(2)--koa2

    1. 安装koa脚手架的时候 执行命令 koa2 -e koa-learn 注意要使用-e的方式,才会生成ejs的模板 2. async await的使用方法:存在的意义:提高promise的可读性 ...

  9. 生产环境部署MongoDB副本集(带keyfile安全认证以及用户权限)

    本文同步于个人Github博客:https://github.com/johnnian/Blog/issues/8,欢迎留言. 安装软件包:mongodb-linux-x86_64-3.4.1.tgz ...

  10. linux之shell终端使用操作快捷键

    所谓的shell终端就是桌面右键里面的打开终端那个终端 敲命令是一件很有趣的事,可是有时候我们会遇到一些很麻烦的事 例如,命令太长导致敲完后一大串字符可读性低,想把vi filename 快速改为ca ...