IRONSOFTWAREHOME
.NET HELP

NBuilder .NET (How It Works For Developers)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: August 1, 2026

NBuilder is 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. NBuilder is a C# open source .NET library designed to simplify the creation of objects for testing and mocking purposes. It allows developers to 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 properties and write custom configurations.

Installing NBuilder

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

PM > Install-Package NBuilder

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; }
}

Example 1: Creating a Person Object with Default Values

// Create a new person object with default values using NBuilder
var person = Builder<Person>
                .CreateNew()
                .Build();
// By default, NBuilder can provide values like 
// Id = 1, Name = Name1, Email = Email1, IsMarried = false

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:

// Initialize a custom builder for the Person object with specific values
var customPersonBuilder = Builder<Person>.CreateNew()
                .With(p => p.Name = "Tom")
                .With(p => p.Email = "Tom@email.com");
// Build the custom person object with the specified properties
var objTom = customPersonBuilder.Build();

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

// Create a list of 10 Person objects with default values using NBuilder
var personList = Builder<Person>
                                     .CreateListOfSize(10)
                                     .Build();

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.

// Creating a list of 10 Person objects with default values
var personList = Builder<Person>
                                            .CreateListOfSize(10)
                                            .Build();

// Print details of each Person object in the list
foreach (var person in personList)
{
    Console.WriteLine($"{person.Id}, {person.Name}, {person.Email}, {person.IsMarried}");
}

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

Example 4: Customizing Generated Objects

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

// Customize properties for all Person objects in the list
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();

This creates a personList with each object having its default value overridden to Name = "Kim", Email = "abc@email.com", and IsMarried = false.

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

In order to get realistic data values in the Person List, you can use the Faker Library .NET to generate realistic data.

// Creating a list of Person objects with random yet realistic values using Faker
var personList = Builder<Person>
                .CreateListOfSize(10)
                .All()
                .With(p => p.Name = Faker.Name.FullName())
                .With(p => p.Id = Faker.RandomNumber.Next(20, 60))
                .Build();

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.

// Creating a list of 10 sequential Person objects using NBuilder
var personList = Builder<Person>.CreateListOfSize(10)
                .All()
                .Do((p, i) => p.Id = 501 + i)
                .Do((p, i) => p.Name = $"Person {i + 1}")
                .Build();

Here, the All() method ensures the subsequent operations apply to all 10 person objects created in memory. The Do() method executes the Action delegate on each Person object. This setup assigns the Id property sequentially starting from 501, and similarly, names each person sequentially as "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 a realistic and diverse set of data for testing. It makes testing easy and maintainable with complex objects that allow developers to define custom initialization logic using lambda expressions and delegate 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;
    }
}

Here, the Person class has several properties such as Id, Name, Email, and IsMarried, while PersonService contains a method GetPersonEmail() that returns the email of a given Person.

Test Classes and Test data

using Xunit;

public class PersonTests
{
     [Fact]
     public void GetPersonEmail_ReturnCorrectEmail()
     {
         // Arrange
         var service = new PersonService();
         string expectedEmail = "Tom@email.com";
         
         // Create a person with specific name and email using NBuilder
         var person = Builder<Person>.CreateNew()
             .With(p => p.Name = "Tom")
             .With(p => p.Email = "Tom@email.com")
             .Build();
         
         // Act
         var actualEmail = service.GetPersonEmail(person);
         
         // Assert
         Assert.Equal(expectedEmail, actualEmail);
     }
}

This unit test verifies that the GetPersonEmail 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

Learn About IronPDF is a powerful C# library designed for creating PDFs from HTML 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:

PM > Install-Package IronPdf

Populate the list of 5 Person objects

// Generating instances of the Person class with NBuilder
var people = Builder<Person>.CreateListOfSize(5).Build();

Creating PDF Document using IronPDF

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

// Setting the IronPDF license key
IronPdf.License.LicenseKey = "Your-License-Key";

// Building HTML content from Person object list
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>";
}

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.

// Rendering HTML content into a PDF document using IronPDF
var renderer = new ChromePdfRenderer();
var pdfDoc = renderer.RenderHtmlAsPdf(htmlContent);
pdfDoc.SaveAs("PersonList.pdf");

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 capabilities 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.

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required