新聞中心
這里有您想知道的互聯網營銷解決方案
WPF單元測試方法總結
WPF單元測試的創(chuàng)建需要有一定編程經驗的開發(fā)人員,才能熟練的操作。那么,在這篇文章中我們將針對WPF單元測試的創(chuàng)建過程做一個簡單的介紹。 #t#

樺南ssl適用于網站、小程序/APP、API接口等需要進行數據傳輸應用場景,ssl證書未來市場廣闊!成為成都創(chuàng)新互聯的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯系或者加微信:13518219792(備注:SSL證書合作)期待與您的合作!
1,對普通類(非WPF UI組件)進行測試:
這和在.Net2.0中使用NUnit進行測試時一樣,不會出現任何問題,參考下面的代碼:
- [TestFixture]
- public class ClassTest {
- [Test] public void TestRun() {
- ClassLibrary1.Class1 obj =
new ClassLibrary1.Class1(); - double expected = 9;
- double result = obj.GetSomeValue(3);
- Assert.AreEqual(expected, result);
- }
- }
2,對WPF UI組件進行測試
使用NUnit對WPF UI組件(比如MyWindow,MyUserControl)進行測試的時候,NUnit會報如下異常:“The calling thread must be STA, because many UI components require this”。
下面是錯誤的WPF單元測試代碼:
- [TestFixture]
- public class ClassTest {
- [Test] public void TestRun()
{ WindowsApplication1.Window1 obj =
new WindowsApplication1.Window1();- double expected = 9;
- double result = obj.GetSomeValue(3);
- Assert.AreEqual(expected, result);
- }
- }
為了讓調用線程為STA,我們可以編寫一個輔助類CrossThreadTestRunner:
- using System; using System.
Collections.Generic;- using System.Text;
- using System.Threading;
- using System.Security.Permissions;
- using System.Reflection;
- namespace TestUnit {
- public class CrossThreadTestRunner {
- private Exception lastException;
- public void RunInMTA(ThreadStart
userDelegate) {- Run(userDelegate, ApartmentState.MTA);
- }
- public void RunInSTA(ThreadStart
userDelegate) {- Run(userDelegate, ApartmentState.STA);
- }
- private void Run(ThreadStart
userDelegate,
ApartmentState apartmentState) {- lastException = null;
- Thread thread = new Thread( delegate() {
- try { userDelegate.Invoke();
- }
- catch (Exception e) { lastException = e;
- }
- });
- thread.SetApartmentState(apartmentState);
- thread.Start();
- thread.Join();
- if (ExceptionWasThrown())
- ThrowExceptionPreservingStack
(lastException);- }
- private bool ExceptionWasThrown() {
- return lastException != null;
- }
- [ReflectionPermission(Security
Action.Demand)]- private static void ThrowException
PreservingStack(Exception exception) {- FieldInfo remoteStackTraceString =
typeof(Exception).GetField( "_remoteStack
TraceString", BindingFlags.Instance |
BindingFlags.NonPublic);- remoteStackTraceString.SetValue(exception,
exception.StackTrace + Environment.NewLine);- throw exception;
- }
- }
- }
并編寫正確的WPF單元測試代碼:
- [TestFixture] public class ClassTest {
- [Test] public void TestRun() {
- CrossThreadTestRunner runner =
new CrossThreadTestRunner();- runner.RunInSTA( delegate {
- Console.WriteLine(Thread.CurrentThread.
GetApartmentState());- WindowsApplication1.Window1 obj =
new WindowsApplication1.Window1();
double expected = 9;- double result = obj.GetSomeValue(3);
- Assert.AreEqual(expected, result);
- });
- }
- }
另外,使用NUnit時,您需要添加對nunit.framework.dll的引用,并對WPF單元測試類添加[TestFixture]屬性標記以及對測試方法添加[Test]屬性標記,然后將生成的程序集用nunit.exe打開就可以了。
本文標題:WPF單元測試方法總結
網頁鏈接:http://fisionsoft.com.cn/article/dhjpiho.html


咨詢
建站咨詢
