Zum Fußzeileninhalt springen
.NET HILFE

NBuilder .NET (Funktionsweise für Entwickler)

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.

Häufig gestellte Fragen

Wie kann ich Testdaten mit NBuilder in .NET generieren?

NBuilder bietet eine Fluent-Schnittstelle, die es Entwicklern ermöglicht, komplexe Objektgrafen und Testdaten mühelos zu generieren. Sie können Methoden wie CreateNew() und CreateListOfSize() verwenden, um einzelne Objekte oder Listen von Objekten mit Standard- oder benutzerdefinierten Werten zu erstellen.

Wie installiere ich NBuilder in einem .NET-Projekt?

Um NBuilder zu installieren, können Sie die NuGet-Paket-Manager-Konsole mit dem Befehl Install-Package NBuilder verwenden. Dadurch werden NBuilder und seine erforderlichen Abhängigkeiten heruntergeladen und installiert.

Kann NBuilder verwendet werden, um zufällige und sequenzielle Daten zu generieren?

Ja, NBuilder unterstützt die Generierung sowohl zufälliger als auch sequenzieller Daten. Sie können Objekt-Eigenschaften mit Methoden wie With() für zufällige Werte anpassen oder Do() verwenden, um Eigenschaften sequenziell festzulegen.

Welche Vorteile hat die Integration von NBuilder mit IronPDF?

Die Integration von NBuilder mit IronPDF ermöglicht es Entwicklern, komplexe Testdaten zu erstellen und als PDFs auszugeben. Dies kann .NET-Anwendungen erweitern, indem es die dynamische PDF-Generierung aus Testdaten ermöglicht und Entwicklungs-Workflows optimiert.

Wie unterstützt NBuilder beim Unit-Testen?

NBuilder ist wertvoll beim Unit-Testen, da es Entwicklern ermöglicht, schnell realistische Testdaten zu generieren. Es vereinfacht die Einrichtung von Testszenarien mit komplexen Objektgrafen, wodurch Tests wartbarer und effektiver werden.

Was ist der Vorteil der Verwendung einer Fluent-Schnittstelle in NBuilder?

Die Fluent-Schnittstelle in NBuilder ermöglicht es Entwicklern, Methodenaufrufe für die Erstellung komplexer Objektgrafen auf eine lesbare und prägnante Weise zu verketten. Dies verbessert die Codeklarheit und reduziert Boilerplate-Code bei der Testdatengenerierung.

Wie kann ich eine Liste von Objekten mit NBuilder erstellen?

Sie können eine Liste von Objekten mit der CreateListOfSize()-Methode von NBuilder erstellen. Zum Beispiel generiert Builder.CreateListOfSize(10).Build() eine Liste von 10 Person-Objekten.

Was sind einige Tipps zur Fehlerbehebung bei der Verwendung von NBuilder?

Stellen Sie sicher, dass NBuilder korrekt über NuGet installiert ist und überprüfen Sie, ob Ihre Projektverweise auf dem neuesten Stand sind. Wenn Sie auf Probleme stoßen, kann ein Blick ins NBuilder GitHub-Repository oder in die Community-Foren hilfreiche Einblicke und Lösungen liefern.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen