Przejdź do treści stopki
POMOC .NET

Aplikacja konsolowa C# (jak to działa dla programistów)

Testowanie odgrywa kluczową rolę w dziedzinie tworzenia oprogramowania, stanowiąc istotny element gwarantujący jakość aplikacji. Wśród mnóstwa dostępnych frameworków .NET Framework wyróżnia się jako powszechnie wybierana opcja do tworzenia aplikacji opartych na systemie Windows. W tym artykule zagłębiamy się w zawiłości .NET TestConsole, narzędzia zaprojektowanego specjalnie do testowania aplikacji .NET.

W trakcie tego omówienia napiszemy obszerny przykład kodu ilustrujący praktyczne wdrożenie .NET TestConsole. Dodatkowo omówimy IronPDF, wzorcową bibliotekę C# do obsługi plików PDF, płynnie zintegrowaną z .NET TestConsole. Biblioteka ta okazuje się nieoceniona, umożliwiając programistom łatwy dostęp do plików PDF oraz ich generowanie w środowisku .NET TestConsole. Dołącz do nas w tej podróży, podczas której odkryjemy funkcjonalności i możliwości wynikające z synergii .NET TestConsole i funkcji C# PDF firmy IronPDF.

1. Wprowadzenie: TestConsole

TestConsole to wszechstronna biblioteka testowa, która wprowadza charakterystyczne podejście do testów jednostkowych w języku programowania C#. Tradycyjne metody testów jednostkowych często napotykają trudności w przypadku dużych zbiorów danych i złożonych asercji, co prowadzi do problemów z identyfikacją różnic między oczekiwanymi a rzeczywistymi wynikami. W odpowiedzi na to TestConsole oferuje nowatorski proces pracy, przechodząc od konwencjonalnego podejścia opartego na przewidywaniach do bezpośredniego porównania sformatowanego wyniku z wyznaczoną "zatwierdzoną" standardową wersją wyjściową.

W tej bibliotece, szczególnie w przypadku TestConsole, wariant ".Core" rozszerza możliwości formatowania odziedziczone po oryginalnym projekcie TestConsole i zawiera niezbędne funkcje zatwierdzania testów w scenariuszach, w których wyniki testów odbiegają od oczekiwań. TestConsole.Core płynnie integruje się z serwerem kompilacji, aby wywołać niepowodzenie testu. 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.

Zainstaluj bibliotekę IronPDF

Instalacja za pomocą menedżera pakietów NuGet

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

  1. Otwórz Visual Studio i w eksploratorze rozwiązań kliknij prawym przyciskiem myszy na swój projekt.
  2. Wybierz "Zarządzaj pakietami NuGet…" z menu kontekstowego.
  3. Przejdź do zakładki "Przeglądaj" i wyszukaj IronPDF.
  4. Wybierz bibliotekę IronPDF z wyników wyszukiwania i kliknij przycisk instalacji.
  5. Zaakceptuj wszelkie monity dotyczące Umowy licencyjnej.

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

Pobierze i zainstaluje IronPDF w Twoim projekcie.

Instalacja za pomocą NuGet Strona internetowa

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.

Instalacja za pomocą biblioteki 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. Rozpakuj plik i dołącz bibliotekę DLL do swojego projektu.

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. Podsumowanie

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.

Często Zadawane Pytania

Jak stworzyć aplikację konsolową w języku C#?

Aby utworzyć aplikację konsolową w języku C#, można użyć programu Visual Studio, aby rozpocząć nowy projekt i wybrać typ projektu „Console App”. Następnie należy napisać kod w języku C# w metodzie Main, aby wykonać logikę aplikacji.

Jaki jest cel .NET TestConsole?

.NET TestConsole jest przeznaczony do testowania aplikacji .NET poprzez zapewnienie unikalnego przepływu pracy, który obejmuje porównanie sformatowanych wyników z zatwierdzonymi standardami, poprawiając wydajność procesu testowania.

Jak mogę przekonwertować dane wyjściowe aplikacji konsolowej do formatu PDF w języku C#?

Możesz użyć IronPDF do konwersji wyników aplikacji konsolowej do formatu PDF w języku C#. Najpierw przechwyć wynik konsoli jako sformatowany ciąg znaków HTML, a następnie użyj metody RenderHtmlAsPdf biblioteki IronPDF, aby utworzyć plik PDF na podstawie treści HTML.

Jakie są zalety korzystania z biblioteki PDF w aplikacjach napisanych w języku C#?

Korzystanie z biblioteki PDF, takiej jak IronPDF, w aplikacjach napisanych w języku C# pozwala programistom generować, modyfikować i wyodrębniać treści z plików PDF, umożliwiając takie funkcje, jak tworzenie plików PDF na podstawie treści HTML, włączanie danych dynamicznych i wiele innych.

Jak działa porównanie wyników w trybie side-by-side w .NET TestConsole?

Porównanie wyników w trybie side-by-side w .NET TestConsole polega na porównaniu sformatowanego wyniku aplikacji z wcześniej zatwierdzonym standardem, co pozwala programistom zidentyfikować rozbieżności i zapewnić dokładność wyników testów.

Czy .NET TestConsole może być używany z .NET Core?

Tak, .NET TestConsole może być używany zarówno z pełnym .NET Frameworkem, jak i .NET Core, zapewniając elastyczność i kompatybilność w różnych środowiskach .NET do testowania aplikacji.

Jak mogę zintegrować bibliotekę PDF z moim projektem .NET?

Aby zintegrować bibliotekę PDF, taką jak IronPDF, z projektem .NET, można użyć menedżera pakietów NuGet w Visual Studio w celu jej zainstalowania lub pobrać plik DLL biblioteki i dodać go do odwołań projektu.

Jaka jest zaleta korzystania z biblioteki testowej w tworzeniu oprogramowania?

Biblioteka testowa, taka jak .NET TestConsole, usprawnia proces testowania poprzez automatyzację zatwierdzania testów, ułatwianie wydajnego porównywania wyników oraz usprawnianie ogólnego zarządzania testami, co prowadzi do poprawy jakości oprogramowania.

Jak radzić sobie z dużymi zbiorami danych za pomocą .NET TestConsole?

.NET TestConsole jest przystosowany do efektywnego przetwarzania dużych zbiorów danych dzięki zastosowaniu podejścia porównawczego, które upraszcza złożone asercje i zapewnia dokładne testowanie rozbudowanych wyników danych.

Gdzie mogę znaleźć więcej informacji na temat korzystania z IronPDF?

Więcej informacji na temat korzystania z IronPDF można znaleźć na oficjalnej stronie internetowej IronPDF, która zawiera obszerne przewodniki, samouczki i dokumentację dotyczącą integracji i wykorzystania IronPDF w projektach C#.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie