Skip to content

Instantly share code, notes, and snippets.

@roryf
Created February 13, 2013 12:47
Show Gist options
  • Save roryf/4944381 to your computer and use it in GitHub Desktop.
Save roryf/4944381 to your computer and use it in GitHub Desktop.
Object extension method to peek at a private field. Useful when testing an against an object which has state but will not actually execute anything. See example using NSubstitute.
repository.Query(Arg.Is<FindUserByEmailQuery>(x => x.PeekPrivateField("emailAddress") == "[email protected]")).Returns(user);
public class FindUserByEmailQuery : MyQUeryBaseClass<User>
{
private string emailAddress;
public FindUserByEmailQuery(string emailAddress)
{
this.emailAddress = emailAddress;
}
public User DoQUery(IQueryable<User> queryable)
{
// performs db query which we don't want for unit tests.
}
}
public static class PrivateFieldExtensions
{
public static object PeekPrivateField(this object subject, string field)
{
var privateFields = subject.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
var fieldInfo = privateFields.FirstOrDefault(x => x.Name == field);
if (fieldInfo == null)
{
return null;
}
return fieldInfo.GetValue(subject);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment