7 c# unit-testing mstest exception-handling
有没有办法可以使用TestContext或基础测试类上的其他方法来处理由MSTest框架处理的异常?
如果在我的一个测试中发生未处理的异常,我想旋转exception.Data字典中的所有项目并将它们显示给测试结果,以帮助我找出测试失败的原因(我们通常会将数据添加到帮助我们在生产环境中调试的异常,所以我想做同样的测试).
注意:我没有测试异常是支持HAPPEN(我有其他测试),我正在测试一个有效的情况,我只需要查看异常数据.
这是我正在谈论的代码示例.
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道为什么我可能不应该有这样的封装方法存在问题,但我们也有子测试来测试PerformSomeCalculation的所有功能......
但是,如果测试失败,99%的时间,我重新运行它通过,所以没有这些信息我无法调试任何东西.我还想在GLOBAL级别上执行此操作,因此如果任何测试失败,我会在测试结果中获取信息,而不是为每个单独的测试执行此操作.
这是将异常信息放在测试结果中的代码.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 4
我遇到了同样的问题,似乎没有对此的支持。您甚至不能使用 ApplicationDomain 的未处理异常挂钩,因为如果 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.");
}
Run Code Online (Sandbox Code Playgroud)
这当然不是最佳的,但至少这样您就不会拥有异常处理程序代码的多个副本。
我建议在http://connect.microsoft.com/上提交此功能请求(或者查看其他人是否已经提出了请求,并添加您的投票。)
| 归档时间: |
|
| 查看次数: |
3101 次 |
| 最近记录: |