Skip to content

Refactor test integration #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/OA.Infrastructure/Extension/ConfigureServiceContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,20 @@ namespace OA.Infrastructure.Extension;

public static class ConfigureServiceContainer
{
public static void AddDbContext(this IServiceCollection serviceCollection,
IConfiguration configuration, IConfigurationRoot configRoot)
public static void AddDbContext(this IServiceCollection serviceCollection, IConfiguration configuration)
{
serviceCollection.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("OnionArchConn") ?? configRoot["ConnectionStrings:OnionArchConn"]
, b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)));

if (configuration.GetValue<bool>("UseInMemoryDatabase"))
{
serviceCollection.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase(nameof(ApplicationDbContext)));
}
else
{
serviceCollection.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("OnionArchConn")
, b => b.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)));
}

}

Expand Down
3 changes: 2 additions & 1 deletion src/OA.Service/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static void AddIdentityService(this IServiceCollection services, IConfigu
if (configuration.GetValue<bool>("UseInMemoryDatabase"))
{
services.AddDbContext<IdentityContext>(options =>
options.UseInMemoryDatabase("IdentityDb"));
options.UseInMemoryDatabase(nameof(IdentityContext)));
}
else
{
Expand All @@ -41,6 +41,7 @@ public static void AddIdentityService(this IServiceCollection services, IConfigu
configuration.GetConnectionString("IdentityConnection"),
b => b.MigrationsAssembly(typeof(IdentityContext).Assembly.FullName)));
}

services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<IdentityContext>()
.AddDefaultTokenProviders();
#region Services
Expand Down
21 changes: 0 additions & 21 deletions src/OA.Test.Integration/ApiCustomerTest.cs

This file was deleted.

160 changes: 160 additions & 0 deletions src/OA.Test.Integration/ApiEndpoints/ApiCustomerTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
using NUnit.Framework;
using OA.Service.Features.CustomerFeatures.Commands;
using System.Net;

namespace OA.Test.Integration.ApiEndpoints;

public class ApiCustomerTest : TestClientProvider
{
[TestCase("api/v1/Customer", HttpStatusCode.OK)]
[TestCase("api/v1/Customer/100", HttpStatusCode.NoContent)]
public async Task GetAllCustomerTestAsync(string url, HttpStatusCode result)
{
var request = new HttpRequestMessage(HttpMethod.Get, url);

var response = await Client
.AddBearerTokenAuthorization()
.SendAsync(request);

Assert.That(response.StatusCode, Is.EqualTo(result));
}

[Test]
public async Task CreateCustomerTestAsync()
{
// Create a customer model
var model = new CreateCustomerCommand
{
CustomerName = "John Wick",
ContactName = "John Wick",
ContactTitle = "Manager",
Address = "123 Main St",
City = "New York",
Region = "NY",
PostalCode = "10001",
Country = "USA",
Phone = "123-456-7890",
Fax = "987-654-3210"
};

// Create POST request
var request = new HttpRequestMessage(HttpMethod.Post, "api/v1/Customer")
{
Content = HttpClientExtensions.SerializeAndCreateContent(model)
};

// Send request and check response
var response = await Client
.AddBearerTokenAuthorization()
.SendAsync(request);

Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}

[Test]
public async Task UpdateCustomerTestAsync()
{
// First, create a new customer
var createModel = new CreateCustomerCommand
{
CustomerName = "John Wick",
ContactName = "John Wick",
ContactTitle = "Manager",
Address = "123 Main St",
City = "New York",
Region = "NY",
PostalCode = "10001",
Country = "USA",
Phone = "123-456-7890",
Fax = "987-654-3210"
};

var createRequest = new HttpRequestMessage(HttpMethod.Post, "api/v1/Customer")
{
Content = HttpClientExtensions.SerializeAndCreateContent(createModel)
};

var createResponse = await Client
.AddBearerTokenAuthorization()
.SendAsync(createRequest);

Assert.That(createResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));

// Now update the new customer
var updateModel = new UpdateCustomerCommand
{
Id = int.Parse(await createResponse.Content.ReadAsStringAsync()),
CustomerName = "Updated John Wick",
ContactName = "Jane Wick",
ContactTitle = "Director",
Address = "456 Another St",
City = "Los Angeles",
Region = "CA",
PostalCode = "90001",
Country = "USA",
Phone = "987-654-3210",
Fax = "123-456-7890"
};

var updateRequest = new HttpRequestMessage(HttpMethod.Put, $"api/v1/Customer/{updateModel.Id}")
{
Content = HttpClientExtensions.SerializeAndCreateContent(updateModel)
};

// Send update request and check response status
var updateResponse = await Client
.AddBearerTokenAuthorization()
.SendAsync(updateRequest);

Assert.That(updateResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));
}

[Test]
public async Task DeleteCustomerTestAsync()
{
// First, create a new customer
var createModel = new CreateCustomerCommand
{
CustomerName = "John Wick",
ContactName = "John Wick",
ContactTitle = "Manager",
Address = "123 Main St",
City = "New York",
Region = "NY",
PostalCode = "10001",
Country = "USA",
Phone = "123-456-7890",
Fax = "987-654-3210"
};

var createRequest = new HttpRequestMessage(HttpMethod.Post, "api/v1/Customer")
{
Content = HttpClientExtensions.SerializeAndCreateContent(createModel)
};

var createResponse = await Client
.AddBearerTokenAuthorization()
.SendAsync(createRequest);

Assert.That(createResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));

// Get the created customer's ID
int customerId = int.Parse(await createResponse.Content.ReadAsStringAsync());

// Now delete the customer
var deleteRequest = new HttpRequestMessage(HttpMethod.Delete, $"api/v1/Customer/{customerId}");

// Send delete request and check response status
var deleteResponse = await Client
.AddBearerTokenAuthorization()
.SendAsync(deleteRequest);

Assert.That(deleteResponse.StatusCode, Is.EqualTo(HttpStatusCode.OK));

// Optionally, you can check if the customer has been actually deleted by trying to retrieve it
var getRequest = new HttpRequestMessage(HttpMethod.Get, $"api/v1/Customer/{customerId}");
var getResponse = await Client.AddBearerTokenAuthorization().SendAsync(getRequest);
Assert.That(getResponse.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
}

}
21 changes: 21 additions & 0 deletions src/OA.Test.Integration/HttpClientAuthExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
namespace OA.Test.Integration;

internal static class HttpClientAuthExtensions
{
const string AuthorizationKey = "Authorization";

// JWT generated for 'superadmin@gmail.com' with max expiry date
const string Jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdXBlcmFkbWluIiwianRpIjoiNDIzNzhlNjktMmI0YS00ZTVhLWEyZjUtM2RjMTI4YTFhNGFiIiwiZW1haWwiOiJzdXBlcmFkbWluQGdtYWlsLmNvbSIsInVpZCI6Ijk3Y2Y0ZDkwLWYyY2EtNGEwZi04MjdhLWU2ZmVkZTE2ODQyYSIsImlwIjoiMTkyLjE2OC40NS4xMzUiLCJyb2xlcyI6WyJTdXBlckFkbWluIiwiQWRtaW4iLCJCYXNpYyIsIk1vZGVyYXRvciJdLCJleHAiOjI1MzQwMjI4ODIwMCwiaXNzIjoiSWRlbnRpdHkiLCJhdWQiOiJJZGVudGl0eVVzZXIifQ.sYDCw6R-HtNfC8xJYENmq39iYJtXiVrAh5dboTrGlX8";

public static HttpClient AddBearerTokenAuthorization(this HttpClient client)
{
// Check if the Authorization header is already present
if (client.DefaultRequestHeaders.Any(p => p.Key == AuthorizationKey))
return client;

client.DefaultRequestHeaders.Add(AuthorizationKey, $"Bearer {Jwt}");

return client;

}
}
19 changes: 19 additions & 0 deletions src/OA.Test.Integration/HttpClientExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Text.Json;
using System.Text;

namespace OA.Test.Integration;

public static class HttpClientExtensions
{
static readonly JsonSerializerOptions DefaultJsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

public static StringContent SerializeAndCreateContent<T>(T model)
{
string jsonContent = JsonSerializer.Serialize(model, DefaultJsonOptions);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
return content;
}
}
2 changes: 1 addition & 1 deletion src/OA.Test.Integration/OA.Test.Integration.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.TestHost" Version="8.0.8" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.8" />
<PackageReference Include="nunit" Version="4.2.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
Expand Down
25 changes: 18 additions & 7 deletions src/OA.Test.Integration/TestClientProvider.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.AspNetCore.Mvc.Testing;

namespace OA.Test.Integration;

public class TestClientProvider
public class TestClientProvider : IDisposable
{
public HttpClient Client { get; private set; }
private readonly WebApplicationFactory<Program> _factory;
public HttpClient Client { get; }

public TestClientProvider()
{
var server = new TestServer(new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Program>());
// Initialize WebApplicationFactory with the Program class
_factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
// Set the environment to Test
builder.UseEnvironment("Test");
});

Client = server.CreateClient();
Client = _factory.CreateClient();
}

public void Dispose()
{
Client.Dispose();
_factory.Dispose();
}
}
9 changes: 2 additions & 7 deletions src/OA/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,13 @@
var builder = WebApplication.CreateBuilder(args);


// Build the configuration
var configRoot = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();

// Bind AppSettings
var appSettings = new AppSettings();
builder.Configuration.Bind(appSettings);

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext(builder.Configuration, configRoot);
builder.Services.AddDbContext(builder.Configuration);
builder.Services.AddIdentityService(builder.Configuration);
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddScopedServices();
Expand Down Expand Up @@ -96,6 +90,7 @@
// Run the application
app.Run();


public partial class Program
{
}
9 changes: 9 additions & 0 deletions src/OA/appsettings.Test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"UseInMemoryDatabase": true,
"Serilog": {
"MinimumLevel": "Information",
"Properties": {
"Application": "Onion Architecture application"
}
}
}
1 change: 1 addition & 0 deletions src/OA/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
}
},
"AllowedHosts": "*",
"UseInMemoryDatabase": false,
"ConnectionStrings": {
"OnionArchConn": "Data Source=.;Initial Catalog=Onion;Integrated Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True",
"IdentityConnection": "Data Source=.;Initial Catalog=OnionIde;Integrated Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True"
Expand Down