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

如何从C#代码调用Dotnet CLI命令?.NET Core3.1 NUnit测试执行方案

如何从C#代码中调用Dotnet CLI命令并运行NUnit测试

Hey there! Let's break down how to call Dotnet CLI commands from C# code, and specifically implement your NUnit test running requirement step by step.

1. 基础逻辑:用System.Diagnostics.Process调用外部命令

In C#, we rely on the Process class to launch and control external processes like the Dotnet CLI. The core steps are:

  • Reference the System.Diagnostics namespace
  • Configure ProcessStartInfo: specify the program to run (dotnet), command arguments, and whether to redirect output/error streams
  • Start the process and wait for it to finish
  • Optional: Capture output or error messages to debug issues easily

2. 针对你的NUnit测试的完整实现

Here's the complete code that fulfills your need to run both dotnet test commands, with error handling and output capture included:

using System;
using System.Diagnostics;

namespace MyNameSpace
{
    class MyProgram
    {
        public void RunTests()
        {
            // Execute first command: dotnet test
            RunDotnetCommand("test");
            
            // Execute second command: dotnet test --filter "Category=CategoryA&Category=CategoryB"
            RunDotnetCommand(@"test --filter ""Category=CategoryA&Category=CategoryB""");
        }

        private void RunDotnetCommand(string arguments)
        {
            // Set up process start details
            var startInfo = new ProcessStartInfo
            {
                FileName = "dotnet", // Target program is Dotnet CLI
                Arguments = arguments, // Pass the command arguments
                RedirectStandardOutput = true, // Redirect output to capture results
                RedirectStandardError = true, // Redirect error messages
                UseShellExecute = false, // Must be false to redirect streams
                CreateNoWindow = true, // Run in background without a new window
                WorkingDirectory = Environment.CurrentDirectory // Use current directory as working path (adjust if needed)
            };

            using (var process = new Process { StartInfo = startInfo })
            {
                try
                {
                    process.Start();
                    // Read output and error synchronously to avoid deadlocks
                    string output = process.StandardOutput.ReadToEnd();
                    string error = process.StandardError.ReadToEnd();
                    
                    process.WaitForExit(); // Wait for the command to complete

                    // Print results (you can log these instead of writing to console)
                    Console.WriteLine($"Command Output:\n{output}");
                    if (!string.IsNullOrEmpty(error))
                    {
                        Console.WriteLine($"Command Errors:\n{error}");
                    }

                    // Check exit code: 0 means success, non-0 means failure
                    if (process.ExitCode != 0)
                    {
                        throw new Exception($"Command failed with exit code: {process.ExitCode}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error executing command: {ex.Message}");
                    // Handle the exception as needed (rethrow, log, etc.)
                }
            }
        }
    }
}

Key Notes:

  • Parameter Escaping: For the --filter argument, we use a verbatim string (@) and double quotes ("") to ensure the CLI correctly parses the filter with spaces and the & logical operator.
  • Working Directory: The WorkingDirectory is set to the current directory. If your test project is in a different path, update this to the full path of your test project folder (e.g., @"C:\MyProjects\MyTestProject").
  • Output Capture: Redirecting output and error streams lets you debug failed tests or log results for later review.
  • Error Handling: The try-catch block and exit code check help you catch and handle issues like missing Dotnet CLI, invalid test project paths, or failed tests.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:32:42