gpt4 book ai didi

c# - 使用反射模拟属性 Getter 抛出异常

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:03 24 4
gpt4 key购买 nike

我想模拟一个我发现的属性,当有人试图从中获取时,我会使用反射抛出异常。问题是我不知道 ID 的类型。以下是我尝试过的示例:

internal static T CreateObjectWithExceptioningIDProperty<T>() where T : class
{
Type type = typeof(T);
var moq = new Mock<T>();
var lambdaParameter = Expression.Parameter(type);
PropertyInfo idProperty = type.GetProperties().First(pi => pi.Name.Equals("ID"));
var lambdaBody = Expression.Property(lambdaParameter, idProperty);
dynamic func = Expression.Lambda(lambdaBody, lambdaParameter);
moq.Setup(func).Throws(new Exception()); // get RuntimeBinderException
return moq.Object;
}

目前,我得到一个 RuntimeBinderException: 'object' does not contain a definition for 'Throws'。我做错了什么?

这类似于 Moq and reflection, passing dynamically generated expression tree / lambda to moqCreate an Expression<Func<,>> using reflection .

最佳答案

如果您将 Setup 的结果转换为 IThrows,它会起作用。我不确定为什么它会失败;可能是因为 moq.Setup(func) 的运行时类型通常不可见(它是 internalMoq)。

((IThrows)moq.Setup(func)).Throws(new Exception());

关于c# - 使用反射模拟属性 Getter 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com