我目前正在编写单元测试,在这个位置,测试失败并出现 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/