有没有一种方法可以获取由 MSTest 框架使用 TestContext 或基测试类上的其他方法处理的异常?
如果在我的一个测试中出现未处理的异常,我想遍历 exception.Data 字典中的所有项目并将它们显示到测试结果中以帮助我找出测试失败的原因(我们通常添加数据到异常以帮助我们在生产环境中进行调试,所以我想对测试做同样的事情)。
注意:我没有测试应该发生的异常(我有其他测试),我正在测试一个有效的案例,我只需要查看异常数据。
这是我正在谈论的代码示例。
[TestMethod]
public void IsFinanceDeadlineDateValid()
{
var target = new BusinessObject();
SetupBusinessObject(target);
//How can I capture this in the text context so I can display all the data
//in the exception in the test result...
var expected = 100;
try
{
Assert.AreEqual(expected, target.PerformSomeCalculationThatMayDivideByZero());
}
catch (Exception ex)
{
ex.Data.Add("SomethingImportant", "I want to see this in the test result, as its important");
ex.Data.Add("Expected", expected);
throw ex;
}
}
我理解为什么我可能不应该有这样的封装方法存在问题,但我们也有子测试来测试 PerformSomeCalculation 的所有功能...
但是,如果测试失败,99% 的情况下,我会重新运行它通过,所以没有这些信息我无法调试任何东西。我还想在全局级别上执行此操作,以便如果任何测试失败,我会在测试结果中获得信息,而不是针对每个单独的测试执行此操作。
这是将异常信息放入测试结果的代码。
public void AddDataFromExceptionToResults(Exception ex)
{
StringBuilder whereAmI = new StringBuilder();
var holdException = ex;
while (holdException != null)
{
Console.WriteLine(whereAmI.ToString() + "--" + holdException.Message);
foreach (var item in holdException.Data.Keys)
{
Console.WriteLine(whereAmI.ToString() + "--Data--" + item + ":" + holdException.Data[item]);
}
holdException = holdException.InnerException;
}
}
最佳答案
我遇到了同样的问题,似乎没有对此的支持。您甚至不能使用 ApplicationDomain 的未处理异常 Hook ,因为如果 MSTEST 在异常冒出那么多之前没有捕获到异常,它自己就会崩溃。
可能的解决方法:
private delegate void TestImplDelegate();
private void RunTestWithExceptionLogging(TestImplDelegate testImpl)
{
try
{
testImpl();
}
catch (Exception e)
{
string message = e.Message; // don't warn about unused variables
// do logging here
}
}
[TestMethod]
public void test1()
{
RunTestWithExceptionLogging(test1Impl);
}
private void test1Impl()
{
// test code goes here
throw new Exception("This should get logged by the test wrapper.");
}
[TestMethod]
public void test2()
{
RunTestWithExceptionLogging(test2Impl);
}
private void test2Impl()
{
// test code goes here
throw new Exception("This should get logged by the test wrapper.");
}
这当然不是最佳选择,但至少这样您就不会拥有异常处理程序代码的多个副本。
我建议在 http://connect.microsoft.com/ 提交一个功能请求(或者查看其他人是否已经提出请求,然后投上您的一票。)
关于c# - MSTest 测试上下文异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2065714/