除了lukbl的答案之外,您还可以在整个程序集范围内执行相同的操作,因此,如果您有多个测试类,则在vstest.console.exe运行时(例如,如果您多次调用它),您将对测试进行全局管理。
根据您如何使用vstest.console(或mstest),需要注意。如果您在多个测试代理之间进行负载平衡,则每个测试代理都将运行自己的vstest.console.exe,并且因此将具有其自己的程序集级别值,因此会话管理将受到在同一代理上运行的测试组的限制。假设这种方法将为您提供使用命令运行的整个测试集的管理:
vstest.console.exe /filter: tests.dll
这意味着,无论您的session_failed变量的范围是类范围还是程序集范围,如果您最终使用不同的vstest.console.exe调用从同一类运行不同的测试,则会失去变量值或控制。
话虽如此,对于多类测试场景,有一个简单的方法:
[TestClass]
public static class TestSettings
{
public static bool SessionTestsFailed = false;
[AssemblyInitialize]
public static void runsBeforeAnyTest(TestContext t)
{
TestSettings.SessionTestsFailed = false;
}
}
[TestClass]
public class Tests1
{
public TestContext TestContext { get; set; }
[TestInitialize()]
public void MyTestInitialize()
{
if (TestSettings.SessionTestsFailed)
Assert.Fail("Session failed, test aborted");
}
[TestCleanup]
public void MyTestFinalize()
{
if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed)
TestSettings.SessionTestsFailed = true;
}
[TestMethod]
public void test11()
{
Console.WriteLine("test11 ran");
Assert.Fail("fail the test");
}
[TestMethod]
public void test12()
{
Console.WriteLine("test12 ran");
Assert.Fail("fail the test");
}
}
[TestClass]
public class Tests2
{
public TestContext TestContext { get; set; }
[TestInitialize()]
public void MyTestInitialize()
{
if (TestSettings.SessionTestsFailed)
Assert.Fail("Session failed, test aborted");
}
[TestCleanup]
public void MyTestFinalize()
{
if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed)
TestSettings.SessionTestsFailed = true;
}
[TestMethod]
public void test21()
{
Console.WriteLine("test21 ran");
Assert.Fail("fail the test");
}
[TestMethod]
public void test22()
{
Console.WriteLine("test22 ran");
Assert.Fail("fail the test");
}
这里有一个简单的方法,可以使用正则表达式匹配和 Visual Studio 的替换全部功能,一次性更新所有测试初始化方法(如果它们的签名相同):
查找:
(\s*)public void MyTestInitialize\(\)(\s*)(\r*\n)(\s*){(\r*\n)
替换:
$1public void MyTestInitialize()$3$4{$1\tif (TestSettings.SessionTestsFailed) Assert.Fail("Session failed, test aborted")
对于TestFinalize()也是类似的处理。