程序不包含适合 .Net MAUI Xunit 中入口点的静态“Main”方法

Dev*_*sad 4 xunit maui

在 .NET MAUI 中运行 Xunit 项目时出现“程序不包含适合入口点的静态‘主’方法”错误

public class UnitTest1
{
  [Fact]
  public void Test1()
  {
  }
}
Run Code Online (Sandbox Code Playgroud)

重现:

  1. 创建一个 MAUI 应用程序并将新项目 XUnit 添加到解决方案中。
  2. 将 MAUI 项目引用到 XUnit 项目。
  3. 运行测试用例然后得到上述异常。

使用 Visual Studio 17.3 预览版 2.0

Ger*_*uis 8

您需要进行一些修改才能使 xUnit 工作。我这里有一个示例存储库:https ://github.com/jfversluis/MauiUnitTestSample

所有修改都在csproj两个项目的文件中,并标有以 开头的注释xUnit

  1. 添加net6.0为 .NET MAUI 项目中的目标。
<!-- xUnit: Add net6.0; here -->
<TargetFrameworks>net6.0;net6.0-android;net6.0-ios;net6.0-maccatalyst</TargetFrameworks>
Run Code Online (Sandbox Code Playgroud)
  1. 使OutputType.NET MAUI 项目的 排除net6.0目标
<!-- xUnit: The condition here only excludes this for the unit test project -->
<OutputType Condition="'$(TargetFramework)' != 'net6.0'">Exe</OutputType>
Run Code Online (Sandbox Code Playgroud)
  1. UseMaui如果您需要引用 .NET MAUI API,请在您的 xUnit 项目中添加
<!-- xUnit: Add UseMaui if you need access to .NET MAUI APIs-->
<UseMaui>true</UseMaui>
Run Code Online (Sandbox Code Playgroud)

您现在应该能够添加并运行单元测试!