Skip to content

Commit

Permalink
refactor(tests): refactor UnitTests to xunit
Browse files Browse the repository at this point in the history
  • Loading branch information
nadirbad committed Feb 22, 2024
1 parent d1fcc29 commit 2ee52b0
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 69 deletions.
9 changes: 9 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,14 @@
<PackageVersion Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
<!-- Analyzers -->
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
<!-- Tests -->
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0" />
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageVersion Include="throw" Version="1.4.0" />
<PackageVersion Include="xunit" Version="2.6.5" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.6" />
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
<PackageVersion Include="Moq" Version="4.16.1" />
</ItemGroup>
</Project>
9 changes: 9 additions & 0 deletions VerticalSliceArchitecture.sln
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
README.md = README.md
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{5F44F0AC-5482-4A73-9CAE-6A550E23B510}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Application.UnitTests", "tests\Application.UnitTests\Application.UnitTests.csproj", "{24BF57AE-47C4-4065-BAB0-72ACB562D22E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -32,13 +36,18 @@ Global
{22454EE9-16B3-4B7A-8352-37E59B858155}.Debug|Any CPU.Build.0 = Debug|Any CPU
{22454EE9-16B3-4B7A-8352-37E59B858155}.Release|Any CPU.ActiveCfg = Release|Any CPU
{22454EE9-16B3-4B7A-8352-37E59B858155}.Release|Any CPU.Build.0 = Release|Any CPU
{24BF57AE-47C4-4065-BAB0-72ACB562D22E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{24BF57AE-47C4-4065-BAB0-72ACB562D22E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{24BF57AE-47C4-4065-BAB0-72ACB562D22E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{24BF57AE-47C4-4065-BAB0-72ACB562D22E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{34C0FACD-F3D9-400C-8945-554DD6B0819A} = {6ED356A7-8B47-4613-AD01-C85CF28491BD}
{22454EE9-16B3-4B7A-8352-37E59B858155} = {6ED356A7-8B47-4613-AD01-C85CF28491BD}
{24BF57AE-47C4-4065-BAB0-72ACB562D22E} = {5F44F0AC-5482-4A73-9CAE-6A550E23B510}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3CB609D9-5D54-4C11-A371-DAAC8B74E430}
Expand Down
40 changes: 20 additions & 20 deletions tests/Application.UnitTests/Application.UnitTests.csproj
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<RootNamespace>VerticalSliceArchitecture.Application.UnitTests</RootNamespace>
<AssemblyName>VerticalSliceArchitecture.Application.UnitTests</AssemblyName>
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<IsPackable>false</IsPackable>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Moq" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="nunit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="6.2.0" />
<PackageReference Include="Moq" Version="4.16.1" />
</ItemGroup>

<ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Application\Application.csproj" />
</ItemGroup>

</Project>

24 changes: 12 additions & 12 deletions tests/Application.UnitTests/Common/Behaviours/RequestLoggerTests.cs
Original file line number Diff line number Diff line change
@@ -1,39 +1,39 @@
using VerticalSliceArchitecture.Application.Common.Behaviours;
using VerticalSliceArchitecture.Application.Common.Interfaces;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;

using Moq;
using NUnit.Framework;

using VerticalSliceArchitecture.Application.Common.Behaviours;
using VerticalSliceArchitecture.Application.Common.Interfaces;
using VerticalSliceArchitecture.Application.Features.TodoItems;

namespace VerticalSliceArchitecture.Application.UnitTests.Common.Behaviours;

public class RequestLoggerTests
{
private Mock<ILogger<CreateTodoItemCommand>> _logger = null!;
private Mock<ICurrentUserService> _currentUserService = null!;
private readonly Mock<ILogger<CreateTodoItemCommand>> _logger;
private readonly Mock<ICurrentUserService> _currentUserService;

[SetUp]
public void Setup()
public RequestLoggerTests()
{
_logger = new Mock<ILogger<CreateTodoItemCommand>>();
_currentUserService = new Mock<ICurrentUserService>();
}

[Test]
[Fact]
public async Task ShouldCallGetUserNameAsyncOnceIfAuthenticated()
{
_currentUserService.Setup(x => x.UserId).Returns(Guid.NewGuid().ToString());

var requestLogger = new LoggingBehaviour<CreateTodoItemCommand>(_logger.Object, _currentUserService.Object);

await requestLogger.Process(new CreateTodoItemCommand { ListId = 1, Title = "title" }, new CancellationToken());
await requestLogger.Process(new CreateTodoItemCommand { ListId = 1, Title = "title" }, CancellationToken.None);
}

[Test]
[Fact]
public async Task ShouldNotCallGetUserNameAsyncOnceIfUnauthenticated()
{
var requestLogger = new LoggingBehaviour<CreateTodoItemCommand>(_logger.Object, _currentUserService.Object);

await requestLogger.Process(new CreateTodoItemCommand { ListId = 1, Title = "title" }, new CancellationToken());
await requestLogger.Process(new CreateTodoItemCommand { ListId = 1, Title = "title" }, CancellationToken.None);
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
using VerticalSliceArchitecture.Application.Common.Exceptions;
using FluentAssertions;
using FluentValidation.Results;
using NUnit.Framework;
using FluentValidation.Results;

using VerticalSliceArchitecture.Application.Common.Exceptions;

namespace VerticalSliceArchitecture.Application.UnitTests.Common.Exceptions;

public class ValidationExceptionTests
{
[Test]
[Fact]
public void DefaultConstructorCreatesAnEmptyErrorDictionary()
{
var actual = new ValidationException().Errors;

actual.Keys.Should().BeEquivalentTo(Array.Empty<string>());
}

[Test]
[Fact]
public void SingleValidationFailureCreatesASingleElementErrorDictionary()
{
var failures = new List<ValidationFailure>
{
new ValidationFailure("Age", "must be over 18"),
new("Age", "must be over 18"),
};

var actual = new ValidationException(failures).Errors;
Expand All @@ -29,17 +28,17 @@ public void SingleValidationFailureCreatesASingleElementErrorDictionary()
actual["Age"].Should().BeEquivalentTo(new string[] { "must be over 18" });
}

[Test]
[Fact]
public void MulitpleValidationFailureForMultiplePropertiesCreatesAMultipleElementErrorDictionaryEachWithMultipleValues()
{
var failures = new List<ValidationFailure>
{
new ValidationFailure("Age", "must be 18 or older"),
new ValidationFailure("Age", "must be 25 or younger"),
new ValidationFailure("Password", "must contain at least 8 characters"),
new ValidationFailure("Password", "must contain a digit"),
new ValidationFailure("Password", "must contain upper case letter"),
new ValidationFailure("Password", "must contain lower case letter"),
new("Age", "must be 18 or older"),
new("Age", "must be 25 or younger"),
new("Password", "must contain at least 8 characters"),
new("Password", "must contain a digit"),
new("Password", "must contain upper case letter"),
new("Password", "must contain lower case letter"),
};

var actual = new ValidationException(failures).Errors;
Expand Down
21 changes: 8 additions & 13 deletions tests/Application.UnitTests/Common/Mappings/MappingTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Runtime.Serialization;
using AutoMapper;
using AutoMapper;

using VerticalSliceArchitecture.Application.Common.Mappings;
using NUnit.Framework;
using VerticalSliceArchitecture.Application.Domain.Todos;
using VerticalSliceArchitecture.Application.Features.TodoLists;

Expand All @@ -20,28 +19,24 @@ public MappingTests()
_mapper = _configuration.CreateMapper();
}

[Test]
[Fact]
public void ShouldHaveValidConfiguration()
{
_configuration.AssertConfigurationIsValid();
}

[Test]
[TestCase(typeof(TodoList), typeof(TodoListDto))]
[TestCase(typeof(TodoItem), typeof(TodoItemDto))]
[Theory]
[InlineData(typeof(TodoList), typeof(TodoListDto))]
[InlineData(typeof(TodoItem), typeof(TodoItemDto))]
public void ShouldSupportMappingFromSourceToDestination(Type source, Type destination)
{
var instance = GetInstanceOf(source);

_mapper.Map(instance, source, destination);
}

private object GetInstanceOf(Type type)
private static object GetInstanceOf(Type type)
{
if (type.GetConstructor(Type.EmptyTypes) != null)
return Activator.CreateInstance(type)!;

// Type without parameterless constructor
return FormatterServices.GetUninitializedObject(type);
return Activator.CreateInstance(type)!;
}
}
3 changes: 3 additions & 0 deletions tests/Application.UnitTests/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
global using FluentAssertions;

global using Xunit;
16 changes: 6 additions & 10 deletions tests/Application.UnitTests/ValueObjects/ColourTests.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
using FluentAssertions;

using NUnit.Framework;

using VerticalSliceArchitecture.Application.Common.Exceptions;
using VerticalSliceArchitecture.Application.Common.Exceptions;
using VerticalSliceArchitecture.Application.Domain.ValueObjects;

namespace VerticalSliceArchitecture.Application.UnitTests.ValueObjects;

public class ColourTests
{
[Test]
[Fact]
public void ShouldReturnCorrectColourCode()
{
var code = "#FFFFFF";
Expand All @@ -19,31 +15,31 @@ public void ShouldReturnCorrectColourCode()
colour.Code.Should().Be(code);
}

[Test]
[Fact]
public void ToStringReturnsCode()
{
var colour = Colour.White;

colour.ToString().Should().Be(colour.Code);
}

[Test]
[Fact]
public void ShouldPerformImplicitConversionToColourCodeString()
{
string code = Colour.White;

code.Should().Be("#FFFFFF");
}

[Test]
[Fact]
public void ShouldPerformExplicitConversionGivenSupportedColourCode()
{
var colour = (Colour)"#FFFFFF";

colour.Should().Be(Colour.White);
}

[Test]
[Fact]
public void ShouldThrowUnsupportedColourExceptionGivenNotSupportedColourCode()
{
FluentActions.Invoking(() => Colour.From("##FF33CC"))
Expand Down

0 comments on commit 2ee52b0

Please sign in to comment.