0
public static string GetErrorMessageFromTestContext(TestContext testContext)
    {
        const BindingFlags privateGetterFlags = System.Reflection.BindingFlags.GetField |
                                                System.Reflection.BindingFlags.GetProperty |
                                                System.Reflection.BindingFlags.NonPublic |
                                                System.Reflection.BindingFlags.Instance |
                                                System.Reflection.BindingFlags.FlattenHierarchy;

    var m_message = string.Empty; // Returns empty if TestOutcome is not failed
    if (testContext.CurrentTestOutcome == UnitTestOutcome.Failed)
    {
        // Get hold of TestContext.m_currentResult.m_errorInfo.m_message (contains the exception text that was thrown)
        var field = testContext.GetType().GetField("m_currentResult", privateGetterFlags);}
4

1 回答 1

0

如何覆盖TestMethodAttribute

public class MyTestMethodAttribute : TestMethodAttribute
{
    public override TestResult[] Execute(ITestMethod testMethod)
    {
        TestResult[] testResults = base.Execute(testMethod);

        foreach (TestResult item in testResults.Where(x => x.Outcome == UnitTestOutcome.Failed))
        {
             // "Assert.AreEqual failed. Expected:<1>. Actual:<2>."
            string errorMessage = item.TestFailureException?.Message;
        }

        return testResults;
    }
}

[TestClass]
public class MyClassTest
{
    [MyTestMethod]
    public void MyTestMethod()
    {
        Assert.AreEqual(1, 2);
    }
}
于 2018-09-12T06:52:18.277 回答