我想模拟一个我发现使用反射的属性,当有人试图从中获取时抛出异常。问题是我不知道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 moq和Create an Expression<Func<,>> using reflection。
答案 0 :(得分:1)
如果您将Setup
的结果投射到IThrows
,则可行。我不确定为什么它没有你怎么拥有它;也许是因为moq.Setup(func)
的运行时类型通常不可见(它是internal
到Moq
)。
((IThrows)moq.Setup(func)).Throws(new Exception());
答案 1 :(得分:0)
也许
moq.Setup( x => x.Id).Throws(new Exception());