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);
}
}
}
@@ -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);
@@ -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)
{
if (amount <= 0)
{
throw new ArgumentException("Debit amount must be positive.");
} }
if (Balance - amount < 0) public class InsufficientFundsException(string insufficientFunds) : Exception(insufficientFunds);
{
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 =>
@@ -28,7 +28,7 @@ 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"
} }