nice refactorings

This commit is contained in:
2022-10-10 03:17:14 +03:00
parent 4ca234aec8
commit 28a6981001
30 changed files with 622 additions and 141 deletions
@@ -1,15 +1,14 @@
using FluentAssertions;
using PracticeCalendar.Domain.Entities;
namespace PracticeCalendar.UnitTests
namespace PracticeCalendar.UnitTests.Domain
{
public class PracticeEventTest
{
string _eventTitle = "Event1";
string _eventDescription = "Description";
string _attendeeName = "Claudiu Farcas";
string _atendeeEmail = "claudiu.farcas@testingbee.com";
readonly string _eventTitle = "Event1";
readonly string _eventDescription = "Description";
readonly string _attendeeName = "Claudiu Farcas";
readonly string _atendeeEmail = "claudiu.farcas@testingbee.com";
[Fact]
public void InitializeProperties()
@@ -23,22 +22,26 @@ namespace PracticeCalendar.UnitTests
[Fact]
public void InitializeWithNullShouldThrowException()
{
Action act = () => {
var practiceEvent = new PracticeEvent(null, _eventDescription);
Action act = () =>
{
var practiceEvent = new PracticeEvent(null!, _eventDescription);
};
act.Should().Throw<ArgumentNullException>();
act = () => {
var practiceEvent = new PracticeEvent(_eventTitle, null);
act = () =>
{
var practiceEvent = new PracticeEvent(_eventTitle, null!);
};
act.Should().Throw<ArgumentNullException>();
act = () => {
act = () =>
{
var practiceEvent = new PracticeEvent(string.Empty, _eventDescription);
};
act.Should().Throw<ArgumentException>();
act = () => {
act = () =>
{
var practiceEvent = new PracticeEvent(_eventTitle, string.Empty);
};
act.Should().Throw<ArgumentException>();
@@ -0,0 +1,12 @@
using static PracticeCalendar.UnitTests.Integration.Testing;
namespace PracticeCalendar.UnitTests.Integration
{
public class BaseTest
{
public BaseTest()
{
ResetState();
}
}
}
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using PracticeCalendar.Infrastructure.Persistence;
namespace PracticeCalendar.UnitTests.Integration
{
public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration(configurationBuilder =>
{
var integrationConfig = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
configurationBuilder.AddConfiguration(integrationConfig);
});
builder.ConfigureServices((builder, services) =>
{
services.Remove<DbContextOptions<ApplicationDbContext>>();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase("InMemoryDbForTesting")
);
});
}
}
}
@@ -0,0 +1,43 @@
using FluentAssertions;
using PracticeCalendar.Application.PracticeEvents.Commands;
using PracticeCalendar.Application.PracticeEvents.Queries;
using static PracticeCalendar.UnitTests.Integration.Testing;
namespace PracticeCalendar.UnitTests.Integration.PracticeEvents
{
public class CreatePracticeEventsTest : BaseTest
{
[Fact]
public async Task ShouldCreatePracticeEvent()
{
await RunBeforeAnyTests();
var query = new CreatePracticeEventCommand(new PracticeEventDto
{
Title = "Some title",
Description = "Some desc",
StartTime = DateTime.Now,
EndTime = DateTime.Now,
Attendees = {
new AttendeeDto
{
Name = "Claudiu F",
EmailAddress = "claudiuf@somewhere.com"
},
new AttendeeDto
{
Name = "Claudiu F 2",
EmailAddress = "claudiuf2@somewhere.com"
}
}
});
var result = await SendAsync(query);
result.Should().NotBeNull();
result.Id.Should().NotBe(0);
result.Attendees.Count.Should().Be(2);
}
}
}
@@ -0,0 +1,48 @@
using FluentAssertions;
using PracticeCalendar.Application.PracticeEvents.Queries.GetPracticeEvents;
using PracticeCalendar.Domain.Entities;
using static PracticeCalendar.UnitTests.Integration.Testing;
namespace PracticeCalendar.UnitTests.Integration.PracticeEvents
{
public class GetPracticeEventsTest : BaseTest
{
[Fact]
public async Task ShouldReturnZeroResult()
{
await RunBeforeAnyTests();
var query = new GetPracticeEventsQuery();
var result = await SendAsync(query);
result.Count.Should().Be(0);
}
[Fact]
public async Task ShouldReturnAllListsAndItems()
{
await RunBeforeAnyTests();
await AddAsync(new PracticeEvent("Test Event", "Event description")
{
Id = 1,
Attendees = {
new Attendee("Claudiu F", "claudiuf@busybee.com")
{
Id = 1
}
}
});
var query = new GetPracticeEventsQuery();
var result = await SendAsync(query);
result.Should().HaveCount(1);
result.First().Attendees.Should().HaveCount(1);
}
}
}
@@ -0,0 +1,20 @@
using Microsoft.Extensions.DependencyInjection;
namespace PracticeCalendar.UnitTests.Integration
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection Remove<TService>(this IServiceCollection services)
{
var serviceDescriptor = services.FirstOrDefault(d =>
d.ServiceType == typeof(TService));
if (serviceDescriptor != null)
{
services.Remove(serviceDescriptor);
}
return services;
}
}
}
@@ -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();
}
}
}
}
@@ -8,9 +8,24 @@
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.9" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2" />
<PackageReference Include="Moq" Version="4.18.2" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -23,7 +38,17 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PracticeCalendar.Domain\PracticeCalendar.Domain.csproj" />
<ProjectReference Include="..\PracticeCalendar.Api\PracticeCalendar.API.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Application\" />
</ItemGroup>
<ItemGroup>
<None Update="xunit.runner.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
@@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"UseInMemoryDatabase": true, //integration tests always with real database
"ConnectionStrings": {
"TestSqliteConnection": "Data Source=practicecalendar_test.sqlite"
}
}
@@ -0,0 +1,4 @@
{
"parallelizeAssembly": false,
"parallelizeTestCollections": false
}