Search code examples
.netstringrandomnbuilder

Is it possible to use NBuilder to Build a collection of random strings?


pretty simple question: can I use NBuilder to create a collection of x number of random strings?

I was trying...

// NOTE: Tags need to be lowercase.
return Builder<string>
    .CreateListOfSize(10)
    .WhereAll()
        .Has(x => x = randomGenerator.Phrase(15))
    .WhereTheFirst(1)
        .Has(x => x = "time")
    .AndTheNext(1)
        .Has(x => x = "place")
    .AndTheNext(1)
        .Has(x => x = "colour")
    .Build();

but it was run-time erroring, something about I needed to call some specific constructor or something.

Anyone have any ideas?


Solution

  • NBuilder creates objects by using the default (parameterless) constructor. The exception you are receiving is because the String class doesn't have a default constructor.

    To create a list of random strings, you could use the Phrase method inside a loop. Maybe not as clean as a single NBuilder chain, but it gets the job done:

       List<string> stringsList = new List<string>();
       var generator = new RandomGenerator();
       for (int i = 0; i < 10; i++)
       {
           stringsList.Add(generator.Phrase(15));
       }
    
       return stringsList;