Skip to content

Instantly share code, notes, and snippets.

@skarllot
Created April 2, 2025 12:17
Show Gist options
  • Save skarllot/dc34e5ce7958254754d3954075ac42d2 to your computer and use it in GitHub Desktop.
Save skarllot/dc34e5ce7958254754d3954075ac42d2 to your computer and use it in GitHub Desktop.
Set custom value for init-only properties on AutoFixture
using System.Linq.Expressions;
using AutoFixture;
public static class AutoFixtureExtensions
{
public static FixtureCustomization<T> For<T>(this Fixture fixture) => new(fixture);
public class FixtureCustomization<T>(Fixture fixture)
{
public FixtureCustomization<T> With<TProp>(Expression<Func<T, TProp>> expr, TProp value)
{
fixture.Customizations.Add(new OverridePropertyBuilder<T, TProp>(expr, value));
return this;
}
public T Create() => fixture.Create<T>();
}
}
using System.Linq.Expressions;
using System.Reflection;
using AutoFixture.Kernel;
public class OverridePropertyBuilder<T, TProp>(Expression<Func<T, TProp>> expr, TProp value) : ISpecimenBuilder
{
private readonly PropertyInfo _propertyInfo =
(expr.Body as MemberExpression)?.Member as PropertyInfo
?? throw new InvalidOperationException("invalid property expression");
public object? Create(object request, ISpecimenContext context)
{
return
request is ParameterInfo pi
&& pi.ParameterType == typeof(TProp)
&& string.Equals(pi.Name, _propertyInfo.Name, StringComparison.OrdinalIgnoreCase)
? value
: new NoSpecimen();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment