Skip to content

Commit

Permalink
Create integrations tests for pessoa fisica controller
Browse files Browse the repository at this point in the history
  • Loading branch information
erlonfs committed Apr 20, 2020
1 parent 03a2cbe commit 4a7e445
Show file tree
Hide file tree
Showing 19 changed files with 389 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public PessoaFisicaRepository(AppDbContext context) : base(context)

public async Task<PessoaFisica> ObterPorCpfAsync(string cpf)
{
return await _context.PessoaFisica.FirstOrDefaultAsync(x => x.Cpf == cpf);
return await _context.PessoaFisica.FirstOrDefaultAsync(x => x.Cpf.Numero == cpf);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
<ItemGroup>
<PackageReference Include="AutoFixture" Version="4.11.0" />
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.3" />
<PackageReference Include="Microsoft.CodeCoverage" Version="16.5.0" />
<PackageReference Include="Microsoft.CodeCoverage" Version="16.5.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.3" />
<PackageReference Include="Moq" Version="4.13.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.console" Version="2.4.1">
Expand Down
28 changes: 23 additions & 5 deletions Demo.GestaoEscolar.WebApplication.Test/Fakes/FakeStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,19 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Data.SqlClient;
using HandlersAssembly = Demo.GestaoEscolar.Handlers.Foo;
using InfraDapperAssembly = Demo.GestaoEscolar.Infra.Dapper.Foo;
using InfraEFAssembly = Demo.GestaoEscolar.Infra.EF.Foo;

namespace Demo.GestaoEscolar.WebApplication
{
public class FakeStartup
public class FakeStartup : TestSetup
{
public IConfiguration Configuration { get; }
public IContainer Container { get; private set; }
Expand Down Expand Up @@ -50,8 +52,14 @@ public void ConfigureServices(IServiceCollection services)

services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("AppDatabase"));
options.UseSqlServer(new SqlConnectionStringBuilder
{
DataSource = @"(LocalDB)\MSSQLLocalDB",
InitialCatalog = "GestaoEscolar",
IntegratedSecurity = true
}.ConnectionString);
options.UseLazyLoadingProxies();
options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
});

var builder = new ContainerBuilder();
Expand Down Expand Up @@ -79,8 +87,6 @@ public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)

app.UseRouting();

//app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
Expand All @@ -91,13 +97,25 @@ public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", $"Gestão Escolar API V1 {env.EnvironmentName}");
});

//var serviceScopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
//using (var serviceScope = serviceScopeFactory.CreateScope())
//{
// var dbContext = serviceScope.ServiceProvider.GetService<AppDbContext>();
// if (dbContext == null)
// {
// throw new NullReferenceException("Cannot get instance of dbContext");
// }


//}
}

public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<PessoaFisicaController>().PropertiesAutowired();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<MessageBus>().As<IMessageBus>();
builder.RegisterType<MessageBusFake>().As<IMessageBus>();

builder.RegisterType<MatriculaService>().As<IMatriculaService>();

Expand Down
21 changes: 21 additions & 0 deletions Demo.GestaoEscolar.WebApplication.Test/Fakes/MessageBusFake.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Threading.Tasks;
using CrossCutting;
using MassTransit;
using NLog;

