WPF单元测试的创建需要有一定编程经验的开发人员,才能熟练的操作。那么,在这篇文章中我们将针对WPF单元测试的创建过程做一个简单的介绍。 #t#
桦南ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!
1,对普通类(非WPF UI组件)进行测试:
这和在.Net2.0中使用NUnit进行测试时一样,不会出现任何问题,参考下面的代码:
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://www.mswzjz.com/qtweb/news14/180914.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联