我试图根据答案实现解决方案 How to handle exceptions raised in other threads when unit testing? ,但我仍然不明白在处理程序中做什么。假设我有一个测试:
[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?)。我不想 catch 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
在 Assert.AreEqual(0
因为它分散了对实际问题的注意力。 (太糟糕了,没有 CollectionAssert.IsEmpty()
方法,它实际上在错误时打印集合。
关于c# - 如何在 MSTest 中处理 currentDomain.UnhandledException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38309657/