-
I have scoured the interwebs and I can't seem to find an example that lets the base class customizations apply to each and every derived class. I see lots of examples on how to omit specific properties but I don't want to do that. Pseudo Code: fixture.Customize<BaseEntity>(c => c.With(e => e.IsDeleted, false));
var derived = fixture.Create<DerivedClass>();
Assert.False(derived.IsDeleted); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
@mwasson74 there is no "nice" way of doing it using the postprocess composer (aka var node = new FilteringSpecimenBuilder(
new FixedBuilder(false),
new AndRequestSpecification(
new PropertySpecification(typeof(bool), nameof(MyBaseClass.IsDeleted)),
new MemberOwnerSpecification(
new BaseTypeSpecification(typeof(MyBaseClass))))); Note that I created two custom request specifications for this tree public class MemberOwnerSpecification : IRequestSpecification
{
public MemberOwnerSpecification(IRequestSpecification typeSpecification)
{
TypeSpecification = typeSpecification
?? throw new ArgumentNullException(nameof(typeSpecification));
}
public IRequestSpecification TypeSpecification { get; }
public bool IsSatisfiedBy(object request)
{
bool result = request switch
{
ParameterInfo parameter => TypeSpecification.IsSatisfiedBy(parameter.Member.ReflectedType),
PropertyInfo property => TypeSpecification.IsSatisfiedBy(property.ReflectedType),
FieldInfo field => TypeSpecification.IsSatisfiedBy(field.ReflectedType),
_ => false
};
return result;
}
}
public class BaseTypeSpecification : IRequestSpecification
{
public BaseTypeSpecification(Type baseType)
{
BaseType = baseType;
}
public Type BaseType { get; }
public bool IsSatisfiedBy(object request)
=> request is Type type
&& this.BaseType.IsAssignableFrom(type);
} Now given that you have two types [Fact]
public void AllGeneratedItemsAreDeleted()
{
var node = new FilteringSpecimenBuilder(
new FixedBuilder(false),
new AndRequestSpecification(
new PropertySpecification(typeof(bool), nameof(MyBaseClass.IsDeleted)),
new MemberOwnerSpecification(
new BaseTypeSpecification(typeof(MyBaseClass)))));
var fixture = new Fixture();
fixture.Customizations.Add(node);
var items = fixture.CreateMany<MyChildClass>(10);
var areAllFalse = items.All(x => x.IsDeleted == false);
Assert.True(areAllFalse);
} Now with a bit more code you could encapsulate that logic in a customization and reuse it in various scenarios. |
Beta Was this translation helpful? Give feedback.
@mwasson74 there is no "nice" way of doing it using the postprocess composer (aka
.Customize<>()
) however you can always create a builder tree that does what you require.Note that I created two custom request specifications for this tree
MemberOwnerSpecification
that helps identify the owner of the currently processed member andBaseTypeSpecification
which validates the type as a child type of a given type.p…