You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#测试时排除编译文件:属性传递失败后的解决方法

如何在运行测试时排除主项目中的指定编译文件?

我需要在运行测试时让主项目projectMain.csproj排除部分编译文件,但这些文件在其他非测试场景下必须正常参与编译。

最初的失败尝试

原本计划通过测试项目传递属性给主项目,实现条件排除:

测试项目projectTest.csproj配置

...
<ItemGroup>
    <ProjectReference Include="path_to_main_project.csproj">
        <IsRunningTests>true</IsRunningTests>
    </ProjectReference>
</ItemGroup>
...

主项目projectMain.csproj配置

...
<ItemGroup Condition="'$(IsRunningTests)' == 'true'">
    <Compile Remove="*ExcludeMe.cs" />
</ItemGroup>
...

这种配置并未生效,虽然直接在主项目的<PropertyGroup>中设置<IsRunningTests>true</IsRunningTests>能达到排除文件的效果,但这不符合我希望仅在测试时触发的需求。

最终解决方法

后来意识到最初的思路有误,通过给主项目添加自定义运行配置解决了问题:

<PropertyGroup Condition="'$(Configuration)' == 'DebugWithTests'">
    <DefineConstants>DEBUG;TEST_BUILD</DefineConstants>
    <IsRunningTests>true</IsRunningTests>
</PropertyGroup>
...

之后只要使用DebugWithTests配置运行测试,主项目就会自动排除指定文件,且不需要修改测试项目的配置。

内容的提问来源于stack exchange,提问作者Vacrin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 09:43:24