I'm trying to get the error message of a failed test case from mstest.
I found something online that uses TestContext and below is the code snippet I have.
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;
}
This thing should return an error message from the failed case. However, when executing the line:
var field = t.GetField("m_currentResult", privateGetterFlags);
field is being assigned with null. Not sure what's the reason so I'm opened to other solutions as well. Thanks!
Your solution doesn't work, because this is MSTest v1 example, and most likely you are using MSTest v2. You won't find message in a TestContext
in v2 because it doesn't exist there. You need to check TestResult
class to get this message.
One way to get TestResult
class is to override TestMethodAttribute
and use it as in example below:
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;
}
}
}