如何在C#单元测试中设置Exception的TargetSite.Name属性
解决方案
方法一:自定义异常类重写TargetSite属性
创建自定义异常类,通过构造函数传入目标方法的MethodBase实例,重写TargetSite属性返回该方法,测试时可精准指定目标方法:
public class TargetedException : Exception { private readonly MethodBase _targetMethod; public TargetedException(MethodBase targetMethod, string message = null, Exception innerException = null) : base(message, innerException) { _targetMethod = targetMethod; } public override MethodBase TargetSite => _targetMethod; }
测试代码示例:
// 获取目标方法的MethodBase实例 var fooMethod = typeof(YourClass).GetMethod("Foo", BindingFlags.Public | BindingFlags.Instance); // 在FluentAssertions中抛出自定义异常 Foo(Arg.Is(blabla)).Throws(new TargetedException(fooMethod));
方法二:通过反射修改Exception的私有字段
利用反射直接修改Exception内部存储TargetSite的私有字段,无需自定义异常(注意:不同.NET版本私有字段名可能为_targetSite或targetSite,需根据实际环境调整):
var exception = new Exception(); var targetSiteField = typeof(Exception).GetField("_targetSite", BindingFlags.Instance | BindingFlags.NonPublic); if (targetSiteField != null) { var fooMethod = typeof(YourClass).GetMethod("Foo", BindingFlags.Public | BindingFlags.Instance); targetSiteField.SetValue(exception, fooMethod); } // 测试中抛出修改后的异常 Foo(Arg.Is(blabla)).Throws(exception);
方法三:用Moq模拟Exception实例
如果项目使用Moq框架,可直接模拟Exception并设置TargetSite属性的返回值:
var fooMethod = typeof(YourClass).GetMethod("Foo", BindingFlags.Public | BindingFlags.Instance); var mockException = new Mock<Exception>(); mockException.SetupGet(e => e.TargetSite).Returns(fooMethod); // 测试中抛出模拟的异常 Foo(Arg.Is(blabla)).Throws(mockException.Object);
内容的提问来源于stack exchange,提问作者Shiro_Moon
相关产品推荐
相关产品推荐

