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.
Features of NBuilder
- 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.
- It is especially useful for unit testing, functional testing, and integration testing.
- It is one of the essential packages for testing built-in .NET data types and complex objects.
- It is used for random data generation. You can contribute to this open-source project.
- 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.
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
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
Sample Image
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()
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()
Sample Image
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
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()
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()
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()
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".
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
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
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.
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()
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
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")
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.
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
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.