-
can a rule on an object be added to after the original |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Not exactly the most elegant, but here's one way to apply void Main()
{
var faker = new ChaosFaker<User>()
.RuleFor(u => u.FirstName, f => f.Name.FirstName())
.RuleFor(u => u.LastName, f => f.Name.LastName())
.RuleFor(u => u.Age, f => f.Random.Number(18, 27))
as ChaosFaker<User>;
faker.Generate(5).Dump();
faker.WithChaos();
faker.Generate(5).Dump();
}
public class User
{
public string FirstName;
public string LastName;
public int? Age;
}
public class ChaosFaker<T> : Faker<T> where T : class{
public ChaosFaker<T> WithChaos()
{
var allRulesets = this.Actions.Values;
foreach (var ruleSet in allRulesets)
{
foreach( var rule in ruleSet ){
this.AddRule(rule.Key, (f, t) => rule.Value.Action(f, t).OrDefault(f));
}
}
return this;
}
} This particular implementation above is a "one time use" kind of situation; ie: once you call If you want to switch between "original" and "with null" on-demand, you'll need to keep a copy of the "old"/original population rule before overwriting it; and load the originals back. Hope that helps. Feel free to carry on the conversation after I close the thread. Thanks, |
Beta Was this translation helpful? Give feedback.
Not exactly the most elegant, but here's one way to apply
.OrNull/.OrDefault
to all rules stored in aFaker<T>
object: