using Microsoft.Extensions.Configuration; using MediatR; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using PracticeCalendar.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; using PracticeCalendar.Domain.Entities; namespace PracticeCalendar.UnitTests.Integration { public partial class Testing { private static WebApplicationFactory _factory = null!; private static IConfiguration _configuration = null!; private static IServiceScopeFactory _scopeFactory = null!; public static async Task RunBeforeAnyTests() { _factory = new CustomWebApplicationFactory(); _scopeFactory = _factory.Services.GetRequiredService(); _configuration = _factory.Services.GetRequiredService(); } public static async Task SendAsync(IRequest request) { using var scope = _scopeFactory.CreateScope(); var mediator = scope.ServiceProvider.GetRequiredService(); return await mediator.Send(request); } public static async Task FindAsync(params object[] keyValues) where TEntity : class { using var scope = _scopeFactory.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); return await context.FindAsync(keyValues); } public static async Task AddAsync(TEntity entity) where TEntity : class { using var scope = _scopeFactory.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); context.Add(entity); await context.SaveChangesAsync(); } public static async Task CountAsync() where TEntity : class { using var scope = _scopeFactory.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); return await context.Set().CountAsync(); } public static void ResetState() { if (_scopeFactory != null) { using var scope = _scopeFactory.CreateScope(); var context = scope.ServiceProvider.GetRequiredService(); context.Set().RemoveRange(context.Set().ToList()); context.Set().RemoveRange(context.Set().ToList()); context.SaveChanges(); } } } }