Skip to content

Instantly share code, notes, and snippets.

@dtchepak
Created August 14, 2012 11:59
Show Gist options
  • Save dtchepak/3348663 to your computer and use it in GitHub Desktop.
Save dtchepak/3348663 to your computer and use it in GitHub Desktop.
SAMPLE: Sub properties using reflection
// SAMPLE ONLY -- DON'T USE FOR REAL STUFF UNLESS YOU'VE REVIEWED AND TESTED :)
// Needs work to make robust: check property type's class has default ctor and so on.
// Can also filter out interfaces as these will be auto-subbed.
public static T SubFor<T>() where T : class
{
var gettableVirtualProps = typeof(T).GetProperties()
.Where(x => x.CanRead && x.GetGetMethod().IsVirtual)
.Select(x => x);
var sub = Substitute.For<T>();
foreach (var prop in gettableVirtualProps)
{
var subForProperty = Substitute.For(new[] { prop.PropertyType }, new object[0]);
var value = prop.GetValue(sub, null);
value.Returns(subForProperty);
}
return sub;
}
public abstract class A { public abstract void AStuff(); public virtual void VirtualAStuff() { } }
public abstract class B { public abstract void BStuff(); }
public class Foo
{
public virtual A A { get; set; }
public virtual B B { get; set; }
}
[Test]
public void TestAutoSubForAllProperties()
{
var sub = SubFor<Foo>();
Assert.NotNull(sub.A);
Assert.NotNull(sub.B);
sub.A.VirtualAStuff();
sub.A.Received().VirtualAStuff();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment