Class 未注册异常:BitmapImage

Class not registered exception: BitmapImage

当我尝试创建一个 BitmapImage 实例时(在 WinUI 3 下),我得到一个异常,指出没有注册必要的 class。这是在 Visual Studio 2022 年内在基于 xUnit 的测试项目中进行的。

抛出异常的那一行很简单:

var retVal = new BitmapImage();

鉴于这条线多么简单,我想知道我的 xUnit 项目设置是否有问题。这是:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
      <TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
      <RuntimeIdentifiers>win10-x64</RuntimeIdentifiers>
    <Nullable>enable</Nullable>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="FluentAssertions" Version="6.6.0" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" />
    <PackageReference Include="xunit" Version="2.4.1" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="coverlet.collector" Version="3.1.2">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\MapLibraryWinApp\MapLibraryWinApp.csproj" />
  </ItemGroup>

</Project>

这是包含我要测试的代码的库的项目文件:

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
        <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
        <RuntimeIdentifiers>win10-x86;win10-x64;win10-arm64</RuntimeIdentifiers>
        <UseWinUI>true</UseWinUI>

        <Nullable>enable</Nullable>
        <RootNamespace>J4JSoftware.MapLibrary</RootNamespace>
        <AssemblyName>J4JSoftware.MapLibraryWinApp</AssemblyName>
        <AssemblyTitle>Map Library (Windows Apps)</AssemblyTitle>
        <Version>0.5.0</Version>
        <Copyright>Copyright © Mark A. Olbert</Copyright>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Microsoft.WindowsAppSDK" Version="1.0.3" />
        <PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22000.197" />
        <PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
    </ItemGroup>

    <ItemGroup>
      <ProjectReference Include="..\..\J4JLogging\J4JLogging\J4JLogging.csproj" />
      <ProjectReference Include="..\MapLibrary\MapLibrary.csproj" />
    </ItemGroup>
</Project>

我想也许测试项目可能需要包含<UseWinUI>标签,但添加它并没有解决问题。

您需要 运行 实际打包的 WinUI 应用程序或 deploy the Windows App SDK runtime 以及 non-MSIX-packaged 应用程序才能使用 WinUI类型。

恐怕不只是从独立测试运行ner app中引用WinUI代码那么简单。

请参阅 this 博客 post 以获取有关如何设置 运行 进行测试的实际应用程序的示例。或者避免在单元测试中创建 UI 特定内容。