如何在MSC#dotnet测试中使用未处理的ExceptionEventHandler
我有一个简单的类如下。我无法使用未处理的ExceptionEventHandler打印以下单元测试的异常。有什么我不知道的吗。我已经使用控制台应用程序测试了相同的代码行,它从未处理的异常处理程序打印异常。当我使用MStest时,同样的方法不适用于我。我正在使用MStest的最新版本如何在MSC#dotnet测试中使用未处理的ExceptionEventHandler,c#,asp.net,.net,.net-core,mstest,C#,Asp.net,.net,.net Core,Mstest,我有一个简单的类如下。我无法使用未处理的ExceptionEventHandler打印以下单元测试的异常。有什么我不知道的吗。我已经使用控制台应用程序测试了相同的代码行,它从未处理的异常处理程序打印异常。当我使用MStest时,同样的方法不适用于我。我正在使用MStest的最新版本 [TestClass] public class UnitTest1 { [AssemblyInitialize] public static void AssemblyInitialize(Test
[TestClass]
public class UnitTest1
{
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext testContext)
{
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)
{
Console.WriteLine("===============================");
Console.WriteLine("===============================");
Console.WriteLine("Test failed:" + ex);
}
}
[TestInitialize]
public void Initialize()
{
}
[TestCleanup]
public void Cleanup()
{
}
[TestMethod]
public void RaiseEvents()
{
AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
{
Console.WriteLine("This is from Unhandled exception:======================");
Exception e = (Exception)eventArgs.ExceptionObject;
Console.WriteLine($@"{sender.ToString()}\t\t{e.Message}{e.GetBaseException()}
{e.InnerException}{e.Data}{e.Source}{e.StackTrace}");
};
var list = new List<string>();
var firstItem = list.FirstOrDefault().Contains("a");
Console.WriteLine($"First Item is:{firstItem}");
}
[AssemblyCleanup]
public static void AssemblyCleanUp()
{
}
}
[TestClass]
公共类UnitTest1
{
[汇编初始化]
公共静态void AssemblyInitialize(TestContext TestContext)
{
AppDomain currentDomain=AppDomain.currentDomain;
currentDomain.UnhandledException+=currentDomain\u UnhandledException;
}
静态无效currentDomain_UnhandledException(对象发送方,UnhandledExceptionEventArgs e)
{
异常ex=e.ExceptionObject作为异常;
如果(ex!=null)
{
Console.WriteLine(“===========================================”);
Console.WriteLine(“===========================================”);
Console.WriteLine(“测试失败:+ex”);
}
}
[测试初始化]
公共无效初始化()
{
}
[测试清理]
公共空间清理()
{
}
[测试方法]
公共无效事件
{
AppDomain.CurrentDomain.UnhandledException+=(发件人,事件参数)=>
{
Console.WriteLine(“这是来自未处理的异常:=========================”;
异常e=(异常)eventArgs.ExceptionObject;
Console.WriteLine($@“{sender.ToString()}\t\t{e.Message}{e.GetBaseException()}
{e.InnerException}{e.Data}{e.Source}{e.StackTrace}”);
};
var list=新列表();
var firstItem=list.FirstOrDefault()包含(“a”);
WriteLine($“第一项为:{firstItem}”);
}
[组装清理]
公共静态void AssemblyCleanUp()
{
}
}
您希望在哪一行引发未处理的异常?我在这一行的测试方法中看不到它:var firstItem=list.FirstOrDefault().Contains(“a”);在RaiseEvents TestMethodTryFirst()
中,确定吗?First()或FirstOrDefault将对此引发异常,因为列表为空。任何调用null或empty的方法都会引发异常,我的目标是使用EventHandler捕获这些未处理的异常。我猜mstest本身安装了一个处理程序来处理异常。据我所知,这个问题以前在这里被问过,但没有得到回答。