【问题标题】:How to stop MsTest tests execution on first failure?如何在第一次失败时停止 MsTest 测试的执行?
【发布时间】:2013-03-30 02:41:06
【问题描述】:

我们正在运行每晚构建,最终使用 MsTest 框架运行我们所有的单元测试。

我们必须有 100% 的通过率,所以如果一个失败了,运行另一个没有意义;因此我们希望在第一次失败的测试中停止执行。

有没有办法实现它?

【问题讨论】:

  • 我遇到了同样的问题。有人吗?

标签: mstest vstest


【解决方案1】:

您确定要丢弃测试结果吗?

假设某人度过了糟糕的一天,并在您的代码中引入了多个错误 A、B 和 C。你可能在星期一才发现 A,所以你修复它,直到星期二你才知道问题 B,然后你直到星期三才修复 C。但是由于您错过了半周的测试覆盖率,周一引入的错误直到引入几天后才会被发现,而且修复它们的成本更高且需要更长的时间。

如果在失败后继续运行测试不会花费您太多,那么这些信息是否有用?


也就是说,在您的测试库中拼凑一个修复程序并不难。让所有可能的测试失败代码路径设置一个静态变量StopAssert.Failed = true;(可能通过包装对Assert 的调用并捕获AssertFailedExceptions。然后只需将[TestInitialize()] 方法添加到每个测试类以在失败后停止每个测试!

public class StopAssert
{
    public static bool Failed { get; private set; }

    public static void AreEqual<T>(T expected, T actual)
    {
        try
        {
            Assert.AreEqual(expected, actual);
        }
        catch
        {
            Failed = true;
            throw;
        }
    }

    // ...skipping lots of methods. I don't think inheritance can make this easy, but reflection might?

    public static void IsFalse(bool condition)
    {
        try
        {
            Assert.IsFalse(condition);
        }
        catch
        {
            Failed = true;
            throw;
        }
    }
}


[TestClass]
public class UnitTest1
{
    [TestInitialize()]
    public void Initialize()
    {
        StopAssert.IsFalse(StopAssert.Failed);
    }

    [TestMethod]
    public void TestMethodPasses()
    {
        StopAssert.AreEqual(2, 1 + 1);
    }

    [TestMethod]
    public void TestMethodFails()
    {
        StopAssert.AreEqual(0, 1 + 1);
    }

    [TestMethod]
    public void TestMethodPasses2()
    {
        StopAssert.AreEqual(2, 1 + 1);
    }
}

[TestClass]
public class UnitTest2
{
    [TestInitialize()]
    public void Initialize()
    {
        StopAssert.IsFalse(StopAssert.Failed);
    }

    [TestMethod]
    public void TestMethodPasses()
    {
        StopAssert.AreEqual(2, 1 + 1);
    }

    [TestMethod]
    public void TestMethodFails()
    {
        StopAssert.AreEqual(0, 1 + 1);
    }

    [TestMethod]
    public void TestMethodPasses2()
    {
        StopAssert.AreEqual(2, 1 + 1);
    }
}

【讨论】:

  • 任何人都可以通过配置设置来做到这一点?我们有很多代码需要修改:(
  • “如果在失败后继续运行测试不会花费太多,那么这些信息是否有用?” - 有时不是。在一个错误导致级联下降的情况下,我也有同样的情况。我想在第一次发生时立即停止,因为我需要找到导致级联的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2021-03-19
  • 2015-11-09
  • 1970-01-01
相关资源
最近更新 更多