【问题标题】:How to get error message with MSTest TestContext?如何使用 MSTest TestContext 获取错误消息?
【发布时间】:2019-07-20 15:30:36
【问题描述】:

我正在尝试从 mstest 获取失败的测试用例的错误消息。

我在网上找到了一些使用TestContext的东西,下面是我拥有的代码sn-p。

public static string GetErrorMessageFromTestContext(TestContext testContext) {

        BindingFlags privateGetterFlags = BindingFlags.GetField |
                                            BindingFlags.GetProperty |
                                            BindingFlags.NonPublic |
                                            BindingFlags.Instance |
                                           BindingFlags.FlattenHierarchy;

        var m_message = string.Empty;
        Type t = testContext.GetType();

        if (testContext.CurrentTestOutcome == UnitTestOutcome.Failed)
        {
            var field = t.GetField("m_currentResult", privateGetterFlags);
            object m_currentResult = field.GetValue(testContext);

            field = m_currentResult.GetType().GetField("m_errorInfo", 
            privateGetterFlags);
            var m_errorInfo = field.GetValue(m_currentResult);

            field = m_errorInfo.GetType().GetField("m_message", 
            privateGetterFlags);
            m_message = field.GetValue(m_errorInfo) as string;
        }

        return m_message;
    }

这个东西应该从失败的案例中返回一条错误消息。但是,在执行该行时:

var field = t.GetField("m_currentResult", privateGetterFlags);

字段被分配了空值。不知道是什么原因,所以我也愿意接受其他解决方案。谢谢!

【问题讨论】:

    标签: c# mstest


    【解决方案1】:

    您的解决方案不起作用,因为这是 MSTest v1 示例,而且您很可能正在使用 MSTest v2。您不会在 v2 中的 TestContext 中找到消息,因为它不存在。您需要查看TestResult 类才能收到此消息。

    获得TestResult 类的一种方法是覆盖TestMethodAttribute 并使用它,如下例所示:

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace TestProject
    {
        [TestClass]
        public class UnitTest
        {
            [MyTestMethod]
            public void TestMethod()
            {
                Assert.IsTrue(false);
            }
        }
    
        public class MyTestMethodAttribute : TestMethodAttribute
        {
            public override TestResult[] Execute(ITestMethod testMethod)
            {
                TestResult[] results = base.Execute(testMethod);
    
                foreach (TestResult result in results)
                {
                    if (result.Outcome == UnitTestOutcome.Failed)
                    {
                        string message = result.TestFailureException.Message;
                    }
                }
    
                return results;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-06
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多