Saltar al pie de página
.NET AYUDA

Aplicación de consola de prueba C# (Cómo funciona para desarrolladores)

Testing plays a pivotal role in the realm of software development, serving as a crucial element in guaranteeing the quality of applications. Among the plethora of frameworks available, .NET stands out as a widely embraced choice for crafting Windows-based applications. This article delves into the intricacies of .NET TestConsole, a tool specifically designed for testing .NET applications.

Throughout this exploration, we will write a comprehensive code example illustrating the practical implementation of .NET TestConsole. Additionally, we will shed light on IronPDF, an exemplary C# PDF library seamlessly integrated with .NET TestConsole. This library proves to be invaluable, empowering developers to effortlessly access and generate PDFs within the .NET TestConsole environment. Join us on this journey as we unravel the functionalities and possibilities that arise from the synergy of .NET TestConsole and IronPDF's C# PDF Functionality.

1. Introduction: TestConsole

TestConsole is a versatile testing library that introduces a distinctive approach to unit tests in the C# programming language. Traditional methods of unit tests often face challenges when dealing with large datasets and complex assertions, leading to difficulties in identifying differences between expected and actual results. In response to this, TestConsole provides a novel workflow, shifting from the conventional prediction-based approach to a side-by-side comparison of formatted output with a designated "approved" standard output version.

In this library, particularly with the TestConsole, the '.Core' variant extends the formatting capabilities inherited from the original TestConsole project and incorporates essential test approval features in scenarios where test results diverge from expectations. TestConsole.Core seamlessly integrates with the build server to trigger a test failure. On the development PC, by default, it offers reconfigurability to utilize installed file compare utilities for visualizing differences. Notably, this approach streamlines the approval process, allowing developers to update the approved version manually if differences are expected.

1.1. Why use TestConsole?

TestConsole.Core draws inspiration from ApprovalTests but distinguishes itself by providing support for writing both full framework and .NET Core test suites. The library addresses the need for testing in diverse environments, as with ApprovalTests at the time of publication, primarily catered to full framework scenarios. The syntax in TestConsole.Core, while sharing similarities with ApprovalTests, offers distinctions, especially concerning file compare tool selection and direct approval of content.

Developed to facilitate testing in .NET Core app code, TestConsole.Core arises from the necessity to bridge the gap left by the lack of .NET standard and .NET Core app support in ApprovalTests. With a focus on enabling effective testing of large datasets, TestConsole.Core's test approval features accommodate data formatted using the Test Console Output object and extend their functionality to handle any plain text input, providing a comprehensive solution for unit testing in C#.

1.2. Install TestConsole C#

The test console can be installed using the NuGet package Manager from inside Visual Studio, or by running the following command in the NuGet package manager Console.

Install-Package TestConsole -Version 2.6.0

Or download directly from the TestConsole distribution on NuGet.

2. Code Example of TestConsole

In this section, we will see how you can convert console outputs to reports. The below source code uses a test console to convert Enumerable objects into a well-formatted report table.

using TestConsoleLib;
using System;
using System.Linq;

// Instantiate the output class from TestConsoleLib
var output = new Output();

// Generate a collection of anonymous objects containing value, square, and string length
var data = Enumerable.Range(0, 10)
    .Select(i => new { Value = i, Squared = i * i, String = new string('I', i) });

// Format the data into a table using TestConsoleLib's method
output.FormatTable(data);

// Retrieve the formatted report as a string
string report = output.Report;

// Print the formatted report to console
Console.WriteLine(report);
using TestConsoleLib;
using System;
using System.Linq;

// Instantiate the output class from TestConsoleLib
var output = new Output();

// Generate a collection of anonymous objects containing value, square, and string length
var data = Enumerable.Range(0, 10)
    .Select(i => new { Value = i, Squared = i * i, String = new string('I', i) });

// Format the data into a table using TestConsoleLib's method
output.FormatTable(data);

// Retrieve the formatted report as a string
string report = output.Report;

// Print the formatted report to console
Console.WriteLine(report);
Imports TestConsoleLib
Imports System
Imports System.Linq

' Instantiate the output class from TestConsoleLib
Private output = New Output()

' Generate a collection of anonymous objects containing value, square, and string length
Private data = Enumerable.Range(0, 10).Select(Function(i) New With {
	Key .Value = i,
	Key .Squared = i * i,
	Key .String = New String("I"c, i)
})

' Format the data into a table using TestConsoleLib's method
output.FormatTable(data)

' Retrieve the formatted report as a string
Dim report As String = output.Report

' Print the formatted report to console
Console.WriteLine(report)
$vbLabelText   $csharpLabel

