Visual Studio单元测试检测失败



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

[TestCleanup()]
public void MyTestCleanup()
{
    // Code to check if test passes or fails
    Common.DriverQuit();
}

然后,基于这个答案,我可以编写其余的代码。如果可能的话,我只需要想办法获取测试结果。

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

[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...
    }
}

所以我找到了解决方案。我要找的是TestContext。

TestContext.CurrentTestOutcome

这将给我一个通过或失败的字符串

最新更新