c# – 如何实例化或模拟窗口编程?

前端之家收集整理的这篇文章主要介绍了c# – 如何实例化或模拟窗口编程?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对于我的一些单元测试,我必须调用需要Window作为参数的方法.不幸的是,我不能传递null,因为该方法使用窗口作为参考来更新状态栏,其中我显示实际应用程序中实际加载的内容.

所以我试图在单元测试中调用构造函数

MainWindow window = new MainWindow();

但是,这会导致MainWindow constrcutor的InitializeComponent方法中出现以下错误

System.Windows.Markup.XamlParseException occurred
  Message='Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '9' and line position '42'.
  Source=PresentationFramework
  LineNumber=9
  LinePosition=42
  StackTrace:
       at System.Windows.Markup.XamlReader.RewrapException(Exception e,IXamlLineInfo lineInfo,Uri baseUri)
  InnerException: System.IO.IOException
       Message=Assembly.GetEntryAssembly() returns null. Set the Application.ResourceAssembly property or use the pack://application:,/assemblyname;component/ Syntax to specify the assembly to load the resource from.
       Source=PresentationFramework
       StackTrace:
            at MS.Internal.AppModel.ResourceContainer.GetResourceManagerWrapper(Uri uri,String& partName,Boolean& isContentFile)
            at MS.Internal.AppModel.ResourceContainer.GetPartCore(Uri uri)
            at System.IO.Packaging.Package.GetPartHelper(Uri partUri)
            at System.IO.Packaging.Package.GetPart(Uri partUri)
            at System.IO.Packaging.PackWebResponse.CachedResponse.GetResponseStream()
            at System.IO.Packaging.PackWebResponse.GetResponseStream()
            at System.IO.Packaging.PackWebResponse.get_ContentType()
            at System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(Uri uri,Stream stream,BitmapCacheOption cacheOption,Guid& clsId,Boolean& isOriginalWritable,Stream& uriStream,UnmanagedMemoryStream& unmanagedMemoryStream,SafeFileHandle& safeFilehandle)
            at System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(Uri baseUri,Uri uri,BitmapCreateOptions createOptions,RequestCachePolicy uriCachePolicy,Boolean insertInDecoderCache)
            at System.Windows.Media.Imaging.BitmapFrame.CreateFromUriOrStream(Uri baseUri,RequestCachePolicy uriCachePolicy)
            at System.Windows.Media.ImageSourceConverter.ConvertFrom(ITypeDescriptorContext context,CultureInfo culture,Object value)
            at System.Windows.Baml2006.TypeConverterMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
            at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CallProvideValue(MarkupExtension me,IServiceProvider serviceProvider)
       InnerException:

所以我的问题是,如何在单元测试中实例化或模拟窗口?

解决方法

尝试以下:
if(Application.ResourceAssembly == null)
    Application.ResourceAssembly = typeof(MainWindow).Assembly;
var window = new MainWindow();
原文链接:https://www.f2er.com/csharp/93648.html

猜你在找的C#相关文章