Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/t unit #1

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,12 @@ jobs:
- name: Build
run: dotnet build --no-restore --configuration Release
- name: Test
working-directory: Tests/CleanAspCore.Api.Tests
run: >
dotnet test
dotnet run
--no-build
--configuration Release
--verbosity normal
--logger GitHubActions
--
RunConfiguration.CollectSourceInformation=true
--report-trx
- name: dotnet publish
working-directory: CleanAspCore.Api
run: dotnet publish --no-build -c Release -o ${{env.DOTNET_ROOT}}/myapp
Expand Down
42 changes: 36 additions & 6 deletions .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@

name: .NET

permissions:
checks: write
pull-requests: write

on:
push:
branches: [ "main" ]
Expand Down Expand Up @@ -35,12 +39,38 @@ jobs:
- name: Check code formatting
run: dotnet format --no-restore --verify-no-changes -v diag
- name: Build
run: dotnet build --no-restore
run: dotnet build
--no-restore
--configuration Release
- name: Test
working-directory: Tests/CleanAspCore.Api.Tests
run: >
dotnet test
dotnet run
--no-build
--verbosity normal
--logger GitHubActions
--
RunConfiguration.CollectSourceInformation=true
--configuration Release
--coverage
--coverage-output-format cobertura
--report-trx
- name: Publish Test Results
uses: EnricoMi/publish-unit-test-result-action@v2
if: always()
with:
files: |
**/*.trx
- name: Code Coverage Report
uses: irongut/[email protected]
with:
filename: "**/*.cobertura.xml"
badge: true
format: markdown
hide_branch_rate: false
hide_complexity: true
indicators: true
output: both

- name: Add Coverage PR Comment
uses: marocchino/sticky-pull-request-comment@v2
if: github.event_name == 'pull_request'
with:
recreate: true
path: code-coverage-results.md
1 change: 1 addition & 0 deletions CleanAspCore.sln
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionItems", "SolutionIt
Readme.md = Readme.md
.github\workflows\dotnet.yml = .github\workflows\dotnet.yml
.github\workflows\deploy.yml = .github\workflows\deploy.yml
Directory.Packages.props = Directory.Packages.props
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CleanAspCore.Api.Tests", "Tests\CleanAspCore.Api.Tests\CleanAspCore.Api.Tests.csproj", "{4B45D679-E787-4236-BD9A-383364CD0E6F}"
Expand Down
7 changes: 3 additions & 4 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http.Polly" Version="9.0.0" />
<PackageVersion Include="Microsoft.Identity.Web" Version="3.4.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="NUnit" Version="4.2.2" />
<PackageVersion Include="NUnit.Analyzers" Version="4.4.0" />
<PackageVersion Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageVersion Include="Microsoft.Testing.Extensions.CodeCoverage" Version="17.13.1" />
<PackageVersion Include="Microsoft.Testing.Extensions.TrxReport" Version="1.4.3" />
<PackageVersion Include="TUnit" Version="0.4.95" />
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.10.0" />
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.10.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
Expand Down
18 changes: 3 additions & 15 deletions Tests/CleanAspCore.Api.Tests/CleanAspCore.Api.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,11 @@
<ItemGroup>
<PackageReference Include="Bogus"/>
<PackageReference Include="FluentAssertions"/>
<PackageReference Include="GitHubActionsTestLogger">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational"/>
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<PackageReference Include="NUnit"/>
<PackageReference Include="NUnit3TestAdapter"/>
<PackageReference Include="NUnit.Analyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Testing.Extensions.CodeCoverage"/>
<PackageReference Include="Microsoft.Testing.Extensions.TrxReport"/>
<PackageReference Include="TUnit"/>
<PackageReference Include="Refit"/>
</ItemGroup>
<ItemGroup>
Expand Down
54 changes: 14 additions & 40 deletions Tests/CleanAspCore.Api.Tests/Data/MigrationTests.cs
Original file line number Diff line number Diff line change
@@ -1,43 +1,32 @@
using System.Collections;
using CleanAspCore.Data;
using CleanAspCore.Data;
using CleanAspCore.TestUtils.DataBaseSetup;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Testcontainers.MsSql;

namespace CleanAspCore.Api.Tests.Data;

