Laravel feature and unit tests, with a real app · Part 2 of 6
Unit tests on the billing domain
Invoice totals, numbering, due dates and money formatting as pure PHP classes, tested with datasets and fixed dates in a tenth of a second, and the rule that keeps them out of the models.
By Abhishek Fouzdar · Updated
This part writes the arithmetic an invoice needs as plain PHP classes and tests them without booting Laravel. By the end there are 57 tests, 46 of them unit tests that run in a tenth of a second, and a clear rule for which code goes where. Part 1 set up the app; the series introduction explains InvoiceMini.
Why the arithmetic leaves the model
An invoice's totals depend on its lines, so the obvious home for the calculation is a method on the Invoice model that reads $this->lines. That works, and it makes every test of the arithmetic a feature test: boot the app, migrate, create a company, a client, an invoice and three lines, then check a number. Thirty lines of setup to test one rounding rule, and twelve rounding rules to test.
Put the calculation in a class that takes plain values and the test becomes: build three value objects, call one method, check four integers. The model keeps a thin recalculate() that converts its lines and stores the result, and that one method gets one feature test. The rule, which part 5 turns into an architecture test: anything under app/Billing that is not an action must not know Eloquent exists.
The lines and the totals
A line is a readonly class that refuses to exist with values an invoice cannot have:
final readonly class LineItem
{
public function __construct(
public float $quantity,
public int $unitPrice,
public float $taxRate,
) {
if ($quantity <= 0) {
throw new \InvalidArgumentException('Quantity must be positive.');
}
if ($unitPrice < 0) {
throw new \InvalidArgumentException('Unit price cannot be negative.');
}
if ($taxRate < 0 || $taxRate > 100) {
throw new \InvalidArgumentException('Tax rate must be between 0 and 100.');
}
}
/** The line's net amount in minor units, rounded half up like an accountant would. */
public function net(): int
{
return (int) round($this->unitPrice * $this->quantity, 0, PHP_ROUND_HALF_UP);
}
}
The calculator applies four rules in order, and the order is the part a tax office cares about:
final class TotalsCalculator
{
/** @param list<LineItem> $lines */
public function calculate(array $lines, float $discountPercent = 0): Totals
{
if ($discountPercent < 0 || $discountPercent > 100) {
throw new \InvalidArgumentException('Discount must be between 0 and 100 percent.');
}
if ($lines === []) {
return Totals::zero();
}
$subtotal = array_sum(array_map(fn (LineItem $line) => $line->net(), $lines));
$discount = self::percentOf($subtotal, $discountPercent);
$tax = 0;
foreach ($lines as $line) {
$taxable = $line->net() - self::percentOf($line->net(), $discountPercent);
$tax += self::percentOf($taxable, $line->taxRate);
}
return new Totals($subtotal, $discount, $tax, $subtotal - $discount + $tax);
}
private static function percentOf(int $amount, float $percent): int
{
return (int) round($amount * $percent / 100, 0, PHP_ROUND_HALF_UP);
}
}
Each line's net is rounded on its own. The discount is a percentage of the subtotal, rounded once. Tax is computed per line on that line's discounted net, because lines carry different rates, and rounded per line, because that is what the printed invoice shows. The total is subtotal minus discount plus tax. Totals is a four-integer value object with a toArray() the model uses to store them.
Testing it
Each rule is a test, and each test reads like the rule:
<?php
use App\Billing\LineItem;
use App\Billing\TotalsCalculator;
it('taxes each line at its own rate', function () {
$totals = (new TotalsCalculator)->calculate([
new LineItem(quantity: 1, unitPrice: 100_00, taxRate: 20), // design work
new LineItem(quantity: 1, unitPrice: 100_00, taxRate: 7), // books, reduced rate
new LineItem(quantity: 1, unitPrice: 100_00, taxRate: 0), // export, zero-rated
]);
expect($totals->tax)->toBe(27_00)
->and($totals->total)->toBe(327_00);
});
it('applies a percentage discount before tax', function () {
$totals = (new TotalsCalculator)->calculate([
new LineItem(quantity: 10, unitPrice: 80_00, taxRate: 20), // 800.00
], discountPercent: 10);
expect($totals->toArray())->toBe([
'subtotal' => 800_00,
'discount' => 80_00,
'tax' => 144_00, // 20 % of 720.00, not of 800.00
'total' => 864_00,
]);
});
it('rejects lines that cannot exist', function (float $quantity, int $unitPrice, float $taxRate) {
new LineItem($quantity, $unitPrice, $taxRate);
})->with([
'zero quantity' => [0, 100, 20],
'negative quantity' => [-1, 100, 20],
'negative price' => [1, -100, 20],
'tax over 100' => [1, 100, 101],
])->throws(InvalidArgumentException::class);
Three things to take from these. Numeric literals with underscores, 100_00, are PHP, not Pest, and they let an integer amount read as the money it is; a reviewer sees 100.00 without doing arithmetic. ->and() continues an expectation chain on a new value, so one test checks related numbers without four expect() calls. ->throws() on the test declares that the closure must throw the class, and with a dataset it checks every case; it replaces the old pattern of expectException() before the call. toBe() is strict identity, ===, which is what you want for integers and the reason the money is never a float.
The test that earns its keep is the one about rounding disagreements:
it('keeps the total consistent when per-line discounts round differently from the invoice discount', function () {
// Two lines of 0.05 each, 10 % off. Per line the discount is 0.005 → rounds to 0.01 each.
// On the subtotal (0.10) it is 0.01. The tax base loses a cent; the total does not.
$totals = (new TotalsCalculator)->calculate([
new LineItem(quantity: 1, unitPrice: 5, taxRate: 20),
new LineItem(quantity: 1, unitPrice: 5, taxRate: 20),
], discountPercent: 10);
expect($totals->subtotal)->toBe(10)
->and($totals->discount)->toBe(1)
->and($totals->tax)->toBe(2) // 20 % of (4 + 4) = 1.6 → 2
->and($totals->total)->toBe(10 - 1 + 2);
});
Rounding the discount per line and once on the subtotal can disagree by a cent on awkward numbers. The calculator uses the subtotal's figure for the total and the per-line figures for the tax, and this test pins that choice. Someone will "fix" it one day; the test will explain why it was deliberate. Tests like this are cheap only because the class is pure: the same case through the model would need two lines, an invoice, and a database.
Three more classes, same shape
Invoice numbers look like INV-2026-0007. The class formats, parses, and computes the next number given the last one; finding the last one needs the database and is the caller's job, so the class stays pure:
it('continues the sequence within a year', function () {
expect(InvoiceNumber::next('INV-2026-0041', 'INV', 2026))->toBe('INV-2026-0042');
});
it('restarts the sequence in a new year', function () {
expect(InvoiceNumber::next('INV-2026-0041', 'INV', 2027))->toBe('INV-2027-0001');
});
it('refuses strings that are not invoice numbers', function (string $bad) {
InvoiceNumber::parse($bad);
})->with(['INV-26-0001', 'INV-2026-1', '2026-0001', ''])->throws(InvalidArgumentException::class);
Due dates are the issue date plus the company's terms, moved to Monday when they land on a weekend. The tests use fixed dates, never now(), so they give the same answer on a Sunday in 2031:
it('moves a weekend due date to the following Monday', function (string $issued, int $terms, string $expected) {
expect(DueDate::compute(CarbonImmutable::parse($issued), $terms)->toDateString())->toBe($expected);
})->with([
'lands on Saturday' => ['2026-10-10', 14, '2026-10-26'], // 24 Oct is a Saturday
'lands on Sunday' => ['2026-10-11', 14, '2026-10-26'], // 25 Oct is a Sunday
'lands on Friday, untouched' => ['2026-10-09', 14, '2026-10-23'],
]);
it('does not mutate the issue date it was given', function () {
$issued = CarbonImmutable::parse('2026-10-05');
DueDate::compute($issued, 30);
expect($issued->toDateString())->toBe('2026-10-05');
});
The second test exists because the class takes CarbonImmutable, and a future edit that changes the parameter to mutable Carbon would make addDays() modify the caller's date. A test that names a bug class is better than a comment that warns about it.
Money formatting turns minor units into a string per currency, and the currency decides the decimals. Most have two; the yen has none; the Kuwaiti dinar has three:
it('formats minor units in the currency\'s own decimals', function (int $minor, string $currency, string $expected) {
expect(Money::format($minor, $currency))->toBe($expected);
})->with([
'euro' => [1234_56, 'EUR', '€1,234.56'],
'dollar' => [99, 'USD', '$0.99'],
'yen has no minor unit' => [1234, 'JPY', '¥1,234'],
// intl separates a code from the number with a non-breaking space, not a space.
'dinar has three' => [1234, 'KWD', "KWD\u{a0}1.234"],
]);
The class is twenty lines over NumberFormatter, which needs the intl extension; part 5's workflow installs it on the runner. The dinar line failed on its first run and is the first entry under what went wrong.
The model keeps a thin method
Invoice::recalculate() is all the model knows about totals:
public function recalculate(): Totals
{
$lines = $this->lines()->get()->map(fn (InvoiceLine $line) => new LineItem(
quantity: (float) $line->quantity,
unitPrice: $line->unit_price,
taxRate: (float) $line->tax_rate,
))->all();
$totals = (new TotalsCalculator)->calculate($lines, (float) $this->discount_percent);
$this->forceFill($totals->toArray())->save();
return $totals;
}
It reads a relation and saves, so its test is a feature test in part 3, and there is exactly one, checking that lines in the database become totals in the database. The twelve rounding rules are not re-tested there. Decimal columns come back from Eloquent as strings, hence the casts; forgetting them is a TypeError on the readonly constructor, which is the constructor doing its job.
Run it
./vendor/bin/pest tests/Unit
PASS Tests\Unit\Billing\DueDateTest
PASS Tests\Unit\Billing\InvoiceNumberTest
PASS Tests\Unit\Billing\MoneyTest
PASS Tests\Unit\Billing\TotalsCalculatorTest
PASS Tests\Unit\InvoiceStatusTest
Tests: 46 passed (56 assertions)
Duration: 0.16s
Forty-six tests in 0.16 seconds, and most of that is PHP starting. Run the whole suite and it is 57 tests in 0.63 seconds; the eleven feature tests from part 1 cost more than all the unit tests together. That is not a complaint about feature tests. It is the reason to keep arithmetic out of them.
The part 2 commit has the four classes and their tests.
What went wrong
Failed asserting that two strings are identical: -'KWD 1.234' +'KWD 1.234'. Two strings that print the same and are not the same. NumberFormatter puts a non-breaking space, U+00A0, between a currency code and the number; my expectation had a normal space. The fix is "KWD\u{a0}1.234" and a comment, because the next person will hit it too. When a string assertion fails on identical-looking output, diff the bytes.
Rounding and floats. 7 × 1.115 is 7.805, which a float stores as a hair under. PHP's round() corrects for that and gives 7.81; a hand-rolled floor($x + 0.5) would give 7.80. The test for fractional quantities exists so the calculator cannot quietly swap one for the other.
Decimal columns are strings. Eloquent returns a decimal column as "1.50", and a readonly constructor typed float refuses it. The (float) casts in recalculate() are the fix, and the single feature test of that method is what caught it.
Part 3 puts the invoice flows behind routes and tests them the way a user reaches them.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
2 / 6