How to handle currentDomain.UnhandledException in MSTest
Here is my approach to the problem:
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))}>."); }
I choose Assert.fail
over Assert.AreEqual(0
because it distracts from the actual problem. (Too bad there is no CollectionAssert.IsEmpty()
method, that actually prints the collection on error.