添加exe项目作为测试项目的依赖

Adding an exe project as a dependency of a test project

我有集成测试 运行 在与 Process.Start 相同的解决方案中生成的可执行文件。测试项目和exe都是net core 3.0 apps.

我想在生成可执行文件(但不链接到它)的项目上向测试项目添加依赖项,我试过这样:

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

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
    <PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
    <PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\TestExe\TestExe.csproj">
      <ReferenceOutputAssembly>false</ReferenceOutputAssembly>
    </ProjectReference>
  </ItemGroup>

</Project>

但是当我在测试中 运行 可执行文件时,它失败并出现以下错误:

A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in 'C:\Program Files\dotnet'

当我检查测试项目的输出目录时,我注意到它缺少 exe 依赖项输出目录中的 TestExe.runtimeconfig.json 文件。手动将此文件复制到测试项目输出目录可解决问题。

表达这种依赖关系的正确方法是什么,以便所有必需的文件最终都在测试项目输出目录中?

我通过搜索 dotnet GitHub 中的问题解决了这个问题,发现 this issue 提供了解决方法。

将以下内容添加到生成您要引用的可执行文件的 .csproj 中:

  <Target Name="AddRuntimeDependenciesToContent" Condition=" '$(TargetFrameworkIdentifier)' == '.NETCoreApp'" BeforeTargets="GetCopyToOutputDirectoryItems" DependsOnTargets="GenerateBuildDependencyFile;GenerateBuildRuntimeConfigurationFiles">
    <ItemGroup>
      <ContentWithTargetPath Include="$(ProjectDepsFilePath)" CopyToOutputDirectory="PreserveNewest" TargetPath="$(ProjectDepsFileName)" />
      <ContentWithTargetPath Include="$(ProjectRuntimeConfigFilePath)" CopyToOutputDirectory="PreserveNewest" TargetPath="$(ProjectRuntimeConfigFileName)" />
    </ItemGroup>
  </Target>

然后确保您引用的项目没有将 ReferenceOutputAssembly 属性 设置为 false:

<ProjectReference Include="..\TestExe\TestExe.csproj"/>