Silverlight Unit Test简要介绍

Silverlight Unit Test

一、搭建单元测试环境。

1、自定义

a.创建Silverlight Application。
b.将.web删除。
c.引进Microsoft.Silverlight.Testing.dll和Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll。
d.修改App.cs文件。This.RootVisual=UnitTestSystem.CreateTestPage();

2、使用模板

这种方法非常方便,将SilverlightTestProject_CSharp.zip放在“%userprofile%\Documents\Visual Studio 2008\Templates\ProjectTemplates”路径下,
再将SilverlightTestClass_CSharp.zip放在” %userprofile%\Documents\Visual Studio 2008\Templates\ItemTemplates”路径下,解压就行了。之后我们就可以在新建/项目/C#中就可以看到Silverlight Test Project。
最后引进Microsoft.Silverlight.Testing.dll和Microsoft.VisualStudio.QualityTools.UnitTesting.Silverlight.dll。

二、单元测试种类。

1、API 单元测试

a.属性、方法(默认值、正确值、错误值、边界值)
错误值主要是对非法值异常的捕获。
b.设计数据测试。(待解决 ⊙>_<⊙||)[Testing the designer data]

c.测试事件(CollectionChanged)
①    创建实例
②    创建一个bool值,用于监听事件是否能成功。
③    添加断言。
④    调用示例方法来触发事件。

2、UI单元测试

a.需要从SilverlightTest继承;
b.实例化。
c.将其添加到TestPanel,例如:this.TestPanel.Children.Add(XXName);

d.除了对其接口的测试外,还要测试其Template。对这部分的测试需要写个静态类,其中的代码如下:
public static class Common
{
public static IDictionary<string, Type> GetTemplateParts(this Type controlType)
{
Dictionary<string, Type> templateParts = new Dictionary<string, Type>();
foreach (Attribute attribute in controlType.GetCustomAttributes(typeof(TemplatePartAttribute), false))
{
TemplatePartAttribute templatePart = attribute as TemplatePartAttribute;
if (templatePart != null)
{
templateParts.Add(templatePart.Name, templatePart.Type);
}
}
return templateParts;
}
public static void AssertTemplatePartDefined(this IDictionary<string, Type> templateParts, string name, Type type)
{
Assert.IsNotNull(templateParts);
Assert.IsTrue(templateParts.ContainsKey(name),
"No template part named {0} was defined!", name);
Assert.AreEqual(type, templateParts[name],
"The template part {0} is of type {1}, not {2}!", name, templateParts[name].FullName, type.FullName);
}
}
e、    对UI的测试应该添加自定义SilverlightControlTest类(从SilverlightTest类中继承),这个类是用于测试UI默认值的。(可选)
其代码如下:
public abstract class SilverlightControlTest : SilverlightTest
{
public static int VisualDelayInMilliseconds = 100;
protected void CreateAsyncTask(FrameworkElement element, params Action[] actions)
{
Assert.IsNotNull(element);
actions = actions ?? new Action[] { };
bool isLoaded = false;
element.Loaded += delegate { isLoaded = true; };
TestPanel.Children.Add(element);
EnqueueConditional(() => isLoaded);
foreach (Action action in actions)
{
Action capturedAction = action;
EnqueueCallback(() => capturedAction());
EnqueueSleep(VisualDelayInMilliseconds);
}
EnqueueCallback(() => TestPanel.Children.Remove(element));
}
protected void CreateAsyncTest(FrameworkElement element, params Action[] actions)
{
CreateAsyncTask(element, actions);
EnqueueTestComplete();
}
}

三、继承关系

posted on 2010-03-03 10:08  chuncn  阅读(564)  评论(0编辑  收藏  举报

导航