namespace Demo.GestaoEscolar.WebApplication.Test
{
public class MessageBusFake : IMessageBus
{
public Task<bool> IsAliveAsync()
{
return Task.FromResult(true);
}

public Task PublishAsync<T>(T e)
{
return Task.CompletedTask;
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using Xunit;

namespace Demo.GestaoEscolar.WebApplication.Test
{
[CollectionDefinition("Integration test collection")]
public class IntegrationTestCollection : ICollectionFixture<TestSetup>
{
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using CrossCutting;
using Demo.GestaoEscolar.Domain.Finders;
using Demo.GestaoEscolar.Domain.Services.PessoasFisicas;
using Demo.GestaoEscolar.Infra.Dapper.Data;
using Demo.GestaoEscolar.WebApplication.Test.Extensions;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
Expand Down Expand Up @@ -53,7 +54,8 @@ protected override IWebHostBuilder CreateWebHostBuilder()
{
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<PessoaFisicaService>().As<IPessoaFisicaService>();
builder.RegisterType<PessaoFisicaFinderFake>().As<IPessoaFisicaFinder>();
builder.RegisterType<PessoaFisicaFinder>().As<IPessoaFisicaFinder>();
builder.RegisterType<MessageBusFake>().As<IMessageBus>();
})
.ConfigureServices(services => services.AddAutofac())
.UseSolutionRelativeContentRoot("Demo.GestaoEscolar.WebApplication")
Expand Down
131 changes: 131 additions & 0 deletions Demo.GestaoEscolar.WebApplication.Test/Infraestructure/TestSetup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Demo.GestaoEscolar.WebApplication.Test
{
public class TestSetup : IDisposable
{
public TestSetup()
{
DestroyDatabase();
CreateDatabase();
CreateSchema();
CreateTablePessoaFisica();
}

public void Dispose()
{
DestroyDatabase();
}

private static void CreateDatabase()
{
ExecuteSqlCommand(Master, $@"
CREATE DATABASE [GestaoEscolar]
ON (NAME = 'GestaoEscolar',
FILENAME = '{Filename}')");
}

private static void CreateSchema()
{
ExecuteSqlCommand(GestaoEscolar, $@"CREATE SCHEMA GES;");
}

private static void CreateTablePessoaFisica()
{
ExecuteSqlCommand(GestaoEscolar, $@"CREATE TABLE GES.PessoaFisica(
Id INT IDENTITY NOT NULL,
EntityId UNIQUEIDENTIFIER NOT NULL,
DataCriacao DATETIME NOT NULL,
Nome VARCHAR(400) NOT NULL,
Cpf VARCHAR(11) NOT NULL,
NomeSocial VARCHAR(400) NULL,
Sexo CHAR(1) NOT NULL,
DataNascimento DATETIME NOT NULL
);
ALTER TABLE GES.PessoaFisica ADD CONSTRAINT PK_PessoaFisica PRIMARY KEY (Id);
ALTER TABLE GES.PessoaFisica ADD CONSTRAINT UC_PessoaFisica_Cpf UNIQUE(Cpf);");
}

private static void DestroyDatabase()
{
var fileNames = ExecuteSqlQuery(Master, @"
SELECT [physical_name] FROM [sys].[master_files]
WHERE [database_id] = DB_ID('GestaoEscolar')",
row => (string)row["physical_name"]);

if (fileNames.Any())
{
ExecuteSqlCommand(Master, @"
ALTER DATABASE [GestaoEscolar] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
EXEC sp_detach_db 'GestaoEscolar'");

fileNames.ForEach(File.Delete);
}
}

private static void ExecuteSqlCommand(
SqlConnectionStringBuilder connectionStringBuilder,
string commandText)
{
using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = commandText;
command.ExecuteNonQuery();
}
}
}

private static List<T> ExecuteSqlQuery<T>(
SqlConnectionStringBuilder connectionStringBuilder,
string queryText,
Func<SqlDataReader, T> read)
{
var result = new List<T>();
using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryText;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(read(reader));
}
}
}
}
return result;
}

private static SqlConnectionStringBuilder Master =>
new SqlConnectionStringBuilder
{
DataSource = @"(LocalDB)\MSSQLLocalDB",
InitialCatalog = "master",
IntegratedSecurity = true
};

private static SqlConnectionStringBuilder GestaoEscolar =>
new SqlConnectionStringBuilder
{
DataSource = @"(LocalDB)\MSSQLLocalDB",
InitialCatalog = "GestaoEscolar",
IntegratedSecurity = true
};

private static string Filename => Path.Combine(
Path.GetDirectoryName(
typeof(TestSetup).GetTypeInfo().Assembly.Location),
"GestaoEscolar.mdf");
}
}

This file was deleted.

Loading

0 comments on commit 4a7e445

Please sign in to comment.