Search code examples
c#bogus

Bogus - Faker to pick a random custom type


Have this:

        var SampleNames = new PersianName[] {
            new XName("Sara","Dianov"),
            new XName("Eliza","Raas"),
            new XName("Robert","Smith")
        };

        var theFaker = new Faker<Architect>()
        .RuleFor(h => h.User.NameBundle, f => f.PickRandom(SampleNames))

Get this error:

Error: System.ArgumentException: 
Your expression 'h.User.NameBundle' cant be used. 
Nested accessors like 'o => o.NestedObject.Foo' at a parent level are not allowed.
 You should create a dedicated faker for NestedObject like new Faker<NestedObject>().RuleFor(o => o.Foo, ...)
 with its own rules that define how 'Foo' is generated.
 See this GitHub issue for more info: https://github.com/bchavez/Bogus/issues/115

How can I resolve the issue? Have read the provided link in the error message, BTW I couldn't resolve it yet. I wanted to assign a random XName element to the h.User.NameBundle, don't if I really need the second faker here and not sure how can I use a separate Faker to achieve this.


Solution

  • You can use another faker for nested types. You could then reference it in the other faker like this .RuleFor(h => h.User, () => userFaker). Here's a sample:

    var samples = new Name[] 
    {
        new Name { FistName = "Sara", LastName = "Dianov" },
        new Name { FistName = "Eliza", LastName = "Raas" },
        new Name { FistName = "Robert", LastName = "Smith" }
    };
    
    var userFaker = new Faker<User>()
        .RuleFor(h => h.Name, f => f.PickRandom(samples));
    
    var someClassFaker = new Faker<SomeClassWithPropUser>()
        .RuleFor(h => h.User, () => userFaker);