Skip to content

Instantly share code, notes, and snippets.

@wilwang
Created August 4, 2015 21:42
Show Gist options
  • Save wilwang/0d813548038565dc454c to your computer and use it in GitHub Desktop.
Save wilwang/0d813548038565dc454c to your computer and use it in GitHub Desktop.
autofixture specimen builder example to truncate strings
// 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