Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
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.
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();
IRON VB CONVERTER ERROR developers@ironsoftware.com
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 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
This creates a personList with its default value as Name = “Kim”, Email = “abc@email.com”, and IsMarried = false.
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
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 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.
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.
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
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);
}
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
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.
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.
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();
IRON VB CONVERTER ERROR developers@ironsoftware.com
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
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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
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 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