Skip to content

Allow passing environment variables to the test process from the InvokeTestingPlatform target #10342

Closed

Description

Summary

InvokeTestingPlatformTask derives from ToolTask, so it already inherits a fully functional EnvironmentVariables parameter. However, the InvokeTestingPlatform target never plumbs it through, so there is no supported way to set environment variables for the test process from MSBuild.

I'd like to propose exposing it via a TestingPlatformEnvironmentVariables property.

Why this matters: repo-local .NET SDKs

This is not hypothetical — it silently changes which runtime your tests execute on.

Many repos (all of the .NET product repos, and anything Arcade-based) install a private SDK into a repo-local folder such as .dotnet/ and build against it, without exporting DOTNET_ROOT for the whole build session. That works for the build because everything goes through the dotnet muxer that was invoked by path.

It does not work for the test run. Test projects using xunit.v3 must build an app host (xunit.v3.core.mtp-v2.props forces UseAppHost=true, and its targets hard-error otherwise), and MTP launches that .exe directly rather than via the muxer. An app host ignores PATH — it resolves a runtime through DOTNET_ROOT, then falls back to the machine-wide install.

The consequences:

  • On a machine with a different .NET installed, tests silently run on the wrong runtime. In our repo the local SDK is 11.0.0-preview.6 while the machine has 11.0.0-preview.7 installed, and the tests ran on preview.7 without any warning — verified via TESTINGPLATFORM_DIAGNOSTIC:
    no DOTNET_ROOT   -> Runtime information: win-x64 - .NET 11.0.0-preview.7.26377.110   # machine-wide
    with DOTNET_ROOT -> Runtime information: win-x64 - .NET 11.0.0-preview.6.26359.118   # repo-local
    
  • On a clean CI machine with no .NET installed at all, the app host finds no runtime and the test run fails outright.

For reference, this is exactly why Arcade's own xunit runner target sets it explicitly when it invokes the runner (XUnitV3.Runner.targets):

EnvironmentVariables="DOTNET_ROOT=$(TestDotNetRoot);DOTNET_ROOT_X86=$(TestDotNetRoot)x86"

Repos that use MTP's own Test/InvokeTestingPlatform target instead of Arcade's runner lose that, and there is currently no supported replacement.

DotnetHostPath does not help here: it only selects the muxer used when there is no app host. With UseAppHost=true it is ignored (verified), and xunit.v3 does not allow turning the app host off.

Proposed fix

The task side already works — nothing to change there. Only the target needs a passthrough:

   <PropertyGroup>
     <TestingPlatformShowTestsFailure Condition=" '$(TestingPlatformShowTestsFailure)' == '' ">false</TestingPlatformShowTestsFailure>
     <TestingPlatformCaptureOutput Condition=" '$(TestingPlatformCaptureOutput)' == '' " >true</TestingPlatformCaptureOutput>
   </PropertyGroup>

   <Target Name="InvokeTestingPlatform" >
     <CallTarget Targets="_TestRunStart" />
     <InvokeTestingPlatformTask TargetPath="$(TargetPath)"
                                ...
                                TestingPlatformCaptureOutput="$(TestingPlatformCaptureOutput)"
+                               EnvironmentVariables="$(TestingPlatformEnvironmentVariables)"
                                DotnetHostPath="$(DOTNET_HOST_PATH)" />
   </Target>

Consumers could then write:

<PropertyGroup>
  <TestingPlatformEnvironmentVariables>DOTNET_ROOT=$(DotNetRoot)</TestingPlatformEnvironmentVariables>
</PropertyGroup>

ToolTask.EnvironmentVariables is string[], so an MSBuild property containing A=1;B=2 binds naturally, and an item-based @(TestingPlatformEnvironmentVariable) form would work equally well if that fits the existing conventions better. Since the parameter is unset by default, the change is fully backwards compatible (ToolTask keeps inheriting the parent process environment).

I'm happy to send a PR if you're on board with the shape.

Verification

I confirmed the task side already works end-to-end by calling it directly with the inherited parameter:

<InvokeTestingPlatformTask TargetPath="$(TargetPath)"
                           ... 
                           EnvironmentVariables="DOTNET_ROOT=$(DotNetRoot.TrimEnd('\/'))" />

