Using AutoBogus to set member property value range

1.6k views Asked by At

I have the following classes:

  Class Person
    Property ID As String = Nothing
    Property Firstname As String = ""
    Property Lastname As String = ""
  End Class

  Class Account
    Property AccountNumber As String = ""
    Property Owners As New List(Of Person)
  End Class

I wish to you utilize https://github.com/nickdodd79/AutoBogus to set a range of values from 1,000 to 10,000 for Person.ID when I instantiate an instance of the Account class like so:

    Dim fk = AutoFaker.Create()
    Dim acct = fk.Generate(Of Account)

Please how may I do this using AutoBogus?

2

There are 2 answers

1
user3574075 On BEST ANSWER

Solution modified from answer provided by Bogus author bchavez at https://github.com/bchavez/Bogus/issues/394.

Sub Main
   Dim personFaker = New AutoFaker(Of Person)
   personFaker.RuleFor(Function(p) p.Firstname, Function(f) f.Name.FirstName)
              .RuleFor(Function(p) p.Lastname, Function(f) f.Name.LastName)
              .RuleFor(Function(p) p.ID, Function(f) f.Random.Int(1000,10000).ToString)

   Dim accountFaker = New AutoFaker(Of Account)
   accountFaker.RuleFor(Function(a) a.AccountNumber, Function(f) f.Random.Replace("###############"))
               .RuleFor(Function(a) a.Owners, Function(f) New List(Of Person)(personFaker.GenerateBetween(1,5)))
   accountFaker.Generate().Dump()
End Sub

Class Person
   Property ID As String = Nothing
   Property Firstname As String = ""
   Property Lastname As String = ""
End Class

Class Account
   Property AccountNumber As String = ""
   Property Owners As New List(Of Person)
End Class
1
Nick Dodd On

The original design of AutoBogus was to generate small object graphs for unit tests. Generating the numbers you require could have a performance impact. However, if the above is what you are trying to generate and nothing more complex, then it could be small enough to succeed.

To use AutoBogus out the box you can do the following:

Dim acct = AutoFaker.Generate(Of Account, 1000)

The second parameter should be the number of accounts you want to create.

AutoBogus uses Bogus under the hood and then leverages Reflection to populate unset properties. If you do see any performance issues, you could use Bogus directly with the caveat that you need define a RuleFor for each property. The Bogus docs provide in-depth details on how to achieve this.

Nick.