.NET HELP

NBuilder .NET (How It Works For Developers)

Published August 13, 2024
Share:

NBuilderis a .NET library simplifying test data generation. Developers can create complex object graphs effortlessly with its fluent interface. It offers flexibility, efficiency, and seamless integration with popular testing frameworks. In this article, we will explore the features of NBuilder, how to install it, and demonstrate its capabilities with practical code examples.

NBuilder .NET (How It Works For Developers): Figure 1 - NBuilder

Features of NBuilder

  1. NBuilderis a C# open source .NET library designed to simplify the creation of objects for testing and mocking purposes. It lets developers quickly generate objects with default or custom-specified inputs based on different data types.
  2. It is especially useful for unit testing, functional testing,and integration testing.
  3. It is one of the essential packages for testing built-in .NET data types and complex objects.
  4. It is used for random data generation. You can contribute to this open-source project.
  5. With NBuilder, you can effortlessly override default property and write custom configurations.

Installing NBuilder

To install NBuilder in the NuGet Package Manager Console, use the following command.

Install-Package Nbuilder
Install-Package Nbuilder
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

The above command will install NBuilder with all its dependencies.

NBuilder .NET (How It Works For Developers): Figure 2 - Install NBuilder

Usage of NBuilder

NBuilder provides a fluent way for creating objects on the fly. Let’s start with a simple example of creating an object.

Here is the Person Model Class source code.

class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public bool IsMarried { get; set; }
    }
class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public bool IsMarried { get; set; }
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Example 1: Creating a Person Object with Default Values

var person = Builder<Person>
                .CreateNew()
                .Build();
       //person = { Id = 1, Name = Name1, Email = Email1 , IsMarried  = false }
var person = Builder<Person>
                .CreateNew()
                .Build();
       //person = { Id = 1, Name = Name1, Email = Email1 , IsMarried  = false }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Sample Image

NBuilder .NET (How It Works For Developers): Figure 3 - Person object with values

Example 2: Creating Objects with a Custom Builder

Here is an example of how to use NBuilder to create and configure a Person object with custom properties:

var customPersonBuilder = Builder<Person>.CreateNew()
                .With(p => p.Name = "Tom")
                .With(p => p.Email = "Tom@email.com");
            var objTom = customPersonBuilder.Build();
var customPersonBuilder = Builder<Person>.CreateNew()
                .With(p => p.Name = "Tom")
                .With(p => p.Email = "Tom@email.com");
            var objTom = customPersonBuilder.Build();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

The above code creates a new Person object with custom properties. It initializes a customPersonBuilder for a Person object, setting the Name to "Tom" and the Email to "Tom@email.com". Finally, it builds the object and assigns it to objTom.

Example 3: Creating a Person Object List with Default Value

var personList = Builder<Person>
                                     .CreateListOfSize(10)
                                     .Build();
var personList = Builder<Person>
                                     .CreateListOfSize(10)
                                     .Build();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Sample Image

NBuilder .NET (How It Works For Developers): Figure 4 - Person object list

Here personList has 10 objects with their default values and prints them.

var personList = Builder<Person>
                                            .CreateListOfSize(10)
                                            .Build();
            // Here it creates the 10 objects of Person in personList
            foreach (var person in personList)
            {
       Console.WriteLine($"{person.Id}, {person.Name}, {person.Email}, {person.IsMarried}, ");
            }
var personList = Builder<Person>
                                            .CreateListOfSize(10)
                                            .Build();
            // Here it creates the 10 objects of Person in personList
            foreach (var person in personList)
            {
       Console.WriteLine($"{person.Id}, {person.Name}, {person.Email}, {person.IsMarried}, ");
            }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

NBuilder .NET (How It Works For Developers): Figure 5 - Automatically assigning values

Example 4: Customising Generated Objects

Sometimes you may need to customize object being created. You can also customize value of object by using with() method.

