푸터 콘텐츠로 바로가기
.NET 도움말

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; }
}
$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
$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();
$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();
$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}");
}
$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();
$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();
$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();
$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;
    }
}
$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);
     }
}
$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();
$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>";
}
$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");
$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.

자주 묻는 질문

.NET에서 NBuilder를 사용하여 테스트 데이터를 생성하려면 어떻게 해야 하나요?

NBuilder는 개발자가 복잡한 개체 그래프를 생성하고 데이터를 손쉽게 테스트할 수 있는 유창한 인터페이스를 제공합니다. CreateNew()CreateListOfSize()와 같은 메서드를 사용하여 단일 개체 또는 기본값 또는 사용자 지정 값을 가진 개체 목록을 생성할 수 있습니다.

.NET 프로젝트에 NBuilder를 설치하려면 어떻게 해야 하나요?

NBuilder를 설치하려면 다음 명령과 함께 NuGet 패키지 관리자 콘솔을 사용하면 됩니다: Install-Package NBuilder. 그러면 필요한 종속 요소와 함께 NBuilder가 다운로드 및 설치됩니다.

무작위 및 순차 데이터를 생성하는 데 NBuilder를 사용할 수 있나요?

예, NBuilder는 임의 및 순차 데이터 생성을 모두 지원합니다. 임의 값의 경우 With()와 같은 메서드를 사용하여 객체 속성을 사용자 지정하거나 Do()를 사용하여 속성을 순차적으로 설정할 수 있습니다.

NBuilder와 IronPDF를 통합하면 어떤 이점이 있나요?

NBuilder와 IronPDF를 통합하면 개발자가 복잡한 테스트 데이터를 생성하고 이를 PDF로 출력할 수 있습니다. 이를 통해 테스트 데이터에서 동적 PDF를 생성하여 개발 워크플로를 간소화함으로써 .NET 애플리케이션을 향상시킬 수 있습니다.

NBuilder는 단위 테스트를 어떻게 지원하나요?

NBuilder는 개발자가 사실적인 테스트 데이터를 빠르게 생성할 수 있어 단위 테스트에서 유용합니다. 복잡한 개체 그래프로 테스트 시나리오 설정을 간소화하여 테스트의 유지 관리와 효율성을 높여줍니다.

NBuilder에서 유창한 인터페이스를 사용하면 어떤 이점이 있나요?

NBuilder의 유창한 인터페이스를 통해 개발자는 복잡한 개체 그래프를 읽기 쉽고 간결하게 생성하기 위해 메서드 호출을 연결할 수 있습니다. 이를 통해 코드 명확성이 향상되고 테스트 데이터를 생성할 때 상용구 코드가 줄어듭니다.

NBuilder로 개체 목록을 만들려면 어떻게 해야 하나요?

NBuilder의 CreateListOfSize() 메서드를 사용하여 개체 목록을 만들 수 있습니다. 예를 들어, Builder.CreateListOfSize(10).Build()는 10개의 Person 오브젝트 목록을 생성합니다.

NBuilder 사용에 대한 문제 해결 팁은 무엇인가요?

NuGet을 통해 NBuilder가 올바르게 설치되었는지 확인하고 프로젝트 참조가 최신 상태인지 확인하세요. 문제가 발생하면 NBuilder GitHub 리포지토리 또는 커뮤니티 포럼을 확인하면 유용한 인사이트와 해결책을 얻을 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.