c# - WPF 应用程序的单元测试失败,出现 NotSupportedException "The Uri prefix is not recognized"

标签 c# wpf unit-testing nunit

我目前正在编写单元测试,在这个位置,测试失败并出现 NotSupportedException“无法识别 URI 前缀”经过小型研究后,我已经注册了“打包”Uri 方案,但它没有帮助。

return _WaitImageThumbnail ?? (_WaitImageThumbnail = new BitmapImage(new Uri("pack://application:,,,/MyAssemblyName;component/images/DefaultThumbnailLoading.png")));

堆栈跟踪:

   at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
   at System.Net.WebRequest.Create(Uri requestUri)
   at MS.Internal.WpfWebRequestHelper.CreateRequest(Uri uri)
   at System.IO.Packaging.PackWebRequest.GetRequest(Boolean allowPseudoRequest)
   at System.IO.Packaging.PackWebRequest.GetResponse()
   at MS.Internal.WpfWebRequestHelper.GetResponse(WebRequest request)
   at MS.Internal.WpfWebRequestHelper.CreateRequestAndGetResponse(Uri uri)
   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, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy, Boolean insertInDecoderCache)
   at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation()
   at System.Windows.Media.Imaging.BitmapImage.EndInit()
   at System.Windows.Media.Imaging.BitmapImage..ctor(Uri uriSource, RequestCachePolicy uriCachePolicy)
   at System.Windows.Media.Imaging.BitmapImage..ctor(Uri uriSource)
   ...

问题: 如何加载图像,以及为什么会出现此异常?

最佳答案

要为单元测试加载图像,您需要做一些事情。

注册 Pack Uri 或初始化 WPF Application 实例

您可以按照前面的 SO 问题 Pack Urls and Unit Testing 注册包 URI或初始化一个 WPF 应用程序,它将为您注册 WPF 框架组件。我通常在程序集初始化阶段执行此操作。

   [AssemblyInitialize]
   public static void InitializeTestAssembly(TestContext ctx)
   {
       if (Application.Current == null)
           new Application();
   }

将图像作为资源或设置作为部署项嵌入

为了使用上面概述的包 uri,必须将图像设置为资源,以便将其烘焙到您的程序集中。如果您不作为资源使用,请将其更改为复制到输出目录的内容,然后配置测试环境以使用测试部署图像:

 [DeploymentItem("/images/DefaultThumbnailLoading.png")]
 [TestMethod]
 public void WhenPerformingLongOperation_ShouldDisbleProgressIndicator()
 {
    // test here
 }

关于c# - WPF 应用程序的单元测试失败,出现 NotSupportedException "The Uri prefix is not recognized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14216297/

相关文章:

c# - 使用不在域上的 DirectoryEntry,设置用户密码永不过期

java - 相当于 Ruby factory_girl 或 Python factory_boy 的 Scala 或 Java(用于单元测试的便捷工厂模式)

c# - 无法确定类型之间关联的主体端

c# - 如果命令被禁用,如何更改上下文菜单项的样式

wpf - 通过 XAML 向 DataGrid 添加行

wpf - XAML 中的字符串插值

java - 使用 Mockito 模拟另一个类中的类方法

python - Django DB 记录在第一次测试用例运行后消失

c# - 为什么 sp_executesql 不返回结果而直接 SP 调用返回结果?

c# - 实现 HSTS 时出现 SSL 错误