Skip to footer content
.NET HELP

NBuilder .NET (How It Works For Developers)

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.

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; }
}
class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public bool IsMarried { get; set; }
}
Friend Class Person
	Public Property Id() As Integer
	Public Property Name() As String
	Public Property Email() As String
	Public Property IsMarried() As Boolean
End Class
$vbLabelText   $csharpLabel

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
// 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
' Create a new person object with default values using NBuilder
Dim person = Builder(Of Person) .CreateNew().Build()
' By default, NBuilder can provide values like 
' Id = 1, Name = Name1, Email = Email1, IsMarried = false
$vbLabelText   $csharpLabel

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();
// 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();
' Initialize a custom builder for the Person object with specific values
Dim customPersonBuilder = Builder(Of Person).CreateNew().With(Sub(p) p.Name = "Tom").With(Sub(p) p.Email = "Tom@email.com")
' Build the custom person object with the specified properties
Dim objTom = customPersonBuilder.Build()
$vbLabelText   $csharpLabel

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();
// Create a list of 10 Person objects with default values using NBuilder
var personList = Builder<Person>
                                     .CreateListOfSize(10)
                                     .Build();
' Create a list of 10 Person objects with default values using NBuilder
Dim personList = Builder(Of Person) .CreateListOfSize(10).Build()
$vbLabelText   $csharpLabel

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}");
}
// 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}");
}
' Creating a list of 10 Person objects with default values
Dim personList = Builder(Of Person) .CreateListOfSize(10).Build()

' Print details of each Person object in the list
For Each person In personList
	Console.WriteLine($"{person.Id}, {person.Name}, {person.Email}, {person.IsMarried}")
Next person
$vbLabelText   $csharpLabel

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

Example 4: Customising 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();
// 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();
' Customize properties for all Person objects in the list
Dim personList = Builder(Of Person) .CreateListOfSize(10).All().With(Sub(p) p.Name = "Kim").With(Sub(p) p.Email = "abc@email.com").With(Sub(p) p.IsMarried = False).Build()
$vbLabelText   $csharpLabel

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();
// 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();
' Creating a list of Person objects with random yet realistic values using Faker
Dim personList = Builder(Of Person) .CreateListOfSize(10).All().With(Sub(p) p.Name = Faker.Name.FullName()).With(Sub(p) p.Id = Faker.RandomNumber.Next(20, 60)).Build()
$vbLabelText   $csharpLabel

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();
// 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();
' Creating a list of 10 sequential Person objects using NBuilder
Dim personList = Builder(Of Person).CreateListOfSize(10).All().Do(Sub(p, i) p.Id = 501 + i).Do(Sub(p, i) p.Name = $"Person {i + 1}").Build()
$vbLabelText   $csharpLabel

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;
    }
}
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;
    }
}
Friend Class Person
	Public Property Id() As Integer
	Public Property Name() As String
	Public Property Email() As String
	Public Property IsMarried() As Boolean
End Class

Friend Class PersonService
	Public Function GetPersonEmail(ByVal person As Person) As String
		Return person.Email
	End Function
End Class
$vbLabelText   $csharpLabel

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);
     }
}
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);
     }
}
Imports Xunit

Public Class PersonTests
	 <Fact>
	 Public Sub GetPersonEmail_ReturnCorrectEmail()
		 ' Arrange
		 Dim service = New PersonService()
		 Dim expectedEmail As String = "Tom@email.com"

		 ' Create a person with specific name and email using NBuilder
		 Dim person = Builder(Of Person).CreateNew().With(Sub(p) p.Name = "Tom").With(Sub(p) p.Email = "Tom@email.com").Build()

		 ' Act
		 Dim actualEmail = service.GetPersonEmail(person)

		 ' Assert
		 Assert.Equal(expectedEmail, actualEmail)
	 End Sub
End Class
$vbLabelText   $csharpLabel

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:

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();
// Generating instances of the Person class with NBuilder
var people = Builder<Person>.CreateListOfSize(5).Build();
' Generating instances of the Person class with NBuilder
Dim people = Builder(Of Person).CreateListOfSize(5).Build()
$vbLabelText   $csharpLabel

Creation 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>";
}
// 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>";
}
' Setting the IronPDF license key
IronPdf.License.LicenseKey = "Your-License-Key"

' Building HTML content from Person object list
Dim htmlContent = "<h1>Person List</h1>"
For Each person In people
	htmlContent &= $"<p>Id: {person.Id}, Name: {person.Name}, Email: {person.Email}, IsMarried: {person.IsMarried}</p>"
Next person
$vbLabelText   $csharpLabel

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");
// Rendering HTML content into a PDF document using IronPDF
var renderer = new ChromePdfRenderer();
var pdfDoc = renderer.RenderHtmlAsPdf(htmlContent);
pdfDoc.SaveAs("PersonList.pdf");
' Rendering HTML content into a PDF document using IronPDF
Dim renderer = New ChromePdfRenderer()
Dim pdfDoc = renderer.RenderHtmlAsPdf(htmlContent)
pdfDoc.SaveAs("PersonList.pdf")
$vbLabelText   $csharpLabel

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.

Frequently Asked Questions

What is NBuilder in .NET?

NBuilder is a .NET library designed to simplify test data generation. It allows developers to create complex object graphs effortlessly using a fluent interface.

How can NBuilder help in testing?

NBuilder is particularly useful for unit testing, functional testing, and integration testing. It facilitates the quick generation of objects with customizable properties, making it easier to test complex scenarios.

How do you install NBuilder?

To install NBuilder, use the NuGet Package Manager Console command: 'Install-Package NBuilder'. This will install NBuilder along with its dependencies.

Can NBuilder generate random data?

Yes, NBuilder supports random data generation and allows developers to override default properties and write custom configurations.

How can I customize object properties with NBuilder?

You can customize object properties using the 'With()' method in NBuilder, which allows you to specify custom values for object properties during creation.

What is an example of creating a single object with NBuilder?

An example in C# is using 'Builder.CreateNew().Build()' to create a new Person object with default values like Id = 1, Name = Name1, etc.

Can NBuilder generate a list of objects?

Yes, NBuilder can create a list of objects using methods like 'CreateListOfSize(10)' which generates a list of 10 objects with default or specified values.

How can NBuilder be integrated with other libraries?

NBuilder can be integrated with libraries like IronPDF to enhance .NET applications, such as generating PDFs from dynamically created data.

How can NBuilder be used in unit testing?

NBuilder can generate realistic test data for unit testing, making it easy to test various scenarios with complex objects by defining custom initialization logic.

What is an example of generating sequential data with NBuilder?

NBuilder can generate sequential data by using methods like 'Do()', which allows setting properties in a sequence, such as assigning incremental Ids to a list of objects.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.