Skip to content

Instantly share code, notes, and snippets.

@aivascu
Created November 15, 2021 17:49
Show Gist options
  • Save aivascu/6a5da6288940dfadb9cbaead610df3c9 to your computer and use it in GitHub Desktop.
Save aivascu/6a5da6288940dfadb9cbaead610df3c9 to your computer and use it in GitHub Desktop.
Manual property customization
public class ExactPropertyCriterion : IEquatable<PropertyInfo>
{
private readonly PropertyInfo propertyInfo;
public ExactPropertyCriterion(PropertyInfo propertyInfo)
{
this.propertyInfo = propertyInfo;
}
public bool Equals(PropertyInfo other)
{
return this.propertyInfo?.Equals(other) == true;
}
}
public class RequestRelay : ISpecimenBuilder
{
private readonly IRequestSpecification specification;
private readonly ISpecimenBuilder builder;
public RequestRelay(IRequestSpecification specification, ISpecimenBuilder builder)
{
this.specification = specification;
this.builder = builder;
}
public object Create(object request, ISpecimenContext context)
{
if (!this.specification.IsSatisfiedBy(request))
return new NoSpecimen();
return this.builder.Create(request, context);
}
}
public class OrderTaxCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customizations.Add(
new RequestRelay(
new PropertySpecification(
new ExactPropertyCriterion(
typeof(Order).GetProperty(nameof(Order.Cost)))),
new FixedBuilder(230)));
}
}
[Fact]
public void CustomizesProperty()
{
var fixture = new Fixture().Customize(new OrderTaxCustomization());
var order = fixture.Create<Order>();
Assert.NotNull(order);
Assert.Equal(230, order.TaxPercent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment