WPF应用程序的单元测试失败,出现NotSupportedException“无法识别Uri前缀”

时间:2013-01-08 13:45:11

标签: c# wpf unit-testing nunit

我目前正在编写单元测试,并且在此位置测试失败并出现NotSupportedException“无法识别URI前缀”经过小规模研究后我已经注册了“pack”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)
   ...

问题: 如何加载图像,以及发生此异常的原因?

1 个答案:

答案 0 :(得分:5)

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

注册Pack Uri或初始化WPF应用程序实例

您可以根据之前的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
 }