Created
February 13, 2013 12:47
-
-
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.
This file contains 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
repository.Query(Arg.Is<FindUserByEmailQuery>(x => x.PeekPrivateField("emailAddress") == "[email protected]")).Returns(user); |
This file contains 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
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. | |
} | |
} |
This file contains 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
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