天天看點

Silverlight實用竅門系列:44.Silverlight 4.0中進行單元測試 【附帶源碼執行個體】

        在Silvelight 4.0的項目中我們也需要制作單元測試以保證項目的品質,本節将講訴如何建立一個項目進行單元測試。

        一、建立一個名為SL4UnitAPP的Silverlight 應用程式,不需要Web承載網站。

<a target="_blank" href="http://blog.51cto.com/attachment/201204/225516220.jpg"></a>

        二、然後滑鼠右鍵點選SL4UnitAPP解決方案,添加一個名為SL4UnitTest的Silverlight Unit Test Application。

        三、在平時VS2010 建立項目時無法添加一個Silverlight Unit Test Application,是以我們需要将C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\下的ItemTemplates檔案夾和ProjectTemplates檔案夾都拷貝到D:\My Documents\Visual Studio 2010\Templates目錄下的ItemTemplates檔案夾和ProjectTemplates檔案夾。

<a target="_blank" href="http://blog.51cto.com/attachment/201204/225343215.jpg"></a>

             四、此時我們可以在VS2010建立一個Silverlight Unit Test Application應用程式如下圖所示:

<a target="_blank" href="http://blog.51cto.com/attachment/201204/225343126.jpg"></a>

             五、在SL4UnitTest應用程式中添加引用SL4UnitApp項目。如下圖所示:

<a target="_blank" href="http://blog.51cto.com/attachment/201204/225343178.jpg"></a>

             七、在SL4UnitApp項目的MainPage.xaml.cs中添加兩個需要驗證的函數和一個公共變量如下代碼所示:

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Net; 

using System.Windows; 

using System.Windows.Controls; 

using System.Windows.Documents; 

using System.Windows.Input; 

using System.Windows.Media; 

using System.Windows.Media.Animation; 

using System.Windows.Shapes; 

namespace SL4UnitAPP 

public partial class MainPage : UserControl 

public MainPage() 

InitializeComponent(); 

/// &lt;summary&gt; 

/// 傳回一個字元mainPage 

/// &lt;/summary&gt; 

/// &lt;returns&gt;&lt;/returns&gt; 

public string ReturnString() 

return "mainPage"; 

public string GetStringFromMethod; 

/// 設定公共變量值為SecMethod 

public void GetString() 

GetStringFromMethod = "SecMethod"; 

             八、在SL4UnitTest項目中我們對MainPage類進行執行個體化,然後我們添加兩個特性為[TestMethod]的變量以供測試是否通過單元測 試(注意:如果因為斷言錯誤,而進入調試模式,可以按F5繼續運作,以看單元測試結果),代碼如下:

using System.Windows.Ink; 

using Microsoft.Silverlight.Testing; 

using Microsoft.VisualStudio.TestTools.UnitTesting; 

using SL4UnitAPP; 

namespace SL4UnitTest 

[TestClass] 

public class Tests 

MainPage mpage = new MainPage(); 

[TestMethod] 

public void TestMethod1() 

//斷言mpage.ReturnString()獲得的結果是mainPage 

Assert.AreEqual(mpage.ReturnString(), "mainPage"); 

public void TestMethod2() 

//先運作mpage.GetString()函數,然後斷言GetStringFromMethod值為SecMethod 

mpage.GetString(); 

Assert.AreEqual(mpage.GetStringFromMethod, "SecMethod1"); 

             九、本執行個體中第一個方法是正确的斷言,第二個方法很明顯是錯誤的斷言,是以按下F5看到的結果如下面兩張圖所示:

本文轉自程興亮 51CTO部落格,原文連結:http://blog.51cto.com/chengxingliang/826460

繼續閱讀