Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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
The above command will install NBuilder with all its dependencies.
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
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
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();
Dim customPersonBuilder = Builder(Of Person).CreateNew().With(Sub(p) p.Name = "Tom").With(Sub(p) p.Email = "Tom@email.com")
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.
var personList = Builder<Person>
.CreateListOfSize(10)
.Build();
var personList = Builder<Person>
.CreateListOfSize(10)
.Build();
IRON VB CONVERTER ERROR developers@ironsoftware.com
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
Sometimes you may need to customize objects being created. You can also customize the value of an object by using the 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,
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()
' 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,
This creates a personList with its default value as Name = “Kim”, Email = “abc@email.com”, and IsMarried = false.
In order to get realistic data values in Person List, you can use the 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
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
Here, the All() method is applied to subsequent operations to all 10 person objects and creates a list in memory. The Do() method is used to execute the Action Delegate on each Person object.
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 objects respectively. By adding the i value in the Id property, the properties are sequentially set from 501 to 510, and the Name property will be set to 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.
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 Class Person has the following properties, and PersonService has only one public method GetPersonEmail() that returns the Person email of that particular object.
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);
}
}
Public Class PersonTests
<Fact>
Public Sub GetPersonEmail_ReturnCorrectEmail()
' Arrange
Dim service = New PersonService()
Dim expectedEmail As String = "Tom@email.com"
Dim person = Builder(Of Person).CreateNew().With(Sub(p) p.Name = "Tom").With(Function(p) p.Email "Tom@email.com").Build()
' Act
Dim actualEmail = service.GetPersonEmailById(person)
' Assert
Assert.Equal(actualEmail, expectedEmail)
End Sub
End Class
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.
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.
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
// 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()
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>";
}
IronPdf.License.LicenseKey = "Your-License-Key"
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.
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");
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".
Below is the output of the PersonList generated by IronPDF. It contains five persons, each with default values.
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.
9 .NET API products for your office documents