MSBuild accepted the parameter (no MSB4064) and the test host switched from the machine-wide runtime to the repo-local one. So this really is only about the target not exposing it.

Current workaround

For anyone hitting this before it's fixed: ToolTask passes the MSBuild process environment on to the child, so the variable can be set on the MSBuild process itself. System.Environment::SetEnvironmentVariable is blocked as an MSBuild property function (MSB4185), so it needs a small inline task:

<UsingTask TaskName="SetEnvironmentVariable"
           TaskFactory="RoslynCodeTaskFactory"
           AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
  <ParameterGroup>
    <Name ParameterType="System.String" Required="true" />
    <Value ParameterType="System.String" Required="true" />
  </ParameterGroup>
  <Task>
    <Code Type="Fragment" Language="cs">System.Environment.SetEnvironmentVariable(Name, Value);</Code>
  </Task>
</UsingTask>

<Target Name="SetDotNetRootForTestRun" BeforeTargets="InvokeTestingPlatform">
  <SetEnvironmentVariable Name="DOTNET_ROOT" Value="$(DotNetRoot.TrimEnd('\/'))" />
</Target>

That works, but it reaches around the public surface of the targets and is the kind of thing that ideally shouldn't be necessary.

Environment

  • Microsoft.Testing.Platform / Microsoft.Testing.Platform.MSBuild 2.2.3 (behaviour is the same on main)
  • xunit.v3 4.0.0-pre.81 (MTP v2 runner)
  • .NET SDK 11.0.100-preview.6, Windows x64

Activity

  1. Youssef1313 commented on Jul 30, 2026

    @Youssef1313
    Member

    This task is rarely used. I'm curious how you're running the tests?

  2. Youssef1313 commented on Jul 30, 2026

    @Youssef1313
    Member

    You linked XUnitV3.Runner.targets from Arcade, but the Exec call there should be done using the apphost. So there should be no interaction with InvokeTestingPlatform target in this scenario at all?

  3. ViktorHofer commented on Jul 30, 2026

    @ViktorHofer
    MemberAuthor

    See dotnet/dotnet#8060. Is there a better way to use xunit + MTP? I'm explicitly not using the Arcade Test infrastructure. Both my local tests (using dotnet test or invoking the /t:Test target) invoked that target.

  4. Youssef1313 commented on Jul 30, 2026

    @Youssef1313
    Member

    dotnet test for MTP isn't supposed to use this target. The target is only called by the VSTest-based dotnet test (which predates the MTP-based dotnet test).
    Did you opt-in to the MTP-based dotnet test via global.json? This one doesn't rely on this target at all.

  5. Youssef1313 commented on Jul 30, 2026

    @Youssef1313
    Member

    Also note that running MTP using the VSTest-based dotnet test is no longer supported in MTP v2.

  6. Youssef1313 commented on Jul 30, 2026

    @Youssef1313
    Member

    Looking at that PR, if you run dotnet test from a working directory which is under src, the empty global.json will be picked, and it will default to using the VSTest-based dotnet test.

  7. ViktorHofer commented on Jul 30, 2026

    @ViktorHofer
    MemberAuthor

    The empty global.json under src is intentional. We don't enable MTP anywhere there. That's the business of the individual inner repo. Copilot is telling me the following about one of your statements:

    We are not using VSTest — confirmed.

    ┌────────────────────────────────────────────┬───────────────────────┬───────────────┐
    │ Path │ InvokeTestingPlatform │ VSTest target │
    ├────────────────────────────────────────────┼───────────────────────┼───────────────┤
    │ dotnet msbuild -t:Test (= build.cmd -test) │ runs │ never runs │
    ├────────────────────────────────────────────┼───────────────────────┼───────────────┤
    │ dotnet test (MTP via global.json) │ doesn't run │ never runs │
    └────────────────────────────────────────────┴───────────────────────┴───────────────┘

    The reviewer's first point is incomplete.  InvokeTestingPlatform  isn't only called by the VSTest-based  dotnet test  — it's also called by MTP's own  Test  target in  Microsoft.Testing.Platform.MSBuild.CustomTestTarget.targets :

    That's our primary CI path ( build.cmd -test ), and no VSTest target is involved. So the env-var request is still valid — but it should be re-scoped to the MSBuild path, since I've now confirmed  dotnet test  doesn't need it: without my workaround it already resolves the repo-local preview.6 runtime correctly. The gap is specific to  InvokeTestingPlatformTask .

    So the InvokeTestingPlatform target is still invoked when you invoke the /t:Test target, without any VSTest in the play BUT you were right that in the dotnet test example it doesn't get invoked. Sorry for my confusion there.

  8. Youssef1313 commented on Jul 30, 2026

    @Youssef1313
    Member

    Yup, /t:Test still uses InvokeTestingPlatform target. That was the only reason we couldn't delete the target altogether actually.

    But then this doesn't affect XUnitV3.Runner.targets right?

    It should be fine to introduce a new TestingPlatformEnvironmentVariables, I think. I just wanted to make sure the exact scenario and use case is well understood.

  9. ViktorHofer commented on Jul 30, 2026

    @ViktorHofer
    MemberAuthor

    But then this doesn't affect XUnitV3.Runner.targets right?

    We don't use Arcade's testing infrastructure. It's completely disabled. With MTP there is virtually no reason to still rely on it. It's more harmful than beneficial.

    Yup, /t:Test still uses InvokeTestingPlatform target. That was the only reason we couldn't delete the target altogether actually.

    OK. Keep supporting an MSBuild entry point is very important IMO. Most of the time customers are already inside an msbuild environment when they want to execute tests.

    It should be fine to introduce a new TestingPlatformEnvironmentVariables, I think

    OK will send a PR, the addition is really much just a one-liner.

    Are there any behavioral differences between the MSBuild and the dotnet test entrypoints?

  10. Youssef1313 commented on Jul 30, 2026

    @Youssef1313
    Member

    Are there any behavioral differences between the MSBuild and the dotnet test entrypoints?

    The user experience is different (what we print, etc). Some options are considered "global" options when using dotnet test on a solution (because the command knows about the whole solution) and that can't be achieved with /t:Test which runs on each project in isolation, etc. Nothing should hopefully be "surprising" though 😄

    OK will send a PR, the addition is really much just a one-liner.

    Sounds good to me if Amaury Levé (@Evangelink) doesn't have additional concerns :)

  11. Evangelink commented on Jul 30, 2026

    @Evangelink
    Member

    Thanks for the very thorough write-up Viktor Hofer (@ViktorHofer), and for pushing through the back-and-forth on the entry points. I'm on board with the passthrough. Two things on top of the diff, one small and one that I think is actually the more interesting half of this issue.

    1. On the exact shape of the diff

    ToolTask.EnvironmentVariables is string[], so binding $(TestingPlatformEnvironmentVariables) means MSBuild splits the property on ;. That's fine for DOTNET_ROOT=..., but it silently corrupts any value that contains a semicolon:

    <TestingPlatformEnvironmentVariables>MY_PATHS=/a;/b</TestingPlatformEnvironmentVariables>

    binds as ["MY_PATHS=/a", "/b"], and the second entry is malformed. It's escapable (/a%3B/b), but that's an obscure footgun to bake into a brand-new public property.

    You already floated the item form in the issue, and I'd lean that way as the primary surface:

    <ItemGroup>
      <TestingPlatformEnvironmentVariable Include="DOTNET_ROOT" Value="$(DotNetRoot)" />
    </ItemGroup>

    Item metadata isn't subject to the ; split, so values are safe as authored. Implementation-wise this stays cheap — take an ITaskItem[] parameter and project it into the inherited EnvironmentVariables at the top of Execute() before base.Execute() runs. (Worth noting ToolTask.EnvironmentOverride is not the right hook here — it's [Obsolete] precisely because a Dictionary can't be set from a project file.)

    Happy to also keep TestingPlatformEnvironmentVariables as sugar for the simple NAME=VALUE case if you'd rather have both; I just wouldn't make the string[] property the only way in.

    2. The DOTNET_ROOT half probably shouldn't need configuration at all

    Re-reading your repro, I think the escape hatch and the bug you hit are two separate things, and we're at risk of shipping only the former.

    The reason dotnet test resolved your repo-local preview.6 and /t:Test didn't isn't that one of them reads a property you haven't set. It's that the SDK explicitly sets DOTNET_ROOT_<ARCH> for you before launching the apphost and we don't. See TestApplication.CreateProcessStartInfo in dotnet/sdk:

    if (Module.DotnetRootArchVariableName is not null)
    {
        processStartInfo.Environment[Module.DotnetRootArchVariableName] = Path.GetDirectoryName(new Muxer().MuxerPath);
    }

    with EnvironmentVariableNames.TryGetDotNetRootArchVariableName returning null when the target architecture differs from the SDK's, so it only fires when it's safe to.

    InvokeTestingPlatformTask has everything needed to do the same. On the apphost path, TryGetRunCommand() returns the .exe and GenerateFullPathToTool returns early — so DotnetHostPath is never consulted at all, which is exactly the "DotnetHostPath does not help here" behaviour you observed. We already have $(DOTNET_HOST_PATH) flowing into the task and an IsCurrentProcessArchitectureCompatible() check that mirrors the SDK's arch guard.

    There's precedent one layer further down too: MSBuild does this for its own apphost-launched child processes in DotnetHostEnvironmentHelper.CreateDotnetRootEnvironmentOverrides, deriving DOTNET_ROOT from DOTNET_HOST_PATH and nulling out the arch-specific variants, since those take precedence over plain DOTNET_ROOT. Notably it also has ClearBootstrapDotnetRootEnvironment, whose comment says the bootstrap value "should not leak to tools those processes execute" — i.e. we can't count on inheriting a usable DOTNET_ROOT from the MSBuild process even when MSBuild itself had one.

    If we do this, your original scenario works with no configuration on a clean CI machine, and the "same repo, two entry points, different runtime" divergence goes away. The env-var passthrough then stops being the fix for a runtime-resolution bug and becomes what it should be: a general escape hatch for everything else. It's a behaviour change, so it'd want an opt-out property and a note in the changelog.

    FWIW this repo works around the same gap today — we pin DOTNET_ROOT in eng/pipelines/variables/test-env-vars.yml, and the /t:Test acceptance test sets it by hand.

    3. > Are there any behavioral differences between the MSBuild and the dotnet test entrypoints?

    Yes, and this is one of them. Off the top of my head, /t:Test → InvokeTestingPlatform:

    • runs one ToolTask per project/TFM, coordinating over a named pipe, with results written per-TFM under TestResults; there's no cross-project aggregation or summary
    • takes extra args via $(TestingPlatformCommandLineArguments), not CLI parsing
    • doesn't read launchSettings.json, and has no equivalent of --environment
    • doesn't set DOTNET_ROOT* (this issue)
    • dispatches multi-TFM via DispatchToInnerBuildsWithMTPTestTarget, gated on $(TestTfmsInParallel)/$(BuildInParallel)

    MTP dotnet test orchestrates in the CLI instead: it aggregates across projects, owns the terminal output, honours launchSettings.json and --environment, and sets the DOTNET_ROOT arch variable as above.

    Agreed with your point that keeping an MSBuild entry point matters — most people are already inside an MSBuild environment when they want to run tests. Which is why I'd rather close the resolution gap properly than leave it as something every repo has to know to configure.

    If you're up for it, I'd suggest two PRs: the passthrough (yours, small), and the DOTNET_ROOT fix separately since it needs its own tests and an opt-out. Happy to take the second one if you'd prefer.

  12. added a commit that references this issue on Aug 3, 2026
    4fe932d
  13. ViktorHofer commented on Aug 3, 2026

    @ViktorHofer
    MemberAuthor

    Heads-up: this auto-closed as "completed" when #10405 merged (my commit said Fixes #10342), but only the first half shipped — the TestingPlatformEnvironmentVariable passthrough.

    Amaury Levé (@Evangelink)'s second point, having the task set DOTNET_ROOT_<ARCH> for the apphost itself so the common case needs no configuration, is still open. I've split it out into #10408 so it isn't lost, with your analysis carried over. Leaving it unassigned since you offered to take it in this comment — happy either way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions