我想通过 MS Test(从 Windows 控制台)运行单元测试,这样我就可以在以下情况下停止/终止测试执行:失败的测试计数超过一定的阈值。
对于我的用例,当一定比例的测试已经失败时,没有必要继续运行测试。
我只能考虑创建一个新的控制台应用程序来包装 mstest.exe 执行,这样我就可以实时解析标准输出,
并最终杀死该进程,例如:
var pi = new ProcessStartInfo()
{
FileName = MS_TEST,
UseShellExecute = false,
RedirectStandardOutput = true,
Arguments = MS_TEST_ARGS
};
int passed = 0; int failed = 0;
using (var process = Process.Start(pi))
{
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (line.Contains("Passed"))
passed++;
if (line.Contains("Failed"))
failed++;
if (failed >= THRESHOLD)
{
process.Kill();
break;
}
}
}
谁能提出更好的方法来做到这一点?我认为 MsTest 本身并不支持这一点。
PowerShell 似乎是一个选项,但标准输出重定向并不是微不足道的。
Update
请注意,我无法修改测试代码,我需要在不以任何方式修改测试代码的情况下完成此操作。
创建一个BaseTestClass
其中包含一个负责终止运行测试的进程的方法。
using System.Diagnostics;
namespace UnitTestProject1
{
public class BaseTestClass
{
private readonly int _threshold = 1;
private static int _failedTests;
protected void IncrementFailedTests()
{
if (++_failedTests >= _threshold)
Process.GetCurrentProcess().Kill();
}
}
}
您必须继承所有测试类BaseTestClass
并使用[TestCleanup]
属性。这TestCleanup()
当在中定义的测试时评估方法DemoTests
课程已结束运行。在该方法中,我们评估刚刚完成的测试的输出。如果失败,我们将终止负责运行测试的进程。
在下面的示例中,我们定义了三个测试。第二次测试,Test_Substracting_Operation()
,旨在故意失败,因此第三个测试将永远不会运行。
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
{
[TestClass]
public class DemoTests : BaseTestClass
{
public TestContext TestContext { get; set; }
[TestCleanup]
public void TestCleanup()
{
if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed)
{
IncrementFailedTests();
}
}
[TestMethod]
public void Test_Adding_Operation()
{
// Arrange
int x = 1;
int y = 2;
// Act
int result = x + y;
// Assert
Assert.AreEqual(3, result);
}
[TestMethod]
public void Test_Substracting_Operation()
{
// Arrange
int x = 1;
int y = 2;
// Act
int result = x - y;
// Assert
Assert.AreEqual(100, result);
}
[TestMethod]
public void Test_Multiplication_Operation()
{
// Arrange
int x = 1;
int y = 2;
// Act
int result = x * y;
// Assert
Assert.AreEqual(2, result);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)