0% found this document useful (0 votes)
6 views2 pages

Xunit Tests for Airplane API Endpoint

The document contains code to test the GET endpoint for retrieving airplane data. It sets up a test database, inserts sample airplane data, makes a request to the GET /Avion endpoint, and asserts that the response has a success status code.

Uploaded by

Rousse Rub
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Xunit Tests for Airplane API Endpoint

The document contains code to test the GET endpoint for retrieving airplane data. It sets up a test database, inserts sample airplane data, makes a request to the GET /Avion endpoint, and asserts that the response has a success status code.

Uploaded by

Rousse Rub
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

using Xunit;

using [Link];
using [Link];
using [Link];
using [Link];
using BackendAerolinea;
using [Link];
using [Link];

using [Link];

namespace TestingAvion;

public class AvionTest1 : IClassFixture<WebApplicationFactory<Program>>


{

[Fact]
public async Task getAvion_ShouldReturnExistingAirplane()
{
// Arrange
var builder = [Link](new string[0]);
var connectionString = "Server=DESKTOP-9A9H02P\\
SQLEXPRESS;Database=Aerolineadb;Trusted_Connection=true;TrustServerCertificate=true
";

[Link]<DataContext>(options =>
{
[Link]<DataContext>(options =>
{
[Link](connectionString); // Configura la conexión a
SQL Server
});
});
var app = [Link]();
var context = [Link]<DataContext>();
await [Link]();
var client = [Link]<HttpClient>(); // Obtén un
HttpClient para realizar solicitudes.

var avionesData = new List<Avion>


{
new Avion
{
Id = 1,
NombreAvion = "Boeing 747",
Horasalida = [Link](8),
Horallegada = [Link](16),
Aeropuertosalida = "Aeropuerto A",
Aeropuertollegada = "Aeropuerto B",
StatusVuelo = "En vuelo",
PasajerosLimite = 300,
LimitePeso = 20000
},
new Avion
{
Id = 2,
NombreAvion = "Airbus A380",
Horasalida = [Link](12),
Horallegada = [Link](20),
Aeropuertosalida = "Aeropuerto X",
Aeropuertollegada = "Aeropuerto Y",
StatusVuelo = "En tierra",
PasajerosLimite = 400,
LimitePeso = 22000
}
};
[Link](avionesData);
await [Link]();

//Act
var response = await [Link]("/Avion");

// Assert
[Link]();
}
}

_________________________________________________________________________

using Xunit;
using [Link];
using [Link];
using [Link];
using BackendAerolinea;

namespace [Link]
{
public class AvionTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;

public AvionTests()
{

[Fact]
public async Task TestGetAvionEndpoint()
{
// Arrange
var client = _factory.CreateClient();

// Act
var response = await [Link]("/Avion");

// Assert
[Link]();
// Add more assertions based on the expected behavior
}

// Add more tests for other endpoints


}
}

Common questions

Powered by AI

The `AvionTests` class demonstrates separation of concerns by isolating test logic from the application logic. It leverages `IClassFixture` to handle setup and initialization, thus separating setup operations from test assertions. Each test method focuses strictly on asserting specific scenarios or API endpoint behaviors rather than dealing with context or application initialization, which encourages maintainability and clarity within the test suite .

`WebApplicationFactory<Program>` simplifies the integration testing process of web APIs by creating a test server that simulates the real application's environment. This class automatically handles dependency injection, providing an instance of the application with all its services configured and ready to use. This eliminates the need for manual configuration of services and middleware, allowing tests to focus solely on verifying application behavior .

The `CreateBuilder` method initializes a new `WebApplicationBuilder` which is used to configure and build a new web application host. This setup enables developers to specify and configure services, middleware, and application settings in a programmatic way, crucial for customizing the environment for testing. The `Build` method then compiles these configurations into an executable application host. These methods facilitate testing flexibility by enabling dynamic alterations to service configurations, middleware, and overall application behavior during tests .

Setting attributes such as `Horasalida` and `Horallegada` provides specific parameters for validating business logic related to flight scheduling and management. These attributes allow the tests to verify that the application correctly processes and returns expected results based on predefined schedules. This precision is essential for simulating real-world scenarios and ensures that time-dependent logic, such as determining flight status or calculating durations, function as intended .

`EnsureCreatedAsync` is called on the database context to ensure that the database is created before any data is added to it. This is particularly important when using an in-memory or test database configuration, as it initializes the necessary schema and data structures. By doing so, the subsequent operations, such as adding test data to the context, can execute without encountering issues related to non-existent databases .

The `getAvion_ShouldReturnExistingAirplane` test sets up a mock database using an in-memory context provided by Entity Framework Core. It populates this context with a list of airplane records including details such as `NombreAvion`, `Horasalida`, `Horallegada`, etc. Once the context is set up, the test makes an HTTP GET request to the `/Avion` endpoint using a `HttpClient`. The success of this operation is verified by asserting that the HTTP response status code is successful, which indicates that the records were correctly retrieved from the database .

Configuring the database context with `TrustServerCertificate=true` ensures that SSL-related security checks are bypassed for testing environments. This is particularly useful when using self-signed certificates or in scenarios where full SSL validation is not needed, such as in controlled testing environments. By setting this, it simplifies connectivity and focuses testing efforts on functionality rather than security configuration, which remains critical in production environments .

The `AddDbContext` method integrates the database context into the ASP.NET Core service container during application startup. It configures the context options, such as the connection string, to establish how and where to connect to the database. A connection string is critical as it specifies the details required to access the SQL Server database, including server location and authentication details. This configuration is crucial in testing scenarios to ensure that test-specific databases or in-memory configurations are used to avoid affecting production data .

The method `EnsureSuccessStatusCode` is used to verify that an HTTP request completed successfully. Specifically, it checks that the HTTP status code returned by the GET request to the `/Avion` endpoint indicates a successful operation, i.e., a status code in the range of 200-299. If the status code falls outside this range, `EnsureSuccessStatusCode` throws an exception, indicating that the request did not complete as expected .

`IClassFixture` is used in xUnit to create a shared context for multiple tests within a test class. It allows the test class to leverage a shared instance of `WebApplicationFactory<Program>`, which sets up the test server and creates the HTTP client used for sending requests to the application. This approach avoids the overhead of re-initializing the web host for each test, making the tests more efficient .

You might also like