使用 .runsettings 檔案設定單元測試

.runsettings 檔案可用來設定單元測試的執行方式。 例如,可用來變更執行測試的 .NET 版本、測試結果的所在目錄,或在測試回合期間所收集的資料。 .runsettings 檔案常見的用法是用來自訂程式碼涵蓋範圍分析

您可以使用回合設定檔案來設定從命令列、IDE,或使用 Azure Test Plans 或 Azure DevOps Server (先前稱為 Team Foundation Server (TFS)) 之組建工作流程中執行的測試。

回合設定檔為選擇性。 如果不想要任何特殊組態,即不需要 .runsettings 檔案。

建立回合設定檔並加以自訂

  1. 將回合設定檔新增至方案。 在 [方案總管] 中,於方案的捷徑功能表上,選擇 [新增]>[新增項目],然後選取 [XML 檔案]。 儲存檔案,其名稱是例如 test.runsettings 的格式。

    如果您沒有看到所有項目範本,請選擇 [顯示所有範本],然後選擇項目範本。

    提示

    檔案名稱並不重要,只要使用的副檔名為 .runsettings 即可。

  2. 新增範例 *.runsettings 檔案中的內容,然後依照下列各節的說明並根據您自己的需求進行自訂。

  3. 指定您想要使用下列其中一種方法的 *.runsettings 檔案:

  4. 執行單元測試以使用自訂回合設定。

如果您想要在 IDE 中開啟和關閉自訂設定,請取消選取或選取 [測試] 功能表中的檔案。

提示

您可以在方案中建立多個 .runsettings 檔案,然後視需要選取其中一個作為使用中測試設定檔。

在 IDE 中指定回合設定檔

可用方法取決於 Visual Studio 版本。

Visual Studio 2019 16.4 版和更新版本

有三種方式可以在 Visual Studio 2019 16.4 版和更新版本中指定回合設定檔。

自動偵測回合設定檔

注意

這只適用於名為 .runsettings 的檔案。

若要自動偵測回合設定檔,請將其放在解決方案的根目錄。

如果啟用自動偵測回合設定檔,此檔案中的設定會套用到所有測試回合中。 您可以使用兩種方法來開啟回合設定檔的自動偵測:

  • 選取 [工具]> [選項]> [測試]> [自動偵測回合設定檔]

    在 Visual Studio 中自動偵測 runsettings 檔案選項

  • 選取 [測試]> [設定回合設定]> [自動偵測回合設定檔]

    在 Visual Studio 中自動偵測 runsettings 檔案功能表

手動選取回合設定檔

在 IDE 中,選取 [測試]> [設定回合設定]> [選取整個解決方案的回合設定檔],然後選取 .runsettings 檔案。

  • 此檔案會覆寫解決方案根目錄的 .runsettings 檔案 (如果存在的話),而且會套用到所有測試回合。
  • 此檔案選取項目只會保存在本機。

在 Visual Studio 中選擇整體測試解決方案的 runsettings 檔案功能表

設定組建屬性

透過專案檔或 Directory.Build.props 檔案,將組建屬性新增至專案。 專案的回合設定檔是透過屬性 RunSettingsFilePath 所指定。

  • C#、VB、C++和 F# 專案中目前支援專案層級回合設定。
  • 為專案指定的檔案會覆寫解決方案中指定的任何其他回合設定檔。
  • 這些 MSBuild 屬性可用來指定回合設定檔的路徑。

為專案指定 .runsettings 檔案的範例:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <RunSettingsFilePath>$(MSBuildProjectDirectory)\example.runsettings</RunSettingsFilePath>
  </PropertyGroup>
  ...
</Project>

Visual Studio 2019 16.3 版和較早版本

若要在 IDE 中指定回合設定檔,請選取 [測試]> [選取設定檔案]。 瀏覽並選取 .runsettings 檔案。

在 Visual Studio 2019 中選取測試設定檔的功能表

檔案隨即出現在 [測試] 功能表中,且您可以選取或取消選取它。 選取時,只要選取 [分析程式碼涵蓋範圍],就會套用回合設定檔。

從命令列指定回合設定檔

