You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 05:06:26