var personList = Builder<Person>
                .CreateListOfSize(10)
                .All()
                .With(p => p.Name = "Kim")
                .With(p => p.Email = "abc@email.com")
                .With(p => p.IsMarried = false)
                .Build();
            // Output:  
            //    Id:  1, Name: Name1, Email: Email1, IsMarried False,
            //    Id : 2, Name: Name2, Email: Email2, IsMarried True,
            //    Id : 3, Name: Name3, Email: Email3, IsMarried False,
            //    Id : 4, Name: Name4, Email: Email4, IsMarried True,
            //    Id : 5, Name: Name5, Email: Email5, IsMarried False,
            //    Id : 6, Name: Name6, Email: Email6, IsMarried True,
            //    Id : 7, Name: Name7, Email: Email7, IsMarried False,
            //    Id : 8, Name: Name8, Email: Email8, IsMarried True,
            //    Id : 9, Name: Name9, Email: Email9, IsMarried False,
            //    Id : 10, Name: Name10, Email: Email10, IsMarried True,
var personList = Builder<Person>
                .CreateListOfSize(10)
                .All()
                .With(p => p.Name = "Kim")
                .With(p => p.Email = "abc@email.com")
                .With(p => p.IsMarried = false)
                .Build();
            // Output:  
            //    Id:  1, Name: Name1, Email: Email1, IsMarried False,
            //    Id : 2, Name: Name2, Email: Email2, IsMarried True,
            //    Id : 3, Name: Name3, Email: Email3, IsMarried False,
            //    Id : 4, Name: Name4, Email: Email4, IsMarried True,
            //    Id : 5, Name: Name5, Email: Email5, IsMarried False,
            //    Id : 6, Name: Name6, Email: Email6, IsMarried True,
            //    Id : 7, Name: Name7, Email: Email7, IsMarried False,
            //    Id : 8, Name: Name8, Email: Email8, IsMarried True,
            //    Id : 9, Name: Name9, Email: Email9, IsMarried False,
            //    Id : 10, Name: Name10, Email: Email10, IsMarried True,
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

This creates a personList with its default value as Name = “Kim”, Email = “abc@email.com”, and IsMarried = false.

Example 5: Creating a Person Object List with Realistic Random Data

In order to get the realistic data value in Person List, you can use Faker Library .NET to get the real value of the data

var personList = Builder<Person>
                .CreateListOfSize(10)
                .All()
                .With(p => p.Name = Faker.Name.FullName())
                .With(p => p.Id = Faker.RandomNumber.Next(20, 60))
                .Build();
var personList = Builder<Person>
                .CreateListOfSize(10)
                .All()
                .With(p => p.Name = Faker.Name.FullName())
                .With(p => p.Id = Faker.RandomNumber.Next(20, 60))
                .Build();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Example 6: Creating a Person Object List with Sequential Data

There are times when you might need to generate objects with sequential data. NBuilder .NET facilitates this using the Do method.

var personList = Builder<Person>.CreateListOfSize(10)
                .All()
                .Do((p, i) => p.Id = 501 + i)
                .Do((p, i) => p.Name = $"Person {i + 1}")
                .Build();
var personList = Builder<Person>.CreateListOfSize(10)
                .All()
                .Do((p, i) => p.Id = 501 + i)
                .Do((p, i) => p.Name = $"Person {i + 1}")
                .Build();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Here the All() method has applied the subsequent operations to all 10 person objects and created a list in memory. The Do() method is used to execute the Action Delegate on each Person object.

Here in this case it sets the Id Property of each person specified by 501. The lambda expressions (p, i) take two parameters p is the person and i is the index of that particular object in the list ranging from (0 to 9) as the list has 10 object respectively. By adding the i value in the Id property the properties are sequentially set to 501 to 510 and the Name property will be set to Person 1 to Person 10.

NBuilder .NET (How It Works For Developers): Figure 6 - Sequential Data

Example 7: NBuilder with Unit Testing using Xunit

NBuilder in .NET is significantly used in testing environments, where developers need to generate realistic and diverse set of data for testing. It makes testing easy and maintainable with complex objects that allow developers to define custom initialisation logic using lambda expression and delegates functions catering to those interested in efficient and flexible test data generation.

Model Class and Service for Unit Testing

class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public bool IsMarried { get; set; }
    }
    class PersonService
    {
        public string GetPersonEmail(Person person)
        {
            return person.Email;
        }
    }