若要從命令列執行測試,請使用 vstest.console.exe,然後使用 /Settings 參數來指定設定檔。

  1. 開啟 Visual Studio 的開發人員命令提示字元

  2. 輸入與下列類似的命令:

    vstest.console.exe MyTestAssembly.dll /EnableCodeCoverage /Settings:CodeCoverage.runsettings
    

    vstest.console.exe --settings:test.runsettings test.dll
    

如需詳細資訊,請參閱 VSTest.Console.exe 命令列選項

*.runsettings 檔案

*.runsettings 檔案是 XML 檔案,其中包含 RunSettings 元素內的不同組態元素。 後續各節詳細說明不同元素。 如需完整的範例,請參閱範例 *.runsettings 檔案

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <!-- configuration elements -->
</RunSettings>

每個組態元素都有預設值,因此為選擇性。

RunConfiguration 元素

<RunConfiguration>
    <MaxCpuCount>1</MaxCpuCount>
    <ResultsDirectory>.\TestResults</ResultsDirectory>
    <TargetPlatform>x86</TargetPlatform>
    <TargetFrameworkVersion>net6.0</TargetFrameworkVersion>
    <TestAdaptersPaths>%SystemDrive%\Temp\foo;%SystemDrive%\Temp\bar</TestAdaptersPaths>
    <TestCaseFilter>(TestCategory != Integration) &amp; (TestCategory != UnfinishedFeature)</TestCaseFilter>
    <TestSessionTimeout>10000</TestSessionTimeout>
    <TreatNoTestsAsError>true</TreatNoTestsAsError>
</RunConfiguration>

RunConfiguration 項目可以包括下列項目:

節點 預設
MaxCpuCount 1 選項名稱區分大小寫,而且很容易錯寫為 MaxCPUCount

此設定可控制處理序層級上的平行處理原則層級。 使用 0 以啟用最大處理序層級平行處理原則。

此設定決定可以平行執行的測試 DLL 或其他測試容器數目上限。 每個 DLL 都會在自己的測試主機處理序中執行,而且會在處理序層級上與其他測試 DLL 中的測試隔離。 此設定不會強制每個測試 DLL 中的測試平行執行。 控制 DLL 內的平行執行 (執行緒層級上) 取決於測試架構,例如 MSTest、XUnit 或 NUnit。

預設值為 1,這表示只會同時執行一個測試主機。 特殊值 0 允許與您所具備的邏輯處理器同樣數量的測試主機 (例如,6 適用於具有 6 個實體核心但沒有多執行緒的電腦,或是 12 適用於具有 6 個實體核心且具有多執行緒的電腦)。

執行中的相異 DLL 數目會決定啟動的測試主機實際數目。
ResultsDirectory 放置測試結果的目錄。 路徑相對於包含 .runsettings 檔案的目錄。
TargetFrameworkVersion net40 或 netcoreapp1.0 省略這整個自動偵測的標記。

此設定會定義用來執行測試的架構版本或架構系列。

接受的值是任何架構 Moniker,例如 net48net472net6.0net5.0netcoreapp3.1uap10.0 或任何有效的完整架構名稱,例如 .NETFramework,Version=v4.7.2.NETCoreApp,Version=v6.0.0。 針對回溯相容性,接受 Framework35Framework40Framework45FrameworkCore10FrameworkUap10,代表 (分別為 net35net40net45netcoreapp1.0uap10.0)。 所有值不區分大小寫。

所提供的值是用來判斷要使用的測試執行階段提供者。 每個測試執行階段提供者都必須遵守要使用的架構系列,但可能不會遵守確切的架構版本:

針對 .NET Framework 4.5.1 - 4.8,會使用以指定的確切版本建置的測試主機。 針對超出該範圍的值,會使用 .NET Framework 4.5.1 測試主機。

針對 .NET,測試專案的 <TargetFramework> (或更精確地 runtimeconfig.json) 會決定實際版本。

針對 UWP,測試專案應用程式本身是測試主機,並決定所使用的 UWP 實際版本。

.runsettings 檔案省略 TargetFrameworkVersion 元素,從組建二進位檔自動判斷架構版本。

自動偵測時,所有目標架構都會整合成單一通用架構。 找到相同目標架構系列的不同版本時,會選擇較新的版本 (例如,net452、net472、net48 = net48)。

針對 .NET Framework 執行器 (在 Visual Studio 中,或是開發人員命令列中的 vstest.console.exe),通用目標 Framework 會設定為 net40。 針對 .NET 執行器 (dotnet test + DLL),通用目標架構會設定為 netcoreapp1.0。
TargetPlatform x86 省略這整個自動偵測的標記。

此設定會定義用來執行測試的結構。 可能的值為:x86x64ARMARM64S390x

自動偵測時,AnyCPU DLL 的結構可能會根據執行器而有所不同。 針對 .NET Framework 執行器 (在 Visual Studio 中,或是開發人員命令列中的 vstest.console.exe),預設值是 x86。 針對 .NET 執行器 (dotnet test),預設值是目前處理序結構。

TreatTestAdapterErrorsAsWarnings false false、true
TestAdaptersPaths TestAdapters 所在目錄的一或多個路徑
TestCaseFilter 格式為<屬性><運算子><值>[|&<運算式>] 的篩選運算式。 布林運算子&應由 HTML 實體&表示。 運算式可包含在括號中。 如需運算式結構的詳細語法,請參閱 vstest/docs/filter.md
TestSessionTimeout 當測試工作階段超過指定的逾時之時,允許使用者終止測試工作階段。 設定逾時可確保資源能被充分取用,且可將測試工作階段限制在設定的時間內。 Visual Studio 2017 15.5 版和更新版本提供這項設定。
DotnetHostPath 指定用來執行測試主機之 dotnet 主機的自訂路徑。 當您建置自己的 dotnet 時,例如建置 dotnet/runtime 存放庫時,會很有用。 指定此選項會略過尋找 testhost.exe,並強制使用 testhost.dll。
TreatNoTestsAsError false true 或 false
指定布林值,這個值會在未探索任何測試時定義結束代碼。 如果值為 true 且未探索任何測試,則會傳回非零結束代碼。 否則會傳回零。

DataCollectors 元素 (診斷資料配接器)

DataCollectors 項目指定診斷資料配接器的設定。 診斷資料配接器會收集有關環境與待測應用程式的其他資訊。 每個配接器都有預設設定,如果您不想要使用預設值,您只需提供設定值即可。

<DataCollectionRunSettings>
  <DataCollectors>
    <!-- data collectors -->
  </DataCollectors>
</DataCollectionRunSettings>

CodeCoverage 資料收集器

程式碼涵蓋範圍資料收集器會建立測試中已執行過之應用程式程式碼部分的記錄。 如需自訂程式碼涵蓋範圍設定的詳細資訊,請參閱自訂程式碼涵蓋範圍分析

<DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
  <Configuration>
    <CodeCoverage>
      <ModulePaths>
        <Exclude>
          <ModulePath>.*CPPUnitTestFramework.*</ModulePath>
        </Exclude>
      </ModulePaths>

      <UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
      <AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
      <CollectFromChildProcesses>True</CollectFromChildProcesses>
      <CollectAspDotNet>False</CollectAspDotNet>
    </CodeCoverage>
  </Configuration>
</DataCollector>

VideoRecorder 資料收集器

測試執行時,視訊資料收集器會擷取螢幕錄製。 這份錄製可用於 UI 測試的疑難排解。 視訊資料收集器在 Visual Studio 2017 15.5 版和更新版本中提供。 如需設定此資料收集器的範例,請參閱範例 *.runsettings 檔案

若要自訂任何其他類型的診斷資料配接器,請使用測試設定檔

改動者資料收集器

此選項可協助您找出造成測試主機當機的問題測試。 執行收集器會在 TestResults 中建立輸出檔案 (Sequence.xml),這會擷取當機前的測試執行順序。

您可以在三種不同的模式中執行改動者:

  • 循序檔案模式:建立包含測試清單的檔案,直到停止回應
  • 損毀傾印模式:在測試主機當機時建立傾印
  • 停止傾印模式:在指定逾時之前測試未完成時建立傾印

XML 組態應該直接放在 <RunSettings> 節點:

<RunSettings>
  <RunConfiguration>
  </RunConfiguration>
  <LoggerRunSettings>
    <Loggers>
      <Logger friendlyName="blame" enabled="True" />
    </Loggers>
  </LoggerRunSettings>
  <DataCollectionRunSettings>
    <DataCollectors>
      <!-- Enables blame -->
      <DataCollector friendlyName="blame" enabled="True">
        <Configuration>
          <!-- Enables crash dump, with dump type "Full" or "Mini".
          Requires ProcDump in PATH for .NET Framework. -->
          <CollectDump DumpType="Full" />
          <!-- Enables hang dump or testhost and its child processes 
          when a test hangs for more than 10 minutes. 
          Dump type "Full", "Mini" or "None" (just kill the processes). -->
          <CollectDumpOnTestSessionHang TestTimeout="10min" HangDumpType="Full" />
        </Configuration>
      </DataCollector>
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>

TestRunParameters

<TestRunParameters>
    <Parameter name="webAppUrl" value="http://localhost" />
    <Parameter name="docsUrl" value="https://learn.microsoft.com" />
</TestRunParameters>

測試回合參數提供方法,定義可供在執行階段的測試使用的變數和值。 使用 MSTest TestContext.Properties 屬性 (或 NUnit TestCoNtext) 存取參數:

private string _appUrl;
public TestContext TestContext { get; set; }

[TestMethod] // [Test] for NUnit
public void HomePageTest()
{
    string _appUrl = TestContext.Properties["webAppUrl"];
}

若要使用測試回合參數,請將公用 TestContext 屬性新增至您的測試類別。

LoggerRunSettings 元素

LoggerRunSettings 區段會定義要用於測試回合的一或多個記錄器。 最常見的記錄器是主控台、Visual Studio 測試結果檔案 (trx) 和 html。

<LoggerRunSettings>
    <Loggers>
      <Logger friendlyName="console" enabled="True">
        <Configuration>
            <Verbosity>quiet</Verbosity>
        </Configuration>
      </Logger>
      <Logger friendlyName="trx" enabled="True">
        <Configuration>
          <LogFileName>foo.trx</LogFileName>
        </Configuration>
      </Logger>
      <Logger friendlyName="html" enabled="True">
        <Configuration>
          <LogFileName>foo.html</LogFileName>
        </Configuration>
      </Logger>
    </Loggers>
  </LoggerRunSettings>

MSTest 元素

這些是執行具有 TestMethodAttribute 屬性之測試方法的測試配接器專屬的設定。

<MSTest>
    <MapInconclusiveToFailed>True</MapInconclusiveToFailed>
    <CaptureTraceOutput>false</CaptureTraceOutput>
    <DeleteDeploymentDirectoryAfterTestRunIsComplete>False</DeleteDeploymentDirectoryAfterTestRunIsComplete>
    <DeploymentEnabled>False</DeploymentEnabled>
    <AssemblyResolution>
      <Directory path="D:\myfolder\bin\" includeSubDirectories="false"/>
    </AssemblyResolution>
</MSTest>
組態 預設
ForcedLegacyMode false 舊版 Visual Studio 中的 MSTest 配接器已進行過最佳化,因此更快速且更具延展性。 某些行為 (例如測試執行順序) 可能與舊版 Visual Studio 稍有出入。 將此值設定為 true,以使用較舊的測試配接器。

例如,如果您為單元測試指定 app.config 檔案,則可以使用此設定。

建議您考慮重構測試,以便使用較新的配接器。
SettingsFile 您可以指定與此處的 MS 測試配接器一起使用的測試設定檔。 您也可以從設定功能表指定測試設定檔。

如果您指定這個值,也必須將 [ForcedlegacyMode] 設定為 [true]

<ForcedLegacyMode>true</ForcedLegacyMode>
DeploymentEnabled true 如果您將此值設定為 false,就不會將您在測試方法中指定的部署項目複製到部署目錄中。
CaptureTraceOutput true 擷取來自 Console.Write*Trace.Write*Debug.Write* API 的文字訊息,此 API 將會與目前執行的測試相關聯。
EnableBaseClassTestMethodsFromOtherAssemblies true 一個值,指出是否要從繼承測試類別的不同組件中,啟用從基底類別探索測試方法。
ClassCleanupLifecycle EndOfClass 如果您想要在組件結尾進行類別清除,請將其設定為 EndOfAssembly。 (從 MSTest v4 開始不再支援,因為 EndOfClass 是預設且唯一的 ClassCleanup 行為)
MapNotRunnableToFailed true 一個值,指出無法執行的結果是否對應至失敗的測試。
平行處理 用來設定平行處理設定:

背景工作角色:要用於平行處理的執行緒/背景工作角色數目,預設為目前電腦上的處理器數目

範圍:平行處理的範圍。 您可以將其設定為 MethodLevel。 根據預設,它是 ClassLevel

<Parallelize><Workers>32</Workers><Scope>MethodLevel</Scope></Parallelize>
TestTimeout 0 取得指定的全域測試案例逾時。
TreatDiscoveryWarningsAsErrors false 若要將測試探索警告報告為錯誤,請將此值設定為 [true]
TreatClassAndAssemblyCleanupWarningsAsErrors false 若要將類別清除中的失敗視為錯誤,請將此值設定為 true
DeployTestSourceDependencies true 一個值,指出是否要部署測試來源參考。
DeleteDeploymentDirectoryAfterTestRunIsComplete true 若要在測試回合之後保留部署目錄,請將此值設定為 false
MapInconclusiveToFailed false 如果測試完成,但狀態結果不明,則通常對應至 [測試總管] 中的已略過狀態。 如果您要讓結果不明的測試顯示為 [失敗],請將此值設定為 true
AssemblyResolution false 您可以在求解及執行單元測試時,指定額外組件的路徑。 例如,您可以針對與測試組件位於不同目錄的相依性組件,使用這些路徑。 若要指定路徑,請使用目錄路徑項目。 路徑可以包括環境變數。

<AssemblyResolution> <Directory path="D:\myfolder\bin\" includeSubDirectories="false"/> </AssemblyResolution>

請注意,這項功能只會在使用 .NET Framework 目標時套用。

.runsettings 檔案範例

下列 XML 顯示一般 .runsettings 檔案的內容。 複製此程式碼,並根據需求編輯。

