In the Setup of my NUnit test, I create AutoFixture customizations where I need predefined values for my objects. However, these are merely defaults - some tests need to somehow override these defaults. This is how I add the customization:
fixture.Customizations.Add(new FilteringSpecimenBuilder(new FixedBuilder(value),
new ParameterSpecification(valueType, propertyName)));
If I merely add a new customization in the test, the customization won't actually be applied because it's lower down in the graph.
So what I thought I could do is remove
the customization that matches the signature of the FilteringSpecimenBuilder I had created before, but this doesn't seem to work unless it's the actual FilteringSpecimenBuilder instance I created in the Setup. And for that to work, I'd have to save-for-later and catalogue all the instances I created in the Setup, which seems redundant since they're already part of the Fixture graph.
I then tried something like this, where "name" is the actual name of the variable I'm trying to remove, but apparently referencing the TargetType and TargetName properties is not allowed as they're obsolete (and the error message doesn't explain what the replacement is):
fixture
.Customizations
.OfType<FilteringSpecimenBuilder>()
.Where(x => x.Specification is ParameterSpecification)
.Where(x=>(((ParameterSpecification)x.Specification).TargetName == "name"))
.ToList()
.ForEach(c => fixture.Customizations.Remove(c));
Does anyone know of a way of replacing a customization, or removing an existing one?
If you want to override existing functionality, the easiest solution is to put it before the Customization you want to override. The Add
method adds to the end of a collection, so use Insert
instead:
fixture.Customizations.Insert(0, new MySpecimenBuilder());
Inserting at index 0
puts that builder before anything else, which means it'll be the first to be checked.