Created
April 2, 2025 12:17
-
-
Save skarllot/dc34e5ce7958254754d3954075ac42d2 to your computer and use it in GitHub Desktop.
Set custom value for init-only properties on AutoFixture
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
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>(); | |
} | |
} |
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
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