檔案的每個項目都有預設值,因此為選擇性。

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <!-- Configurations that affect the Test Framework -->
  <RunConfiguration>
    <!-- Use 0 for maximum process-level parallelization. This does not force parallelization within the test DLL (on the thread-level). You can also change it from the Test menu; choose "Run tests in parallel". Unchecked = 1 (only 1), checked = 0 (max). -->
    <MaxCpuCount>1</MaxCpuCount>
    <!-- Path relative to directory that contains .runsettings file-->
    <ResultsDirectory>.\TestResults</ResultsDirectory>

    <!-- Omit the whole tag for auto-detection. -->
    <!-- [x86] or x64, ARM, ARM64, s390x  -->
    <!-- You can also change it from the Test menu; choose "Processor Architecture for AnyCPU Projects" -->
    <TargetPlatform>x86</TargetPlatform>

    <!-- Any TargetFramework moniker or omit the whole tag for auto-detection. -->
    <!-- net48, [net40], net6.0, net5.0, netcoreapp3.1, uap10.0 etc. -->
    <TargetFrameworkVersion>net40</TargetFrameworkVersion>

    <!-- Path to Test Adapters -->
    <TestAdaptersPaths>%SystemDrive%\Temp\foo;%SystemDrive%\Temp\bar</TestAdaptersPaths>

    <!-- TestCaseFilter expression -->
    <TestCaseFilter>(TestCategory != Integration) &amp; (TestCategory != UnfinishedFeature)</TestCaseFilter>

    <!-- TestSessionTimeout was introduced in Visual Studio 2017 version 15.5 -->
    <!-- Specify timeout in milliseconds. A valid value should be greater than 0 -->
    <TestSessionTimeout>10000</TestSessionTimeout>

    <!-- true or false -->
    <!-- Value that specifies the exit code when no tests are discovered -->
    <TreatNoTestsAsError>true</TreatNoTestsAsError>
  </RunConfiguration>

  <!-- Configurations for data collectors -->
  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
        <Configuration>
          <CodeCoverage>
            <ModulePaths>
              <Exclude>
                <ModulePath>.*CPPUnitTestFramework.*</ModulePath>
              </Exclude>
            </ModulePaths>

            <!-- We recommend you do not change the following values: -->
            <UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
            <AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
            <CollectFromChildProcesses>True</CollectFromChildProcesses>
            <CollectAspDotNet>False</CollectAspDotNet>

          </CodeCoverage>
        </Configuration>
      </DataCollector>

      <DataCollector uri="datacollector://microsoft/VideoRecorder/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TestTools.DataCollection.VideoRecorder.VideoRecorderDataCollector, Microsoft.VisualStudio.TestTools.DataCollection.VideoRecorder, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="Screen and Voice Recorder">
        <!--Video data collector was introduced in Visual Studio 2017 version 15.5 -->
        <Configuration>
          <!-- Set "sendRecordedMediaForPassedTestCase" to "false" to add video attachments to failed tests only -->
          <MediaRecorder sendRecordedMediaForPassedTestCase="true"  xmlns="">           ​
            <ScreenCaptureVideo bitRate="512" frameRate="2" quality="20" />​
          </MediaRecorder>​
        </Configuration>
      </DataCollector>

      <!-- Configuration for blame data collector -->
      <DataCollector friendlyName="blame" enabled="True">
      </DataCollector>

    </DataCollectors>
  </DataCollectionRunSettings>

  <!-- Parameters used by tests at run time -->
  <TestRunParameters>
    <Parameter name="webAppUrl" value="http://localhost" />
    <Parameter name="webAppUserName" value="Admin" />
    <Parameter name="webAppPassword" value="Password" />
  </TestRunParameters>

  <!-- Configuration for loggers -->
  <LoggerRunSettings>
    <Loggers>
      <Logger friendlyName="console" enabled="True">
        <Configuration>
            <Verbosity>quiet</Verbosity>
        </Configuration>
      </Logger>
      <Logger friendlyName="trx" enabled="True">
        <Configuration>
          <LogFileName>foo.trx</LogFileName>
        </Configuration>
      </Logger>
      <Logger friendlyName="html" enabled="True">
        <Configuration>
          <LogFileName>foo.html</LogFileName>
        </Configuration>
      </Logger>
      <Logger friendlyName="blame" enabled="True" />
    </Loggers>
  </LoggerRunSettings>

  <!-- Adapter Specific sections -->

  <!-- MSTest adapter -->
  <MSTest>
    <MapInconclusiveToFailed>True</MapInconclusiveToFailed>
    <CaptureTraceOutput>false</CaptureTraceOutput>
    <DeleteDeploymentDirectoryAfterTestRunIsComplete>False</DeleteDeploymentDirectoryAfterTestRunIsComplete>
    <DeploymentEnabled>False</DeploymentEnabled>
    <AssemblyResolution>
      <Directory path="D:\myfolder\bin\" includeSubDirectories="false"/>
    </AssemblyResolution>
  </MSTest>

</RunSettings>

.runsettings 檔案中指定環境變數

環境變數可以在 .runsettings 檔案中設定,該檔案可以直接與測試主機互動。 您必須在 .runsettings 檔案中指定環境變數,以支援需要設定環境變數的非常重要專案,例如 DOTNET_ROOT。 這些變數是在繁衍測試主機程序時設定的,而且可在主機中使用。

範例

下列程式碼是傳遞環境變數的範例 .runsettings 檔案:

<?xml version="1.0" encoding="utf-8"?>
<!-- File name extension must be .runsettings -->
<RunSettings>
  <RunConfiguration>
    <EnvironmentVariables>
      <!-- List of environment variables we want to set-->
      <DOTNET_ROOT>C:\ProgramFiles\dotnet</DOTNET_ROOT>
      <SDK_PATH>C:\Codebase\Sdk</SDK_PATH>
    </EnvironmentVariables>
  </RunConfiguration>
</RunSettings>

RunConfiguration 節點應該包含 EnvironmentVariables 節點。 環境變數可以指定為元素名稱及其值。

注意

由於啟動測試主機時應該一律設定這些環境變數,因此測試應該一律在不同的程序中執行。 有鑑於此,當有環境變數時,將會設定 /InIsolation 旗標,以便一律叫用測試主機。