-
-
Save viktorsteinwand/fa2fb4875183f1a0a31c24c15cd59fbf to your computer and use it in GitHub Desktop.
SAMPLE: Sub properties using reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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