Test Data Generation: Auto populate objects with NAuto

Wednesday, April 9, 2014
by Sean McAlinden

NAuto is a test data generator for .Net. You can download it from Nuget as usual, if you need some instructions visit the following page: http://www.nuget.org/packages/NAuto. It has a similar goal to libraries like NBuilder but with it's own syntax and distinguishing features.   Whilst NAuto has quite a few features, this post is the proverbial hello world.  

Fill a complex model with data using NAuto and 1 line of code*

Lets say you have a complex model with a load of properties, and complex child properties etc. etc.   Something like:

public class SubTestModel
    public string SubString { get; set; }
    public string SubEmail { get; set; }
    public string SubPostCode { get; set; }
    public int? SubInteger { get; set; }
    public double? SubDouble { get; set; }
    public DateTime? SubDateTime { get; set; }
    public bool? SubBool { get; set; }
    public List<SubSubTestModel> FavouriteComplexList { get; set; }
    public int[] SimpleArray { get; set; }
    public SubSubTestModel SubSubTestModel { get; set; }

public class SubSubTestModel
    public string SubSubString { get; set; }
    public string SubSubEmail { get; set; }
    public string SubSubPostCode { get; set; }
    public int SubSubInteger { get; set; }
    public double SubSubDouble { get; set; }
    public DateTime SubSubDateTime { get; set; }
    public bool SubSubBool { get; set; }
    public List<SubSubTestModel> FavouriteComplexList { get; set; }

To populate this entire model with pretty good data, you pass the parent type and call AutoBuild.  


var testModel = NAuto.AutoBuild<TestModel>()

If you now inspect the model, you will find that it is nicely populated. You might also be surprised to find that some property look remarkably similar to the intended use of the property, for example values in the property containing the text "Email" will be formatted as an email string i.e. {someText}@{someMoreText}.com , urls will look like urls, postal codes will look like postal codes etc. this is due to the easy to extend convention mappings, I'll cover this in detail later on..   NAuto goes a lot further than this and has many interesting and useful features which I'll cover in future posts. Grab it from Nuget and have a play. There is a link on Nuget to a full documentation site.   * I've split the statement for readability so I guess technically it's now 3 lines... doesn't sound as good though