我尝试根据答案实施解决方案单元测试时如何处理其他线程引发的异常? https://stackoverflow.com/a/934604/518530,但我仍然不明白在处理程序中要做什么。假设我有一个测试:
[TestMethod]
void Test()
{
new Thread(() => { throw new Exception(); }).Start();
}
我对所有测试进行了全局初始化:
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += currentDomain_UnhandledException;
}
static void currentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
if (ex != null)
Trace.WriteLine(ex);
Assert.Fail("Unhandled Exception in thread.");
}
问题是 Assert.Fail 实际上抛出了异常,该异常再次被 currentDomain_UnhandledException 捕获,并导致 MSTest 崩溃(stackoverflow?)。我不想捕获 Assert.Fail,但我想让测试失败。如何解决呢?
我知道我可以捕获异常并在测试的主线程上调用它,但我需要数千个测试的全局解决方案。我不想让每一个测试都变得复杂。
这是我解决问题的方法:
private List<(object sender, UnhandledExceptionEventArgs e)> _UnhandledExceptions;
[TestInitialize()]
public void Initialize()
{
_UnhandledExceptions = new List<(object sender, UnhandledExceptionEventArgs e)>();
AppDomain.CurrentDomain.UnhandledException += (sender, e) => {
_UnhandledExceptions.Add((sender, e));
};
}
[TestCleanup()]
public void Cleanup()
{
if (_UnhandledExceptions.Count != 0) Assert.Fail($"There were {_UnhandledExceptions.Count} unhandled Exceptions! <{string.Join(">," + Environment.NewLine + "<", _UnhandledExceptions.ToArray().Select(ev => ev.e.ExceptionObject))}>.");
}
我选择Assert.fail
over Assert.AreEqual(0
因为它分散了人们对实际问题的注意力。 (可惜没有CollectionAssert.IsEmpty()
方法,实际上在错误时打印集合。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)