MageWind
MageWind

Reputation: 841

Mock a Property Getter Throw an Exception Using Reflection

I would like to mock a property that I found using reflection to throw an exception when someone tries to Get from it. The problem is that I do not know the type of ID. Below is an example of what I have tried:

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;
}

Currently, I get a RuntimeBinderException: 'object' does not contain a definition for 'Throws'. What am I doing wrong?

This is similar to Moq and reflection, passing dynamically generated expression tree / lambda to moq and Create an Expression<Func<,>> using reflection.

Upvotes: 2

Views: 969

Answers (2)

Tim S.
Tim S.

Reputation: 56576

If you cast the result of Setup to IThrows, it works. I'm not sure why it fails how you have it; maybe because the runtime type of moq.Setup(func) is not normally visible (it's internal to Moq).

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

Upvotes: 1

nvsnkv
nvsnkv

Reputation: 21

Maybe

moq.Setup( x => x.Id).Throws(new Exception());

?

Upvotes: 0

Related Questions