Improve testing and some cleanup refactoring.

This commit is contained in:
2026-07-29 11:07:12 +02:00
parent 249a166d07
commit 44846eaa13
15 changed files with 253 additions and 96 deletions
@@ -0,0 +1,33 @@
using FinancialApi.Domain.Entities;
using FluentAssertions;
namespace FinancialApi.Application.UnitTests;
public class AccountTests
{
[Theory]
[InlineData(AccountType.Credit)]
public void GivenCreditAccountType_ShouldAllowNegativeBalance(AccountType accountType)
{
var account = new Account(1, 0, accountType);
var updatedAccount = account.ApplyPosting(100, EntryType.Debit);
updatedAccount.Balance.Should()
.BeNegative();
}
[Theory]
[InlineData(AccountType.Debit)]
[InlineData(AccountType.Revenue)]
[InlineData(AccountType.Liability)]
public void GivenDebitAccountType_ShouldNotAllowNegativeBalance(AccountType accountType)
{
var account = new Account(1, 0, accountType);
var act = () => account.ApplyPosting(100, EntryType.Debit);
act.Should()
.Throw<InsufficientFundsException>();
}
}
@@ -16,8 +16,8 @@ public class ApplyFeeHandlerTests
{ {
// Arrange // Arrange
var command = new ApplyFeeCommand(1, 100); var command = new ApplyFeeCommand(1, 100);
var account = new Account(1, 100, "Debit"); var account = new Account(1, 100, AccountType.Debit);
var revenueAccount = new Account(99999, 0, "Credit"); var revenueAccount = new Account(99999, 0, AccountType.Credit);
var pair = new FeeContext(account, revenueAccount, TimeProvider.System.GetUtcNow()); var pair = new FeeContext(account, revenueAccount, TimeProvider.System.GetUtcNow());
// Act // Act
@@ -36,4 +36,110 @@ public class ApplyFeeHandlerTests
intents.Event.Amount.Should() intents.Event.Amount.Should()
.Be(command.Amount); .Be(command.Amount);
} }
public class LiabilityAccount
{
[Theory]
[InlineData(100.0, 20.0, 80.0)]
[InlineData(199.78, 10.0, 189.78)]
[InlineData(200000, 0.09, 199999.91)]
[InlineData(1000, 1000, 0)]
public void GivenStartingBalanceGreaterThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
var command = new ApplyFeeCommand(1, feeAmount);
var account = new Account(1, startingBalance, AccountType.Liability);
var revenueAccount = new Account(99999, 0, AccountType.Credit);
var pair = new FeeContext(account, revenueAccount, TimeProvider.System.GetUtcNow());
// Act
var intents = ApplyFeeHandler.Handle(command, pair);
// Assert
using var _ = new AssertionScope();
intents.CustomerWrite.Entity.Balance.Should()
.Be(expectedBalance);
}
[Theory]
[InlineData(100.0, 110.0)]
[InlineData(199.78, 200.0)]
[InlineData(200000, 200000.01)]
[InlineData(1000, 1999999)]
public void GivenStartingBalanceLessThanFee_ApplyFee_ShouldFail(decimal startingBalance, decimal feeAmount)
{
var command = new ApplyFeeCommand(1, feeAmount);
var account = new Account(1, startingBalance, AccountType.Liability);
var revenueAccount = new Account(99999, 0, AccountType.Credit);
var pair = new FeeContext(account, revenueAccount, TimeProvider.System.GetUtcNow());
// Act
var act = () => ApplyFeeHandler.Handle(command, pair);
// Assert
using var _ = new AssertionScope();
act.Should()
.Throw<InsufficientFundsException>();
account.Balance.Should()
.Be(startingBalance);
revenueAccount.Balance.Should()
.Be(0);
}
}
public class CreditAccount
{
[Theory]
[InlineData(100.0, 20.0, 80.0)]
[InlineData(199.78, 10.0, 189.78)]
[InlineData(200000, 0.09, 199999.91)]
[InlineData(1000, 1000, 0)]
public void GivenStartingBalanceGreaterThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
var command = new ApplyFeeCommand(1, feeAmount);
var account = new Account(1, startingBalance, AccountType.Credit);
var revenueAccount = new Account(99999, 0, AccountType.Credit);
var pair = new FeeContext(account, revenueAccount, TimeProvider.System.GetUtcNow());
// Act
var intents = ApplyFeeHandler.Handle(command, pair);
// Assert
using var _ = new AssertionScope();
intents.CustomerWrite.Entity.Balance.Should()
.Be(expectedBalance);
}
[Theory]
[InlineData(100.0, 110.0, -10.0)]
[InlineData(199.78, 200.0, -0.22)]
[InlineData(200000, 200000.01, -0.01)]
[InlineData(1000, 1999999, -1998999)]
public void GivenStartingBalanceLessThanFee_ApplyFee_ShouldBeExpectedBalance(
decimal startingBalance,
decimal feeAmount,
decimal expectedBalance
)
{
var command = new ApplyFeeCommand(1, feeAmount);
var account = new Account(1, startingBalance, AccountType.Credit);
var revenueAccount = new Account(99999, 0, AccountType.Credit);
var pair = new FeeContext(account, revenueAccount, TimeProvider.System.GetUtcNow());
// Act
var intents = ApplyFeeHandler.Handle(command, pair);
// Assert
using var _ = new AssertionScope();
intents.CustomerWrite.Entity.Balance.Should()
.Be(expectedBalance);
}
}
} }
@@ -0,0 +1,37 @@
using FinancialApi.Application.Commands;
using FinancialApi.Application.Handlers;
using FinancialApi.Application.Models;
using FinancialApi.Domain.Entities;
using FluentAssertions;
using FluentAssertions.Execution;
using Microsoft.Extensions.Time.Testing;
namespace FinancialApi.Application.UnitTests;
public class ApplyTransferHandlerTests
{
public class ApplyFeeHandlerTests
{
[Fact]
public void GivenValidAccounts_BasicFee_ShouldValidateEverything()
{
// Arrange
var fakeTimeProvider = new FakeTimeProvider();
var command = new TransferFundsCommand(1, 2, 100);
var sourceAccount = new Account(1, 100, AccountType.Liability);
var destAccount = new Account(1, 100, AccountType.Liability);
var transferContext = new TransferContext(sourceAccount, destAccount, fakeTimeProvider.GetUtcNow());
// Act
var intents = TransferFundsHandler.Handle(command, transferContext);
// Assert
using var _ = new AssertionScope();
intents.SourceWrite.Entity.Balance.Should()
.Be(0);
intents.DestWrite.Entity.Balance.Should()
.Be(200);
}
}
}
@@ -9,9 +9,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4"/> <PackageReference Include="coverlet.collector" Version="6.0.4"/>
<PackageReference Include="FluentAssertions" Version="8.10.0" /> <PackageReference Include="FluentAssertions" Version="8.10.0"/>
<PackageReference Include="JasperFx" Version="2.27.0" /> <PackageReference Include="JasperFx" Version="2.27.0"/>
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.6.0" /> <PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.6.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1"/>
<PackageReference Include="xunit" Version="2.9.3"/> <PackageReference Include="xunit" Version="2.9.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4"/> <PackageReference Include="xunit.runner.visualstudio" Version="3.1.4"/>
@@ -22,13 +22,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FinancialApi.Application\FinancialApi.Application.csproj" /> <ProjectReference Include="..\FinancialApi.Application\FinancialApi.Application.csproj"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Wolverine"> <Reference Include="Wolverine">
<HintPath>..\..\..\..\..\..\.nuget\packages\wolverinefx\6.18.0\lib\net10.0\Wolverine.dll</HintPath> <HintPath>..\..\..\..\..\..\.nuget\packages\wolverinefx\6.18.0\lib\net10.0\Wolverine.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -1,3 +1,3 @@
namespace FinancialApi.Application.Commands; namespace FinancialApi.Application.Commands;
public abstract record TransferFundsCommand(int SourceAccountId, int DestinationAccountId, decimal Amount); public record TransferFundsCommand(int SourceAccountId, int DestinationAccountId, decimal Amount);
@@ -7,16 +7,16 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FinancialApi.Domain\FinancialApi.Domain.csproj" /> <ProjectReference Include="..\FinancialApi.Domain\FinancialApi.Domain.csproj"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Extensions.Logging.Abstractions"> <Reference Include="Microsoft.Extensions.Logging.Abstractions">
<HintPath>..\..\..\..\..\..\.nuget\packages\microsoft.extensions.logging.abstractions\10.0.9\lib\net10.0\Microsoft.Extensions.Logging.Abstractions.dll</HintPath> <HintPath>..\..\..\..\..\..\.nuget\packages\microsoft.extensions.logging.abstractions\10.0.9\lib\net10.0\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference> </Reference>
<Reference Include="Wolverine"> <Reference Include="Wolverine">
<HintPath>..\..\..\..\..\..\.nuget\packages\wolverinefx\6.18.0\lib\net10.0\Wolverine.dll</HintPath> <HintPath>..\..\..\..\..\..\.nuget\packages\wolverinefx\6.18.0\lib\net10.0\Wolverine.dll</HintPath>
</Reference> </Reference>
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -31,13 +31,10 @@ public static class ApplyFeeHandler
{ {
var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit); var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit);
var updatedRevenue = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit); var updatedRevenue = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit);
var serviceFee = 0.5m;
var lines = new List<JournalLine> var lines = new List<JournalLine>
{ {
new(updatedSource.Id, cmd.Amount, EntryType.Debit), new(updatedSource.Id, cmd.Amount, EntryType.Debit), new(updatedRevenue.Id, cmd.Amount, EntryType.Credit)
new(updatedRevenue.Id, cmd.Amount - serviceFee, EntryType.Credit),
new(updatedRevenue.Id, serviceFee, EntryType.Credit)
}; };
var journalEntry = BalancedJournal.Create( var journalEntry = BalancedJournal.Create(
@@ -20,7 +20,10 @@ public static class TransferFundsHandler
var source = await query.FindByIdAsync(cmd.SourceAccountId); var source = await query.FindByIdAsync(cmd.SourceAccountId);
var dest = await query.FindByIdAsync(cmd.DestinationAccountId); var dest = await query.FindByIdAsync(cmd.DestinationAccountId);
if (source == null || dest == null) return null; if (source == null || dest == null)
{
return null;
}
return new TransferContext(source, dest, timeProvider.GetUtcNow()); return new TransferContext(source, dest, timeProvider.GetUtcNow());
} }
@@ -28,8 +31,8 @@ public static class TransferFundsHandler
public static ( IStorageAction<Account> SourceWrite, IStorageAction<Account> DestWrite, IStorageAction<JournalEntry> public static ( IStorageAction<Account> SourceWrite, IStorageAction<Account> DestWrite, IStorageAction<JournalEntry>
JournalWrite, FundsTransferredEvent Event ) Handle(TransferFundsCommand cmd, TransferContext context) JournalWrite, FundsTransferredEvent Event ) Handle(TransferFundsCommand cmd, TransferContext context)
{ {
var updatedSource = context.Source.Debit(cmd.Amount); var updatedSource = context.Source.ApplyPosting(cmd.Amount, EntryType.Debit);
var updatedDest = context.Destination.Credit(cmd.Amount); var updatedDest = context.Destination.ApplyPosting(cmd.Amount, EntryType.Credit);
var lines = new List<JournalLine> var lines = new List<JournalLine>
{ {
@@ -6,7 +6,10 @@ public record BalancedJournal
{ {
public JournalEntry Entry { get; } public JournalEntry Entry { get; }
private BalancedJournal(JournalEntry entry) => Entry = entry; private BalancedJournal(JournalEntry entry)
{
Entry = entry;
}
public static BalancedJournal Create(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines) public static BalancedJournal Create(Guid id, string description, DateTimeOffset createdAt, List<JournalLine> lines)
{ {
@@ -22,7 +25,7 @@ public record BalancedJournal
); );
} }
return new(new JournalEntry(id, description, createdAt, lines)); return new BalancedJournal(new JournalEntry(id, description, createdAt, lines));
} }
public static BalancedJournal CreateReversal(JournalEntry original, string reason, DateTimeOffset now) public static BalancedJournal CreateReversal(JournalEntry original, string reason, DateTimeOffset now)
@@ -1,54 +1,32 @@
namespace FinancialApi.Domain.Entities; namespace FinancialApi.Domain.Entities;
public record Account(int Id, decimal Balance, string AccountType) public enum AccountType
{
Liability,
Debit,
Credit,
Revenue
}
public record Account(int Id, decimal Balance, AccountType Type)
{ {
public Account ApplyPosting(decimal amount, EntryType entryType) public Account ApplyPosting(decimal amount, EntryType entryType)
{ {
if (amount <= 0) if (amount <= 0)
{ {
throw new ArgumentException("Credit amount must be positive."); throw new ArgumentException("Amount must be positive.");
} }
var newBalance = Balance; var newBalance = entryType == EntryType.Credit ? Balance + amount : Balance - amount;
if (AccountType == "Revenue") ;
{
newBalance = entryType == EntryType.Credit ? newBalance + amount : newBalance - amount;
}
else
{
newBalance = entryType == EntryType.Debit ? newBalance - amount : newBalance + amount;
}
if (newBalance < 0 && AccountType == "Liability") if (newBalance < 0 && Type is AccountType.Liability or AccountType.Debit or AccountType.Revenue)
{ {
throw new InvalidOperationException("Insufficient funds."); throw new InsufficientFundsException("Insufficient funds.");
} }
return this with { Balance = newBalance }; return this with { Balance = newBalance };
} }
}
public Account Debit(decimal amount) public class InsufficientFundsException(string insufficientFunds) : Exception(insufficientFunds);
{
if (amount <= 0)
{
throw new ArgumentException("Debit amount must be positive.");
}
if (Balance - amount < 0)
{
throw new InvalidOperationException("Insufficient funds.");
}
return this with { Balance = Balance - amount };
}
public Account Credit(decimal amount)
{
if (amount <= 0)
{
throw new ArgumentException("Credit amount must be positive.");
}
return this with { Balance = Balance + amount };
}
}
@@ -16,9 +16,9 @@ public class AccountDbContext(DbContextOptions<AccountDbContext> options) : DbCo
modelBuilder.Entity<Account>() modelBuilder.Entity<Account>()
.HasData( .HasData(
new Account(1, 10000000.00m, "Credit"), new Account(1, 10000000.00m, AccountType.Credit),
new Account(2, 50000000.00m, "Liability"), new Account(2, 50000000.00m, AccountType.Liability),
new Account(99999, 0.00m, "Revenue") new Account(99999, 0.00m, AccountType.Revenue)
); );
modelBuilder.Entity<JournalEntry>(builder => modelBuilder.Entity<JournalEntry>(builder =>
@@ -7,16 +7,16 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FinancialApi.Application\FinancialApi.Application.csproj" /> <ProjectReference Include="..\FinancialApi.Application\FinancialApi.Application.csproj"/>
<ProjectReference Include="..\FinancialApi.Domain\FinancialApi.Domain.csproj" /> <ProjectReference Include="..\FinancialApi.Domain\FinancialApi.Domain.csproj"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.9" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.9"/>
<PackageReference Include="WolverineFx" Version="6.18.0" /> <PackageReference Include="WolverineFx" Version="6.18.0"/>
<PackageReference Include="WolverineFx.EntityFrameworkCore" Version="6.18.0" /> <PackageReference Include="WolverineFx.EntityFrameworkCore" Version="6.18.0"/>
<PackageReference Include="WolverineFx.Sqlite" Version="6.18.0" /> <PackageReference Include="WolverineFx.Sqlite" Version="6.18.0"/>
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -8,15 +8,15 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" /> <FrameworkReference Include="Microsoft.AspNetCore.App"/>
<PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="10.7.0" /> <PackageReference Include="Microsoft.Extensions.Http.Resilience" Version="10.7.0"/>
<PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="10.7.0" /> <PackageReference Include="Microsoft.Extensions.ServiceDiscovery" Version="10.7.0"/>
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.16.0" /> <PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.16.0"/>
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.16.0" /> <PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.16.0"/>
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.16.0" /> <PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.16.0"/>
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.16.0" /> <PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.16.0"/>
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.16.0" /> <PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.16.0"/>
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -7,16 +7,16 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9"/>
<PackageReference Include="Microsoft.OpenApi" Version="2.10.0" /> <PackageReference Include="Microsoft.OpenApi" Version="2.10.0"/>
<PackageReference Include="WolverineFx" Version="6.18.0" /> <PackageReference Include="WolverineFx" Version="6.18.0"/>
<PackageReference Include="WolverineFx.Http" Version="6.18.0" /> <PackageReference Include="WolverineFx.Http" Version="6.18.0"/>
<PackageReference Include="WolverineFx.RuntimeCompilation" Version="6.18.0" /> <PackageReference Include="WolverineFx.RuntimeCompilation" Version="6.18.0"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\FinancialApi.Infrastructure\FinancialApi.Infrastructure.csproj" /> <ProjectReference Include="..\FinancialApi.Infrastructure\FinancialApi.Infrastructure.csproj"/>
<ProjectReference Include="..\FinancialApi.ServiceDefaults\FinancialApi.ServiceDefaults.csproj" /> <ProjectReference Include="..\FinancialApi.ServiceDefaults\FinancialApi.ServiceDefaults.csproj"/>
</ItemGroup> </ItemGroup>
</Project> </Project>
@@ -7,8 +7,8 @@ Accept: application/json
Content-Type: application/json Content-Type: application/json
{ {
"accountId": 1, "accountId": 1,
"amount": 50.0 "amount": 50.0
} }
### Transfer Between Accounts ### Transfer Between Accounts
@@ -17,9 +17,9 @@ POST {{FinancialApi_HostAddress}}/accounts/transfer
Content-Type: application/json Content-Type: application/json
{ {
"sourceAccountId": 1, "sourceAccountId": 1,
"destinationAccountId": 2, "destinationAccountId": 2,
"amount": 1000.00 "amount": 1000.00
} }
### Reverse a Journal Entry ### Reverse a Journal Entry
@@ -28,8 +28,8 @@ POST {{FinancialApi_HostAddress}}/journal/reverse
Content-Type: application/json Content-Type: application/json
{ {
"originalJournalId": "FD2BFD8E-7C85-4CAD-A12B-CCBCD7C12B4A", "originalJournalId": "B65EB28C-7EC1-4B70-9069-06A61A4FE857",
"reason": "Incorrect Account Fee" "reason": "Incorrect Account Fee"
} }
### Events ### Events