Visual Studio 单元测试检测失败

Visual Studio unit test detect failure

所以我在 Visual Studio 2015 年编写测试,并使用 MS UnitTesting 对其执行 运行。我想做的是编写一些代码,然后在测试完成后我可以更新一个集会测试用例。我正在寻找的是如何检测刚刚 运行 的测试用例是通过还是失败。我一直在看反射但没有看到测试的选项

[TestCleanup()]
public void MyTestCleanup()
{
    // Code to check if test passes or fails

    Common.DriverQuit();
}

然后根据这个答案我可以编写其余的代码。如果可能的话,我只需要弄清楚如何访问测试结果。

所以我想出了解决办法。我要找的是 TestContext。

TestContext.CurrentTestOutcome

这将给我一串通过或失败

MSTest 框架有一个 TestContext class,其中包含与当前测试相关的所有信息。您可以通过声明同名 属性 来访问它,然后由框架自动设置:

[TestClass]
public class UnitTest1
{
    private TestContext testContextInstance;

    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }

    ...

声明后,您可以直接访问您需要的信息:

[TestCleanup]
public void Cleanup()
{
    if (TestContext.CurrentTestOutcome == UnitTestOutcome.Failed)
    {
        // whatever...
    }
}