This C# code snippet utilizes the TestConsoleLib library to demonstrate and run a simple example of formatting and reporting tabular data using TestConsole's Output class. It begins by creating an instance of the Output class named output. Subsequently, it generates a collection of 10 elements containing anonymous objects with properties representing an integer value, its square, and a string of 'I's whose length corresponds to the integer value.

The output.FormatTable() method is then invoked to format the data into a table. The formatted result is stored in the report string variable, which is finally printed to the console using Console.WriteLine(). This showcases TestConsole's capability and ability to easily format and present tabular data for improved readability during unit testing or debugging scenarios.

2.1. Output

Test Console Application C# (How It Works For Developer): Figure 1 - Output of previous code

3. IronPDF

IronPDF's Official Website offers a comprehensive platform for a robust C# PDF library designed to simplify and enhance the process of working with PDF documents in .NET applications. Offering a comprehensive set of features, IronPDF empowers developers to effortlessly create, manipulate, and extract content from PDF files within their C# projects. With a focus on flexibility and ease of use, IronPDF supports a wide range of functionalities, including the generation of PDFs from HTML, images, or existing documents, as well as the incorporation of dynamic content, such as charts and tables.

Its capabilities extend to the merging, splitting, and manipulation of PDF pages, as well as functions such as the extraction of text and images. Whether for reporting, documentation, or any PDF-related task, IronPDF stands out as a reliable and versatile solution, streamlining the integration of PDF functionality into C# applications with minimal effort.

3.1. Creating PDF Files of Test Console Reports

In this section, we will discuss how you can convert the output from TestConsole reports.

Get started with IronPDF


Install IronPDF Library

Install Using NuGet Package Manager

To integrate IronPDF into your Console project using the NuGet Package manager, follow these steps:

  1. Open Visual Studio and in the solution explorer, right-click on your project.
  2. Choose “Manage NuGet packages…” from the context menu.
  3. Go to the browse tab and search IronPDF.
  4. Select IronPDF library from the search results and click the install button.
  5. Accept any license agreement prompt.

If you want to include IronPDF in your project via Package Manager console, then execute the following command in Package Manager Console:

Install-Package IronPdf

It’ll fetch and install IronPDF into your project.

Install Using NuGet Website

For a detailed overview of IronPDF, including its features, compatibility, and additional download options, visit the IronPDF page on the NuGet website at https://www.nuget.org/packages/IronPdf.

Install Via DLL

Alternatively, you can incorporate IronPDF directly into your project using its DLL file. Download the ZIP file containing the DLL from this IronPDF ZIP Package. Unzip it, and include the DLL in your project.

Once installed, now we will recreate the above example report, but this time instead of writing it into the console, we will create a PDF report from it.

using TestConsole.OutputFormatting;
using TestConsoleLib;
using IronPdf;
using System;
using System.Linq;

// Instantiate the output class from TestConsoleLib
var output = new Output();

// Generate a collection of anonymous objects containing value, square, and string length
var data = Enumerable.Range(0, 10)
    .Select(i => new { Value = i, Squared = i * i, String = new string('I', i) });

// Format the data into a table and obtain the formatted output as a string
output.FormatTable(data);
string report = output.Report;

// Wrap the report in HTML pre-tags to maintain formatting
var htmlContent = $"<pre>{report}</pre>";

// Initialize IronPDF renderer and render the HTML content to PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save the PDF to a file
pdf.SaveAs("test.pdf");
using TestConsole.OutputFormatting;
using TestConsoleLib;
using IronPdf;
using System;
using System.Linq;

// Instantiate the output class from TestConsoleLib
var output = new Output();

// Generate a collection of anonymous objects containing value, square, and string length
var data = Enumerable.Range(0, 10)
    .Select(i => new { Value = i, Squared = i * i, String = new string('I', i) });

// Format the data into a table and obtain the formatted output as a string
output.FormatTable(data);
string report = output.Report;

// Wrap the report in HTML pre-tags to maintain formatting
var htmlContent = $"<pre>{report}</pre>";

// Initialize IronPDF renderer and render the HTML content to PDF
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save the PDF to a file
pdf.SaveAs("test.pdf");
Imports TestConsole.OutputFormatting
Imports TestConsoleLib
Imports IronPdf
Imports System
Imports System.Linq

' Instantiate the output class from TestConsoleLib
Private output = New Output()

' Generate a collection of anonymous objects containing value, square, and string length
Private data = Enumerable.Range(0, 10).Select(Function(i) New With {
	Key .Value = i,
	Key .Squared = i * i,
	Key .String = New String("I"c, i)
})

' Format the data into a table and obtain the formatted output as a string
output.FormatTable(data)
Dim report As String = output.Report

' Wrap the report in HTML pre-tags to maintain formatting
Dim htmlContent = $"<pre>{report}</pre>"

' Initialize IronPDF renderer and render the HTML content to PDF
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)

' Save the PDF to a file
pdf.SaveAs("test.pdf")
$vbLabelText   $csharpLabel

This C# code snippet showcases the integration of TestConsoleLib and IronPDF to generate a PDF document containing a formatted table of data. Initially, it creates an instance of the Output class from TestConsoleLib and formats a table using data generated from a range of integers. The formatted output is stored in the report string variable, which is then enclosed within HTML pre-tags to preserve the formatting.

Subsequently, the code utilizes the ChromePdfRenderer from IronPDF to render the HTML content as a PDF document. Finally, the resulting PDF is saved as "test.pdf." This code demonstrates the seamless combination of TestConsoleLib for formatting and IronPDF for PDF generation, providing a straightforward solution for incorporating formatted data into PDF documents within a C# application.

3.1.1. Output

Test Console Application C# (How It Works For Developer): Figure 2 - Output of previous code

4. Conclusion

The .NET TestConsole emerges as a pivotal testing library for C# applications, presenting a distinctive approach to unit testing that alleviates challenges associated with large datasets and complex assertions. The TestConsole.Core variant extends its utility across diverse environments, bridging gaps left by other frameworks and providing an efficient workflow for side-by-side comparisons of formatted outputs.

It integrates seamlessly with IronPDF, a robust C# library, and not only facilitates streamlined testing but also extends its capabilities to PDF generation and manipulation. Together, these tools empower developers to effortlessly handle testing intricacies and enhance document generation in their C# projects, offering a comprehensive and efficient solution.

The detailed and complete tutorial on IronPDF HTML to PDF conversion can be found in the IronPDF Tutorial Guide.

Preguntas Frecuentes

¿Cómo puedo crear una aplicación de consola en C#?

Para crear una aplicación de consola en C#, puede utilizar Visual Studio para iniciar un nuevo proyecto y seleccionar 'Aplicación de Consola' como el tipo de proyecto. Luego, escriba su código C# dentro del método Main para ejecutar la lógica de su aplicación.

¿Cuál es el propósito de .NET TestConsole?

.NET TestConsole está diseñado para probar aplicaciones .NET proporcionando un flujo de trabajo único que involucra la comparación lado a lado de salidas formateadas contra estándares aprobados, mejorando la eficiencia del proceso de pruebas.

¿Cómo puedo convertir las salidas de aplicaciones de consola a PDF en C#?

Puede usar IronPDF para convertir las salidas de aplicaciones de consola a PDF en C#. Primero, capture la salida de la consola como una cadena HTML formateada, luego use el método RenderHtmlAsPdf de IronPDF para crear un PDF a partir del contenido HTML.

¿Cuáles son los beneficios de usar una biblioteca PDF en aplicaciones C#?

El uso de una biblioteca PDF como IronPDF en aplicaciones C# permite a los desarrolladores generar, modificar y extraer contenido de archivos PDF, habilitando funciones tales como la creación de PDF desde contenido HTML, la incorporación de datos dinámicos, y más.

¿Cómo funciona la comparación de salidas lado a lado en .NET TestConsole?

La comparación de salidas lado a lado en .NET TestConsole implica comparar la salida formateada de su aplicación con un estándar preaprobado, permitiendo a los desarrolladores identificar discrepancias y asegurar la precisión en los resultados de las pruebas.

¿Puede .NET TestConsole usarse con .NET Core?

Sí, .NET TestConsole puede usarse tanto con el marco completo como con .NET Core, proporcionando flexibilidad y compatibilidad en diferentes entornos .NET para probar aplicaciones.

¿Cómo puedo integrar una biblioteca PDF en mi proyecto .NET?

Para integrar una biblioteca PDF como IronPDF en su proyecto .NET, puede usar el administrador de paquetes NuGet en Visual Studio para instalarla, o descargar el DLL de la biblioteca y agregarlo a las referencias de su proyecto.

¿Cuál es la ventaja de usar una biblioteca de pruebas en el desarrollo de software?

Una biblioteca de pruebas, como .NET TestConsole, agiliza el proceso de pruebas al automatizar las aprobaciones de prueba, facilitar comparaciones de salidas lado a lado eficientemente y mejorar la gestión general de las pruebas, llevando a una calidad de software mejorada.

¿Cómo manejas conjuntos de datos grandes con .NET TestConsole?

.NET TestConsole está equipada para manejar conjuntos de datos grandes de manera efectiva utilizando un enfoque de comparación que simplifica las aserciones complejas y asegura una prueba precisa de amplias salidas de datos.

¿Dónde puedo encontrar más información sobre el uso de IronPDF?

Más información sobre el uso de IronPDF se puede encontrar en el sitio web oficial de IronPDF, que proporciona guías completas, tutoriales y documentación para integrar y utilizar IronPDF en proyectos C#.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más