安全中国首页 > 编程中心 > .NET编程
 
安全中国网友投稿专用上传FTP空间:
Ftp服务器:download.anqn.com
Ftp端口:21
用户名:anqn
密 码:anqn.com
 

为Asp.net控件写单元测试(ViewState)[1]

更新时间:2008-7-29 15:14:32
责任编辑:ShellExp
热 点:
通常一个典型的asp.net控件至少会用ViewState存储一些属性,以便于在页面postback后不用重新设置。在这篇文章里我将介绍如何为控件写单元测试,以确保一个属性被正确的保存在ViewState里。

为了演示,我写了一个简单的控件。

namespace Eilon.Sample.Controls {
using System;
using System.Web.UI;
public class NewLabel : Control {
public string Text {
get {
string s = ViewState["Text"] as string;
return s ?? String.Empty;
}
set {
ViewState["Text"] = value;
}
}
protected override void Render(HtmlTextWriter writer) {
writer.Write(Text);
}
}
}

        这个控件只是简单的将它唯一的属性Text输出。

        好的,让我们写一个简单的单元测试,以确保这个控件正确的工作。

namespace Eilon.Sample.Controls.Test {
using System;
using System.IO;
using System.Web.UI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class NewLabelTest {
[TestMethod]
public void TextReturnsEmptyStringDefault() {
NewLabel label = new NewLabel();
Assert.AreEqual(String.Empty, label.Text,

"Default text should be empty string (not null)");
}
[TestMethod]
public void GetSetText() {
const string value = "Some Text";
NewLabel label = new NewLabel();
label.Text = value;
Assert.AreEqual(value, label.Text,

"Property value isn't the same as what we set");
}
[TestMethod]
public void RenderEmpty() {
NewLabel label = new NewLabel();
Assert.AreEqual(String.Empty, GetRenderedText(label),

"Shouldn't have rendered anything");
}
[TestMethod]
public void RenderWithText() {
const string value = "Some Text";
NewLabel label = new NewLabel();
label.Text = value;
Assert.AreEqual(value, GetRenderedText(label),

"Should have rendered the text");
}
private static string GetRenderedText(Control c) {
HtmlTextWriter writer = new HtmlTextWriter(new StringWriter());
c.RenderControl(writer);
return writer.InnerWriter.ToString();
}
}
}

看上去我们已经覆盖了100%的代码,是这样吗?事实上我们根本不能保证这个控件的属性已经被正确的存储到ViewState里了。可是我们知道与ViewState有关的函数都是protected的,并不能从外部访问。解决这个问题,可以有很多办法,这里我们写一个internal interface,

 
学习软件编程开发技术,推荐加入以下软件编程培训班:
易语言软件编程培训班(简单易学)  Delphi软件编程培训班  VC++软件编程培训班
VB软件编程培训班  JAVA高端编程就业研发班

学习网站开发制作技术,推荐加入以下网站开发培训班:
ASP.net网站开发项目实战班  ASP语言网站建设培训班

学习网络安全入侵防护技术,推荐加入以下技术培训班:
大型网络安全入侵防护班  网站脚本程序全方位安全检测班

学习网络管理、网吧运营维护技术(网管),推荐加入以下培训班:
大型网吧技术管理人才特训班  Linux网络嵌入架构工程师培训班

学习专项特殊技术,推荐加入以下专项技术培训班:
软件与游戏外挂脱壳破解班(逆向工程)  赚钱王道-网赚技能培训班  Flash动画设计师就业特训班

 
相关编程
一日一文章
 
一日一软件
一日一动画