mirror of
https://github.com/farcasclaudiu/PracticeCalendar.git
synced 2026-06-28 13:01:04 +03:00
nice refactorings
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
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<Program> _factory = null!;
|
||||
private static IConfiguration _configuration = null!;
|
||||
private static IServiceScopeFactory _scopeFactory = null!;
|
||||
|
||||
public static async Task RunBeforeAnyTests()
|
||||
{
|
||||
_factory = new CustomWebApplicationFactory();
|
||||
_scopeFactory = _factory.Services.GetRequiredService<IServiceScopeFactory>();
|
||||
_configuration = _factory.Services.GetRequiredService<IConfiguration>();
|
||||
}
|
||||
|
||||
public static async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
|
||||
var mediator = scope.ServiceProvider.GetRequiredService<ISender>();
|
||||
|
||||
return await mediator.Send(request);
|
||||
}
|
||||
|
||||
public static async Task<TEntity?> FindAsync<TEntity>(params object[] keyValues)
|
||||
where TEntity : class
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
|
||||
return await context.FindAsync<TEntity>(keyValues);
|
||||
}
|
||||
|
||||
public static async Task AddAsync<TEntity>(TEntity entity)
|
||||
where TEntity : class
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
|
||||
context.Add(entity);
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public static async Task<int> CountAsync<TEntity>() where TEntity : class
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
|
||||
return await context.Set<TEntity>().CountAsync();
|
||||
}
|
||||
|
||||
public static void ResetState()
|
||||
{
|
||||
if (_scopeFactory != null)
|
||||
{
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
context.Set<Attendee>().RemoveRange(context.Set<Attendee>().ToList());
|
||||
context.Set<PracticeEvent>().RemoveRange(context.Set<PracticeEvent>().ToList());
|
||||
context.SaveChanges();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user