【问题标题】:NUnit tests calling cmd.exe commands with use of Processes don't pass使用进程调用 cmd.exe 命令的 NUnit 测试未通过
【发布时间】:2021-06-24 17:52:07
【问题描述】:

所以我正在创建一个 NUnit 项目,其中每个测试:

  • System.Diagnostics 运行一个新的Process
  • 使用cmd.exe 调用lli.exe,并将LLVM 代码文件作为参数
  • 检查此命令的退出代码和输出

一切顺利,测试在单独运行时通过,从测试资源管理器中逐一运行。但是,当我尝试在一次运行中运行多个测试时,就会出现问题。这是我的代码:

        [Theory]
        [TestCase("TestFile1", "")]
        [TestCase("TestFile2", "")]
        [TestCase("TestFile3", "0X17FFAA")]
        public void TestValidProgram(string programPath, string expectedOutput = "")
        {
            Compiler.Compile(programPath); // here {programPath}.ll file is created
            
            string result;
            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = $"/C {lliPath} {programPath}.ll",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                CreateNoWindow = true
            };
            using (Process proc = new Process())
            {
                proc.StartInfo = startInfo;
                proc.Start();
                proc.WaitForExit();
                result = proc.StandardOutput.ReadToEnd();
                Console.WriteLine($"res: {result}");
                Assert.AreEqual(0, proc.ExitCode); // stopping here
                proc.Close();
            }

            Assert.AreEqual(expectedOutput, result);
        }

当我在一次运行中运行所有 3 个测试时,只有第一个 TestFile1 通过,其余在此断言处停止:
Assert.AreEqual(0, proc.ExitCode);proc.ExitCode 等于 1。此外,result 字符串是空(因为它不应该是TestFile3)。

并行运行不是这种情况,我按顺序运行它们。此外,添加 [NonParallelizable] 属性不会改变任何内容。 Compiler创建的文件是正确创建的,可以使用lli.exe成功运行。

我使用 VSCode 2019 16.10.2。该项目在 .Net Framework 4.8 和 NUnit 3.13.2 上运行。 (我知道我可以使用 .net core 或 .net5,但这是项目的要求)。
我的想法用完了,需要帮助! :)

【问题讨论】:

    标签: c# nunit lli


    【解决方案1】:

    [SetUp] 属性下的方法将在每次执行每个测试用例/方法之前执行。

    确保在此方法中执行另一个测试用例之前终止所有先前的进程。

    【讨论】:

    • 不应该终止吗?我的意思是,我使用proc.WaitForExit(); 并处置proc。我刚刚检查了proc.HasExited 属性-退出后它设置为true,正如可以预料的那样。
    • ProcessStartInfo 的猜测问题。尝试在[SetUp] 方法中使用它,并在测试方法中单独使用startInfo.Arguments
    • @Gowthaman 设置方法的上下文与测试方法的上下文相同。但是,每次测试后似乎都需要使用 TearDown 方法进行清理。我也会怀疑编译步骤。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多