单元测试-例子

你的RP是由你的程序质量决定的。软件是由多⼈合作完成的,不同⼈员的⼯作相互有依赖关系。例如,⼀个⼈写的模块被其他⼈写的模块调⽤。软件的很多错误都来源于程序员对模块功能的误解、疏忽或不了解模块的变化。如何能让⾃⼰负责的模块功能定义尽量明确,模块内部的改变不会影响其他模块,⽽且模块的质量能得到稳定的、量化的保证?单元测试就是⼀个很有效的解决⽅案。

例⼦:许多应⽤程序中都会⽤到"⽤户"这⼀类型,⽤户的标识通常是⼀个邮件地址。对应的单元测试该怎么写?我们来练习⼀下。⾸先我们创建了⼀个C#的类库(Class Library),并写了如代码清单所示的代码:

代码清单

namespace DemoUser

{

public class User

{

public User(string userEmail)

{

m_email = userEmail;

}

//user email as user id

private string m_email;

}

}

好,图中,底部窗⼝标题为Create Unit Tests,右键选中User,出现"New Test Project"弹窗,这样就可以创建新的单元测试。

创建好单元测试后,注意到在Solution Explorer中出现了三个新的⽂件。

Class1Test.cs:Class1.cs对应的单元测试⽂件。DemoUser.vsmdi:测试管理⽂件。Localtestrun.testrunconfig:本地测试运⾏设置⽂件。如何管理设置⽂件呢?右键再选属性(Property)并不对,必须双击设置⽂件才能进⼊管理及设置界⾯。进⼊设置界⾯后,可以让单元测试产⽣"demouser.dll"的代码覆盖报告。注意在单元测试中,VSTS⾃动为你⽣成了测试的⾻架,但是你还是要⾃⼰做不少事情,最起码要把那些标注为//TODO的事情给做了(如代码清单2-2所⽰)。此时,单元测试还在使⽤Assert.In-conclusive,表明这是⼀个未经验证的(Inconclu-sive)单元测试。

代码清单

/// <summary>

/// A test for User (string)

/// </summary>

TestMethod()

public void ConstructorTest()

{

// TODO: Initialize to an appropriate

// value User target = new User(userEmail);

string userEmail = null;

// TODO: Implement code to verify target

Assert.Inconclusive("TODO: Implement code to verify target");

代码清单2-2

/// <summary>

/// A test for User (string)

/// </summary>

TestMethod()

public void ConstructorTest()

{

// TODO: Initialize to an appropriate

// value User target = new User(userEmail);

string userEmail = null;

// TODO: Implement code to verify target

Assert.Inconclusive("TODO: Implement code to verify target");}

相关推荐
未知鱼19 小时前
Python安全开发之简易whois查询
java·python·安全
cpp_250119 小时前
P1203 [IOI 1993 / USACO1.1] 坏掉的项链 Broken Necklace
数据结构·c++·算法·线性dp
_小草鱼_19 小时前
【搜索与图论】BFS(广度优先搜索)
算法·图论·bfs·宽度优先
Aloha_up19 小时前
spring的几个八股
java·后端·spring
weixin_4219226919 小时前
分布式日志系统实现
开发语言·c++·算法
逸Y 仙X19 小时前
文章九:ElasticSearch索引字段常见属性
java·大数据·服务器·数据库·elasticsearch·搜索引擎
不想看见40419 小时前
Daily Temperatures单调栈--力扣101算法题解笔记
算法
左左右右左右摇晃19 小时前
Java笔记——多态
java·笔记·python
空空潍19 小时前
2026年IDEA、PyCharm等专业版学生免费申请教育许可证
java·ide·intellij-idea
炽烈小老头19 小时前
【每天学习一点算法 2026/03/21】颜色分类
学习·算法