[FixtureLifeCycle(LifeCycle.SingleInstance)]
[Parallelizable(ParallelScope.Self)]
internal sealed class MigrationTests
internal sealed class MigrationTests(MsSqlContainer databaseContainer, ILogger<MigrationTests> logger)
{
#pragma warning disable NUnit1032
private MsSqlContainer _databaseContainer = null!;
#pragma warning restore NUnit1032
private ILogger<MigrationTests> _logger = null!;
private AsyncServiceScope _scope;

[SetUp]
public void BeforeTestCase()
public static IEnumerable<Func<MigrationScript>> MigrationTestCases()
{
_scope = GlobalSetup.Provider.CreateAsyncScope();
_databaseContainer = _scope.ServiceProvider.GetRequiredService<MsSqlContainer>();
_logger = _scope.ServiceProvider.GetRequiredService<ILogger<MigrationTests>>();
}
using DbContext context = new HrContext();
var migrations = context.GenerateMigrationScripts();

[TearDown]
public async Task AfterTestCase()
{
await _scope.DisposeAsync();
foreach (var migration in migrations)
{
yield return () => migration;
}
}

[TestCaseSource(typeof(MigrationTestCases))]
[Test]
[MethodDataSource(nameof(MigrationTestCases))]
[NotInParallel("MigrationsTest")]
public async Task MigrationsUpAndDown_NoErrors(MigrationScript migration)
{
var databaseName = "MigrationsTest";
await _databaseContainer.CreateDatabase(databaseName);
var migrator = new SqlMigrator(_databaseContainer, _logger, databaseName);
await databaseContainer.CreateDatabase(databaseName);
var migrator = new SqlMigrator(databaseContainer, logger, databaseName);
var upResult = await migrator.Up(migration);
upResult.ExitCode.Should().Be(0, $"Error during migration up: {upResult.Stderr}");
var downResult = await migrator.Down(migration);
Expand All @@ -47,25 +36,10 @@
}

[Test]
public void ModelShouldNotHavePendingModelChanges()

Check warning on line 39 in Tests/CleanAspCore.Api.Tests/Data/MigrationTests.cs

View workflow job for this annotation

GitHub Actions / build

Member 'ModelShouldNotHavePendingModelChanges' does not access instance data and can be marked as static (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822)

Check warning on line 39 in Tests/CleanAspCore.Api.Tests/Data/MigrationTests.cs

View workflow job for this annotation

GitHub Actions / build

Member 'ModelShouldNotHavePendingModelChanges' does not access instance data and can be marked as static (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1822)
{
using DbContext context = new HrContext();
var hasPendingModelChanges = context.Database.HasPendingModelChanges();
hasPendingModelChanges.Should().BeFalse();
}

[SuppressMessage("CodeQuality", "CA1812:Avoid uninstantiated internal classes")]
private sealed class MigrationTestCases : IEnumerable
{
public IEnumerator GetEnumerator()
{
using DbContext context = new HrContext();
var migrations = context.GenerateMigrationScripts();

foreach (var migration in migrations)
{
yield return new TestCaseData(migration);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace CleanAspCore.Api.Tests.Endpoints.Departments;

internal sealed class AddDepartmentsTests : TestBase
internal sealed class AddDepartmentsTests(TestWebApi sut)
{
[Test]
public async Task CreateDepartment_IsAdded()
Expand All @@ -11,12 +11,12 @@ public async Task CreateDepartment_IsAdded()
var department = new CreateDepartmentRequestFaker().Generate();

//Act
var response = await Sut.CreateClientFor<IDepartmentApiClient>().CreateDepartment(department);
var response = await sut.CreateClientFor<IDepartmentApiClient>().CreateDepartment(department);

//Assert
await response.AssertStatusCode(HttpStatusCode.Created);
var createdId = response.GetGuidFromLocationHeader();
Sut.AssertDatabase(context =>
sut.AssertDatabase(context =>
{
context.Departments.Should().BeEquivalentTo(new[] { new { Id = createdId } });
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
namespace CleanAspCore.Api.Tests.Endpoints.Departments;

internal sealed class GetDepartmentByIdTests : TestBase
internal sealed class GetDepartmentByIdTests(TestWebApi sut)
{
[Test]
public async Task GetDepartmentById_ReturnsExpectedDepartment()
{
//Arrange
var department = new DepartmentFaker().Generate();
Sut.SeedData(context =>
sut.SeedData(context =>
{
context.Departments.Add(department);
});

//Act
var response = await Sut.CreateClientFor<IDepartmentApiClient>().GetDepartmentById(department.Id);
var response = await sut.CreateClientFor<IDepartmentApiClient>().GetDepartmentById(department.Id);


//Assert
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,50 +3,51 @@

namespace CleanAspCore.Api.Tests.Endpoints.Employees;

internal sealed class CreateEmployeeTests : TestBase
internal sealed class CreateEmployeeTests(TestWebApi sut)
{
[Test]
public async Task CreateEmployee_IsAdded()
{
//Arrange
var createEmployeeRequest = new CreateEmployeeRequestFaker().Generate();
Sut.SeedData(context =>
sut.SeedData(context =>
{
context.Departments.Add(new DepartmentFaker().RuleFor(x => x.Id, createEmployeeRequest.DepartmentId).Generate());
context.Jobs.Add(new JobFaker().RuleFor(x => x.Id, createEmployeeRequest.JobId).Generate());
});

//Act
var response = await Sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).CreateEmployee(createEmployeeRequest);
var response = await sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).CreateEmployee(createEmployeeRequest);

//Assert
await response.AssertStatusCode(HttpStatusCode.Created);
var createdId = response.GetGuidFromLocationHeader();
Sut.AssertDatabase(context =>
sut.AssertDatabase(context =>
{
context.Employees.Should().BeEquivalentTo(new[] { new { Id = createdId } });
});
}

private static readonly TestScenario<(FakerConfigurator<CreateEmployeeRequest>, string[])>[] _validationCases =
[
new((string)"FirstName is null",
((FakerConfigurator<CreateEmployeeRequest>, string[]))(x => x.RuleFor(y => y.FirstName, (string?)null), ["FirstName"])),
new((string)"LastName is null",
((FakerConfigurator<CreateEmployeeRequest>, string[]))(x => x.RuleFor(y => y.LastName, (string?)null), ["LastName"])),
new((string)"Gender is null",
((FakerConfigurator<CreateEmployeeRequest>, string[]))(x => x.RuleFor(y => y.Gender, (string?)null), ["Gender"])),
new((string)"Email is null",
((FakerConfigurator<CreateEmployeeRequest>, string[]))(x => x.RuleFor(y => y.Email, (string?)null), ["Email"])),
new((string)"Invalid email",
((FakerConfigurator<CreateEmployeeRequest>, string[]))(x => x.RuleFor(y => y.Email, "this is not a valid email address"), ["Email"])),
new((string)"Job does not exist",
((FakerConfigurator<CreateEmployeeRequest>, string[]))(x => x.RuleFor(y => y.JobId, Guid.NewGuid()), ["JobId"])),
new((string)"Department does not exist",
((FakerConfigurator<CreateEmployeeRequest>, string[]))(x => x.RuleFor(y => y.DepartmentId, Guid.NewGuid()), ["DepartmentId"])),
];
public static IEnumerable<Func<TestScenario<(FakerConfigurator<CreateEmployeeRequest>, string[])>>> ValidationTestCases()
{
yield return () => new((string)"FirstName is null",
(x => x.RuleFor(y => y.FirstName, (string?)null), ["FirstName"]));
yield return () => new((string)"LastName is null",
(x => x.RuleFor(y => y.LastName, (string?)null), ["LastName"]));
yield return () => new((string)"Gender is null",
(x => x.RuleFor(y => y.Gender, (string?)null), ["Gender"]));
yield return () => new((string)"Email is null",
(x => x.RuleFor(y => y.Email, (string?)null), ["Email"]));
yield return () => new((string)"Invalid email",
(x => x.RuleFor(y => y.Email, "this is not a valid email address"), ["Email"]));
yield return () => new((string)"Job does not exist",
(x => x.RuleFor(y => y.JobId, Guid.NewGuid()), ["JobId"]));
yield return () => new((string)"Department does not exist",
(x => x.RuleFor(y => y.DepartmentId, Guid.NewGuid()), ["DepartmentId"]));
}

[TestCaseSource(nameof(_validationCases))]
[Test]
[MethodDataSource(nameof(ValidationTestCases))]
public async Task CreateEmployee_InvalidRequest_ReturnsBadRequest(TestScenario<(FakerConfigurator<CreateEmployeeRequest> configurator, string[] expectedErrors)> scenario)
{
//Arrange
Expand All @@ -57,18 +58,18 @@ public async Task CreateEmployee_InvalidRequest_ReturnsBadRequest(TestScenario<(
.RuleFor(x => x.DepartmentId, departmentId)
.RuleFor(x => x.JobId, jobId)).Generate();

Sut.SeedData(context =>
sut.SeedData(context =>
{
context.Departments.Add(new DepartmentFaker().RuleFor(x => x.Id, departmentId).Generate());
context.Jobs.Add(new JobFaker().RuleFor(x => x.Id, jobId).Generate());
});

//Act
var response = await Sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).CreateEmployee(createEmployeeRequest);
var response = await sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).CreateEmployee(createEmployeeRequest);

//Assert
await response.AssertBadRequest(scenario.Input.expectedErrors);
Sut.AssertDatabase(context =>
sut.AssertDatabase(context =>
{
context.Employees.Should().BeEmpty();
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
namespace CleanAspCore.Api.Tests.Endpoints.Employees;

internal sealed class DeleteEmployeeByIdTests : TestBase
internal sealed class DeleteEmployeeByIdTests(TestWebApi sut)
{
[Test]
public async Task DeleteEmployeeById_IsDeleted()
{
//Arrange
var employee = new EmployeeFaker().Generate();
Sut.SeedData(context =>
sut.SeedData(context =>
{
context.Employees.Add(employee);
});

//Act
var response = await Sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).DeleteEmployeeById(employee.Id);
var response = await sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).DeleteEmployeeById(employee.Id);

//Assert
await response.AssertStatusCode(HttpStatusCode.NoContent);
Sut.AssertDatabase(context => { context.Employees.Should().BeEmpty(); });
sut.AssertDatabase(context => { context.Employees.Should().BeEmpty(); });
}

[Test]
Expand All @@ -27,7 +27,7 @@ public async Task DeleteEmployeeById_DoesNotExist_ReturnsNotFound()
var id = Guid.NewGuid();

//Act
var response = await Sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).DeleteEmployeeById(id);
var response = await sut.CreateClientFor<IEmployeeApiClient>(ClaimConstants.WriteRole).DeleteEmployeeById(id);

//Assert
await response.AssertStatusCode(HttpStatusCode.NotFound);
Expand Down
Loading
Loading