Generating Mock Data using NBuilder

Rajnilari2015
Posted by in C# category on for Beginner level | Points: 250 | Views : 170 red flag

NBuilder is a tool for generating mock data. Many times it happens that while performing unit testing we need to generate test data. NBuilder comes into a very handy way in such situations. In this article, we will look into how to use NBuilder to generate test data with examples.


 Download source code for Generating Mock Data using NBuilder

Introduction

NBuilder is a tool for generating mock data. Many times it happens that while performing unit testing we need to generate test data. NBuilder comes into a very handy way in such situations. In this article, we will look into how to use NBuilder to generate test data with examples.

Installation and SetUp

Fire a console application and issue the below command through Nuget Package Manager Console.

PM >Install-Package NBuilder

Let us now create a "Employee" entity class as under

public class Employee
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public string Email { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
    public DateTime DOB { get; set; }
    public DateTime DOJ { get; set; }
    public string Address { get; set; }
    public decimal Salary { get; set; }
}

Generating a single data for the Employee Object

Now suppose we want to generate a single data for the Employee Object. We can use NBuilder like the following.

 var employee = Builder<Employee>
                .CreateNew()
                .Build();   

NBuilder follows Fluent Interfacing to work with its methods. It uses the Builder Pattern for creating a builder class. This builder class is responsible for creating a particular type of object (Employee in our case) via the fluent interface.

The CreateNew() method returns a ISingleObjectBuilder ensuring that only one object is return.

Finally, the Build() method that keeps track of the desired state of the object being built by actually building the object.

The desired result is as under

Generating a collection of data for the Employee Object

Now suppose we want to generate a collection of data for the Employee Object. We can use NBuilder like the following.

var employees = Builder<Employee>
                .CreateListOfSize(10)
                .Build();

Here we are creating 10 test data for Employee Object. This is achieved by using the CreateListOfSize(int size) of NBuilder. This method returns IListBuilder.

The outout is as under

Builder<Employee>
                .CreateListOfSize(10)
                .Build()
                .ToList()
                .ForEach(i => Console.WriteLine($"EmployeeId = {i.EmployeeId}  EmployeeName = {i.EmployeeName} Email = {i.Email} Age = {i.Age}"));
 /* Result */

EmployeeId = 1  EmployeeName = EmployeeName1 Email = Email1 Age = 1
EmployeeId = 2  EmployeeName = EmployeeName2 Email = Email2 Age = 2
EmployeeId = 3  EmployeeName = EmployeeName3 Email = Email3 Age = 3
EmployeeId = 4  EmployeeName = EmployeeName4 Email = Email4 Age = 4
EmployeeId = 5  EmployeeName = EmployeeName5 Email = Email5 Age = 5
EmployeeId = 6  EmployeeName = EmployeeName6 Email = Email6 Age = 6
EmployeeId = 7  EmployeeName = EmployeeName7 Email = Email7 Age = 7
EmployeeId = 8  EmployeeName = EmployeeName8 Email = Email8 Age = 8
EmployeeId = 9  EmployeeName = EmployeeName9 Email = Email9 Age = 9
EmployeeId = 10  EmployeeName = EmployeeName10 Email = Email10 Age = 10

Customizing the value of Email and Gender Property for the Employee Object

Using NBuilder we can also customize the value of a property. In this example, we will describe how we can customize the Email and Gender property value of the Employee Object

using FizzWare.NBuilder;
using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        { 
            //Customizing the value of a field
            Builder<Employee>
                .CreateListOfSize(10)
                .All()                
                .With(w=>w.Email= GenerateEmailAddress())               
                .And(w=>w.Gender = GenerateGender())
                .Build()
                .ToList()
                .ForEach(i => Console.WriteLine($"EmployeeId = {i.EmployeeId}  EmployeeName = {i.EmployeeName} Email = {i.Email} Gender = {i.Gender}"));

            Console.ReadKey();
        }

        private static Random _random = new Random();
        public static string GenerateEmailAddress()
        {
           return $"{string.Join("", Enumerable.Repeat("abcdefABCDEF", 2).Select(s => s[_random.Next(s.Length)]))}@test.com";
        }

        public static string GenerateGender()
        {
            var gender = _random.Next(1, 9) % 2 == 0 ? "Male" : "Famale";
            return $"{gender}";
        }
    }
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
        public DateTime DOB { get; set; }
        public DateTime DOJ { get; set; }
        public string Address { get; set; }
        public decimal Salary { get; set; }
    }
}

/* Result */

EmployeeId = 1  EmployeeName = EmployeeName1 Email = bC@test.com Gender = Famale
EmployeeId = 2  EmployeeName = EmployeeName2 Email = Ad@test.com Gender = Famale
EmployeeId = 3  EmployeeName = EmployeeName3 Email = cb@test.com Gender = Male
EmployeeId = 4  EmployeeName = EmployeeName4 Email = BD@test.com Gender = Male
EmployeeId = 5  EmployeeName = EmployeeName5 Email = bB@test.com Gender = Famale
EmployeeId = 6  EmployeeName = EmployeeName6 Email = bc@test.com Gender = Male
EmployeeId = 7  EmployeeName = EmployeeName7 Email = Ce@test.com Gender = Famale
EmployeeId = 8  EmployeeName = EmployeeName8 Email = Bc@test.com Gender = Famale
EmployeeId = 9  EmployeeName = EmployeeName9 Email = CB@test.com Gender = Male
EmployeeId = 10  EmployeeName = EmployeeName10 Email = Fa@test.com Gender = Male

Reference

NBuilder tutorials

Conclusion

Nbuilder is used in the Arrange phase of Unit Testing. It's a great tool for data generation.Hope this will be helpful.Thanks for reading.Zipped file is attached herewith.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)