亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 MSTest TestContext 獲取錯誤消息?

如何使用 MSTest TestContext 獲取錯誤消息?

C#
九州編程 2023-07-09 15:08:22
我正在嘗試從 mstest 獲取失敗測試用例的錯誤消息。我在網上找到了一些使用 TestContext 的東西,下面是我的代碼片段。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);字段被分配為 null。不確定原因是什么,所以我也愿意接受其他解決方案。謝謝!
查看完整描述

1 回答

?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

您的解決方案不起作用,因為這是 MSTest v1 示例,并且很可能您正在使用 MSTest v2。您不會在TestContextv2 中的 a 中找到消息,因為那里不存在該消息。您需要檢查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;

        }

    }

}


查看完整回答
反對 回復 2023-07-09
  • 1 回答
  • 0 關注
  • 158 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號