class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public bool IsMarried { get; set; }
    }
    class PersonService
    {
        public string GetPersonEmail(Person person)
        {
            return person.Email;
        }
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Here the Class Person has the following properties and PersonService has only one public method GetPersonEmail() that returns the Person email of that particular object.

Test Classes and Test data

public class PersonTests
 {
     [Fact]
     public void GetPersonEmail_ReturnCorrectEmail()
     {
         // Arrange
         var service = new PersonService();
         string expectedEmail = "Tom@email.com";
         var person = Builder<Person>.CreateNew()
             .With(p => p.Name = "Tom")
             .With(p => p.Email "Tom@email.com")
             .Build();
         // Act
         var actualEmail = service.GetPersonEmailById(person);
         // Assert
         Assert.Equal(actualEmail,expectedEmail);
     }
 }
public class PersonTests
 {
     [Fact]
     public void GetPersonEmail_ReturnCorrectEmail()
     {
         // Arrange
         var service = new PersonService();
         string expectedEmail = "Tom@email.com";
         var person = Builder<Person>.CreateNew()
             .With(p => p.Name = "Tom")
             .With(p => p.Email "Tom@email.com")
             .Build();
         // Act
         var actualEmail = service.GetPersonEmailById(person);
         // Assert
         Assert.Equal(actualEmail,expectedEmail);
     }
 }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

This unit test verifies that the GetPersonEmailById method of the PersonService class correctly returns the email address of a Person object with the expected email "Tom@email.com". It uses the Arrange-Act-Assert pattern to set up the test data, execute the method, and then check that the actual result matches the expected result.

Integrating NBuilder with IronPDF

IronPDFis a powerful C# library designed for creating, editing, and processing PDF documents within .NET applications. With its intuitive API, developers can seamlessly integrate PDF functionality into their projects, whether they're generating invoices, reports, or interactive forms.

NBuilder .NET (How It Works For Developers): Figure 7 - IronPDF

Installing IronPDF

Open the NuGet Package Manager console, and run the following command:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

Populate the list of 5 Person objects

//  Generating instances of the Person class with NBuilder
        var people = Builder<Person>.CreateListOfSize(5).Build();
//  Generating instances of the Person class with NBuilder
        var people = Builder<Person>.CreateListOfSize(5).Build();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Creation PDF Document using IronPDF

This code sets the IronPDF license key and generates HTML content from a list of Person objects.

IronPdf.License.LicenseKey = "Your-License-Key";
    var htmlContent = "<h1>Person List</h1>";
        foreach (var person in people)
        {
            htmlContent += $"<p>Id: {person.Id}, Name: {person.Name}, Email: {person.Email}, IsMarried: {person.IsMarried}</p>";
    }
IronPdf.License.LicenseKey = "Your-License-Key";
    var htmlContent = "<h1>Person List</h1>";
        foreach (var person in people)
        {
            htmlContent += $"<p>Id: {person.Id}, Name: {person.Name}, Email: {person.Email}, IsMarried: {person.IsMarried}</p>";
    }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

The IronPdf.License.LicenseKey is set with a specific license key to enable the features of IronPDF.

HTML content is dynamically constructed by iterating over the people list, appending each Person object's details (Id, Name, Email, IsMarried) into the HTML structure.

Rendering the Person List in PDF Document Using IronPDF

This code converts HTML content to a PDF document using IronPDF's ChromePdfRenderer.

var renderer = new ChromePdfRenderer();
        var pdfDoc = renderer.RenderHtmlAsPdf(htmlContent);
        pdfDoc.SaveAs("PersonList.pdf");
var renderer = new ChromePdfRenderer();
        var pdfDoc = renderer.RenderHtmlAsPdf(htmlContent);
        pdfDoc.SaveAs("PersonList.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

ChromePdfRenderer is instantiated to render the HTML content stored in htmlContent into a PDF document. The resulting PDF document is saved to the file system with the name "PersonList.pdf".

Output

Below is the output of the PersonList generated by IronPDF. It contains five persons, each with default values.

NBuilder .NET (How It Works For Developers): Figure 8 - PDF Output

Conclusion

In conclusion, NBuilder is a robust and flexible tool for generating test data in .NET, streamlining the creation of complex object graphs, and enhancing the efficiency of testing processes. By integrating with IronPDF, developers can easily extend their applications to include PDF generation for those who find it valuable for their projects. Together, NBuilder and IronPDF can significantly enhance development workflows, making testing and document generation seamless and efficient.

< PREVIOUS
Refit C# (How It Works For Developers)
NEXT >
C# TryParse (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >