Created
August 4, 2015 21:42
-
-
Save wilwang/0d813548038565dc454c to your computer and use it in GitHub Desktop.
autofixture specimen builder example to truncate strings
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
// lifted from http://stackoverflow.com/a/10130176/4040187 | |
public class StringPropertyTruncateSpecimenBuilder<TEntity> : ISpecimenBuilder | |
{ | |
private readonly int _length; | |
private readonly PropertyInfo _prop; | |
public StringPropertyTruncateSpecimenBuilder(Expression<Func<TEntity, string>> getter, int length) | |
{ | |
_length = length; | |
_prop = (PropertyInfo)((MemberExpression)getter.Body).Member; | |
} | |
public object Create(object request, ISpecimenContext context) | |
{ | |
var pi = request as PropertyInfo; | |
return pi != null && AreEquivalent(pi, _prop) | |
? context.Create<string>().Substring(0, _length) | |
: (object) new NoSpecimen(request); | |
} | |
private bool AreEquivalent(PropertyInfo a, PropertyInfo b) | |
{ | |
return a.DeclaringType == b.DeclaringType | |
&& a.Name == b.Name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment