95 lines
3.2 KiB
C#
95 lines
3.2 KiB
C#
using Microsoft.AspNetCore.Hosting;
|
|
using Microsoft.AspNetCore.Mvc.Testing;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using MongoDB.Driver;
|
|
using BCards.Web.Configuration;
|
|
|
|
namespace BCards.Tests.Fixtures;
|
|
|
|
public class BCardsWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
|
|
{
|
|
public IMongoDatabase TestDatabase { get; private set; } = null!;
|
|
|
|
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
|
{
|
|
builder.ConfigureAppConfiguration((context, config) =>
|
|
{
|
|
// Remove existing configuration and add test configuration
|
|
config.Sources.Clear();
|
|
config.AddJsonFile("appsettings.Testing.json");
|
|
config.AddEnvironmentVariables();
|
|
});
|
|
|
|
builder.ConfigureServices(services =>
|
|
{
|
|
// Remove the existing MongoDB registration
|
|
var mongoDescriptor = services.SingleOrDefault(
|
|
d => d.ServiceType == typeof(IMongoDatabase));
|
|
if (mongoDescriptor != null)
|
|
{
|
|
services.Remove(mongoDescriptor);
|
|
}
|
|
|
|
var mongoClientDescriptor = services.SingleOrDefault(
|
|
d => d.ServiceType == typeof(IMongoClient));
|
|
if (mongoClientDescriptor != null)
|
|
{
|
|
services.Remove(mongoClientDescriptor);
|
|
}
|
|
|
|
// Add test MongoDB client and database
|
|
services.AddSingleton<IMongoClient>(serviceProvider =>
|
|
{
|
|
var testConnectionString = "mongodb://localhost:27017";
|
|
return new MongoClient(testConnectionString);
|
|
});
|
|
|
|
services.AddScoped(serviceProvider =>
|
|
{
|
|
var client = serviceProvider.GetRequiredService<IMongoClient>();
|
|
var databaseName = $"bcards_test_{Guid.NewGuid():N}";
|
|
TestDatabase = client.GetDatabase(databaseName);
|
|
return TestDatabase;
|
|
});
|
|
|
|
// Configure test Stripe settings
|
|
services.Configure<StripeSettings>(options =>
|
|
{
|
|
options.PublishableKey = "pk_test_fake_key_for_testing";
|
|
options.SecretKey = "sk_test_fake_key_for_testing";
|
|
options.WebhookSecret = "whsec_fake_webhook_secret_for_testing";
|
|
});
|
|
});
|
|
|
|
builder.UseEnvironment("Testing");
|
|
|
|
// Suppress logs during testing to reduce noise
|
|
builder.ConfigureLogging(logging =>
|
|
{
|
|
logging.ClearProviders();
|
|
logging.AddConsole();
|
|
logging.SetMinimumLevel(LogLevel.Warning);
|
|
});
|
|
}
|
|
|
|
protected override void Dispose(bool disposing)
|
|
{
|
|
if (disposing && TestDatabase != null)
|
|
{
|
|
// Clean up test database
|
|
try
|
|
{
|
|
var client = TestDatabase.Client;
|
|
client.DropDatabase(TestDatabase.DatabaseNamespace.DatabaseName);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// Ignore cleanup errors
|
|
}
|
|
}
|
|
|
|
base.Dispose(disposing);
|
|
}
|
|
} |