Skip to content

Fixtures, data rows and assertions

A test gets the values it needs from a fixture or a data row. A fixture is a method that builds a value once, and each test that needs the value gets it as a parameter. A data row is one set of arguments for a test, and the test runs once for each row. A hook is a method that runs before or after the tests, for example to delete a file. An assertion checks a value. The attribute #[TestOnly] marks a class or method that only tests can use.

Fixtures

A fixture is a value your tests share. It is built once, and every test that needs it is called with it.

You write a public static method and put #[Fixture] above it. The type that method returns is what the fixture supplies. Every test in the same class that declares a parameter of that type is called with the value. The name of the parameter does not matter, only its type. A fixture may declare a parameter as well, so one fixture can be built from another.

The method runs once for the whole class, before the tests. Each test then works on its own copy, so a change one test makes is not visible to another. Setup that costs time, such as reading a file or building a large object, happens one time. Each test runs on its own, so without a fixture this setup runs once for every test.

Good to know: a fixture belongs to its own class, and a test cannot use another class's fixture. A parameter that no fixture supplies does not compile.

One value for every test

<?nvs
// Shows how every test gets one value. `#[Fixture]` goes above a `public static`
// method, and the type that method returns is what it supplies.
use Core\Test;
use Core\Test\Fixture;
class ShippingRates
{
public function constructor(public int $baseCents, public int $perItemCents)
{}
public function totalCents(int $items): int
{
return $this->baseCents + $this->perItemCents * $items;
}
}
class ShippingRatesTest
{
// This method runs once for the whole class. Every test below that declares
// a `ShippingRates` parameter is called with what it returns.
#[Fixture]
public static function rates(): ShippingRates
{
return new ShippingRates(499, 120);
}
#[Test]
public function threeItemsPayTheBaseAndThreeItems(ShippingRates $rates): void
{
Test::assertSame($rates->totalCents(3), 859);
}
// The type of the parameter says which fixture fills it. The name is yours
// to choose.
#[Test]
public function anEmptyOrderPaysTheBase(ShippingRates $anyNameYouLike): void
{
Test::assertSame($anyNameYouLike->totalCents(0), 499);
}
}
// This prints 859.
ShippingRates $rates = new ShippingRates(499, 120);
echo $rates->totalCents(3), "\n";
Output
859

A fixture built from another fixture

<?nvs
// Shows a fixture built from another fixture. A `#[Fixture]` method may declare
// a parameter too, and it is filled the same way a test's parameter is.
use Core\Test;
use Core\Test\Fixture;
class Settings
{
public function constructor(public string $host)
{}
}
class Mailer
{
public function constructor(public Settings $settings)
{}
public function route(string $address): string
{
return $address . ' via ' . $this->settings->host;
}
}
class MailerTest
{
#[Fixture]
public static function settings(): Settings
{
return new Settings('smtp.example.com');
}
// This fixture needs a `Settings`, so it is built after the one above. The
// order you write the two methods in does not matter.
#[Fixture]
public static function mailer(Settings $settings): Mailer
{
return new Mailer($settings);
}
#[Test]
public function itRoutesThroughTheConfiguredHost(Mailer $mailer): void
{
Test::assertSame($mailer->route('ana@example.com'), 'ana@example.com via smtp.example.com');
}
// A test may declare both. Each parameter is filled from its own type.
#[Test]
public function bothFixturesReachOneTest(Mailer $mailer, Settings $settings): void
{
Test::assertSame($mailer->settings->host, $settings->host);
}
}
// This prints `ana@example.com via smtp.example.com`.
Mailer $mailer = new Mailer(new Settings('smtp.example.com'));
echo $mailer->route('ana@example.com'), "\n";
Output
ana@example.com via smtp.example.com

Setup that happens once

<?nvs
// Shows the use a fixture is really for. Setup that costs time happens one time
// for the whole class, and each test works with the result.
use Core\Test;
use Core\Test\Fixture;
// A user as a login form checks it: a name and a stored password hash.
class Account
{
public function constructor(public string $name, public string $hash)
{}
public function logIn(secret string $typed): bool
{
return Core\Password::verify($typed, $this->hash);
}
}
class AccountTest
{
// `Core\Password::hash` takes a long time, so guessing a password is slow.
// This fixture runs it once. Without the fixture, every test runs it.
#[Fixture]
public static function account(): Account
{
return new Account('ada', Core\Password::hash('correct horse'));
}
#[Test]
public function theRightPasswordLogsIn(Account $account): void
{
Test::assertTrue($account->logIn('correct horse'));
}
#[Test]
public function aWrongPasswordDoesNotLogIn(Account $account): void
{
Test::assertSame($account->logIn('wrong horse'), false);
}
#[Test]
public function anEmptyPasswordDoesNotLogIn(Account $account): void
{
Test::assertSame($account->logIn(''), false);
}
}
// This prints `true`.
Account $account = new Account('ada', Core\Password::hash('correct horse'));
echo $account->logIn('correct horse') ? 'true' : 'false', "\n";
Output
true

Details

A fixture method that is not static or not public, or that returns void, is E0735. A #[Fixture] with a field, such as #[Fixture(name: "x")], is E0454.

Two fixtures of one class that return the same type are E0304. Fixtures that need each other, such as s needing r and r needing s, are E0737, and the message shows the cycle.

The type must be the same. A fixture that returns a subclass S2 does not fill a parameter of type S, and that parameter is E0736. A fixture may return any type, such as int, ?int or array<int>.

A fixture is built only when a test that runs needs it. A fixture that only skipped tests need is not built.

A fixture that throws an error makes each test that needs it fail, with the error's message. The other tests of the class still run.

A variadic or inout parameter on a test method is E0733.

A fixture method is test code, like a test method. Only a test, a fixture or a class hook may call it. A call from other code is the compile error E0889. nvs run and nvs build do not compile it.

Data rows

A data row gives one test a set of values. You write one row for each set, and each row is reported as its own case.

#[TestWith(name: value, …)] goes above a #[Test] method. Each field of the row names one parameter of that method, and the value is a constant. Repeat #[TestWith] for every set of values you want. The runner calls the method once per row, in the order you wrote the rows, and reports them as method#0, method#1 and so on. A row that fails is reported on its own, and the rows after it still run.

Rows and fixtures work together in one test. A parameter that a row names is filled by the row. A parameter that no row names is filled by the fixture of that type.

Good to know: every row of a method fills the same parameters, and a field that names no parameter does not compile.

One row for each case

<?nvs
// Shows how to give one test several sets of values. Each `#[TestWith]` row is
// its own case, so a row that fails does not stop the rows after it.
use Core\Test;
use Core\Test\TestWith;
class Band
{
public static function of(uint $orders): string
{
if ($orders >= 100) {
return 'gold';
}
if ($orders >= 10) {
return 'silver';
}
return 'bronze';
}
}
class BandTest
{
// Each field of a row names one parameter below. The values are constants.
#[TestWith(orders: 0, want: 'bronze')]
#[TestWith(orders: 10, want: 'silver')]
#[TestWith(orders: 100, want: 'gold')]
#[Test]
public function itNamesTheBandOfAnOrderCount(uint $orders, string $want): void
{
Test::assertSame(Band::of($orders), $want);
}
}
// This prints `bronze silver gold`.
echo Band::of(0), ' ', Band::of(10), ' ', Band::of(100), "\n";
Output
bronze silver gold

Rows and a fixture in one test

<?nvs
// Shows rows and a fixture in one test. A parameter a row names is filled by the
// row. A parameter no row names is filled by the fixture of that type.
use Core\Test;
use Core\Test\Fixture;
use Core\Test\TestWith;
class Vat
{
public function constructor(public int $percent)
{}
// The tax on an amount in cents. 19 percent of 1000 cents is 190 cents.
public function on(int $cents): int
{
return Core\Math::quotient($cents * $this->percent, 100);
}
}
class VatTest
{
// The same rate for every row, built once for the whole class.
#[Fixture]
public static function vat(): Vat
{
return new Vat(19);
}
// `$cents` and `$want` come from the row. `$vat` comes from the fixture.
#[TestWith(cents: 100, want: 19)]
#[TestWith(cents: 1000, want: 190)]
#[TestWith(cents: 0, want: 0)]
#[Test]
public function itTaxesAnAmountInCents(int $cents, int $want, Vat $vat): void
{
Test::assertSame($vat->on($cents), $want);
}
}
// This prints 190.
Vat $vat = new Vat(19);
echo $vat->on(1000), "\n";
Output
190

A table of permissions

<?nvs
// Shows the rows for a check that returns `true` or `false`. There is one row
// for each combination of the inputs, and each row gives the expected result.
use Core\Test;
use Core\Test\TestWith;
class Access
{
// An editor may change any article. Anybody else may change only their own.
public static function canEdit(string $role, bool $isAuthor): bool
{
if ($role == 'editor') {
return true;
}
return $isAuthor;
}
}
class AccessTest
{
// Four rows for the four combinations, so no case is left untested.
#[TestWith(role: 'editor', isAuthor: true, want: true)]
#[TestWith(role: 'editor', isAuthor: false, want: true)]
#[TestWith(role: 'writer', isAuthor: true, want: true)]
#[TestWith(role: 'writer', isAuthor: false, want: false)]
#[Test]
public function itAnswersEveryCombination(string $role, bool $isAuthor, bool $want): void
{
Test::assertSame(Access::canEdit($role, $isAuthor), $want);
}
}
// This prints `true` and then `false`.
echo Access::canEdit('editor', false) ? 'true' : 'false', "\n";
echo Access::canEdit('writer', false) ? 'true' : 'false', "\n";
Output
true
false

A row that fails

<?nvs
// Shows the report for a test with three rows. Each row is its own case, and
// the third one fails.
// proof: test
// proof: exit 1
use Core\Test;
use Core\Test\TestWith;
final class Slug
{
public static function of(string $title): string
{
return Core\Str::lower(Core\Str::replace(Core\Str::trim($title), ' ', '-'));
}
}
final class SlugTest
{
// The report names the rows `itSlugs#0`, `itSlugs#1` and `itSlugs#2`.
#[TestWith(title: 'Hello World', want: 'hello-world')]
#[TestWith(title: ' padded ', want: 'padded')]
#[TestWith(title: 'Mixed Case', want: 'mixed case')]
#[Test]
public function itSlugs(string $title, string $want): void
{
Test::assertSame(Slug::of($title), $want);
}
}
Output
SlugTest
✓ itSlugs#0
✓ itSlugs#1
✗ itSlugs#2
Core\Test::assertSame failed: `$actual` is "mixed-case", `$expected` is "mixed case"
1 failed, 2 passed, 0 skipped, 0 flaky

Details

A row value is a literal of the parameter's type: an int, uint, float, bool or string written in the code. An int literal also fills a float parameter. A class constant, an enum case, an array and a negative number for a uint are E0738.

A field that names no parameter is E0738, and so is a value of the wrong type. A field given twice in one row is E0304. A row that leaves out a parameter that another row fills is E0738.

#[TestWith] on a method without #[Test] is E0738. A parameter with no row and no fixture is E0736.

When a row and a fixture can both fill a parameter, the row is used.

skip: on a test with rows skips every row, and each row is reported as skipped. With retries:, each row gets its own attempts.

--filter selects a single row by its name, such as --filter SlugTest::itSlugs#1.

Hooks

A hook is a method that the test runner calls around your tests. You use one to clean up something a test leaves outside itself, such as a file or a database table.

  • #[BeforeClass] runs once, before the tests of the class. It is a public static method.
  • #[AfterClass] runs once, after the last test. It is a public static method. It can take a Core\Test\Summary, which has the counts of passed and failed tests.
  • #[AfterEachTest] runs after each test, on the same object as the test. It can take a Core\Test\Outcome, which has the name of the test and whether it passed.

The after hooks also run when a test fails. #[AfterClass] also runs when #[BeforeClass] throws an error.

To prepare each test, use the constructor. To share a value with the tests, use a fixture.

Good to know: a class has at most one hook of each kind. A subclass inherits the hooks of its parent class.

Remove the file a test wrote

<?nvs
// Shows `#[AfterEachTest]` removing the file a test wrote, so the next run starts
// without it.
use Core\IO;
use Core\Path;
use Core\Test;
use Core\Test\AfterEachTest;
class ShoppingList
{
public static function text(array<string> $items): string
{
string $text = '';
foreach ($items as string $item) {
$text = $text . '- ' . $item . "\n";
}
return $text;
}
}
class ShoppingListTest
{
public string $file;
public function constructor()
{
$this->file = Path::fromWorkingDirectory('shopping-list-test.txt');
}
#[Test]
public function itWritesOneLinePerItem(): void
{
IO::write($this->file, ShoppingList::text(['bread', 'milk']));
Test::assertSame(IO::readText($this->file), "- bread\n- milk\n");
}
// This runs after the test, also when the test fails.
#[AfterEachTest]
public function removeTheFile(): void
{
IO::remove($this->file);
}
}
// This prints `- bread`, then `- milk`.
echo ShoppingList::text(['bread', 'milk']);
Output
- bread
- milk

Create a table once for the class

<?nvs
// Shows `#[BeforeClass]` creating a database table once for the class, and
// `#[AfterClass]` deleting it after the last test.
use Core\Db;
use Core\Test;
use Core\Test\AfterClass;
use Core\Test\BeforeClass;
class Seed
{
// This builds one `insert` statement for many products.
public static function insertProducts(array<string> $names): string
{
string $values = '';
foreach ($names as string $name) {
if ($values != '') {
$values = $values . ', ';
}
$values = $values . "('" . $name . "')";
}
return 'insert into products (name) values ' . $values;
}
}
class ProductTest
{
// The table is outside every test, so a hook creates it one time.
#[BeforeClass]
public static function createTable(): void
{
var $db = Db::connect('test');
$db->execute('create table products (name text)', []);
$db->execute(Seed::insertProducts(['tea', 'cake']), []);
}
// `db: "test"` undoes what the test writes, so every test sees two rows.
#[Test(db: 'test')]
public function itFindsTheSeededProducts(): void
{
var $rows = Db::connect('test')->query('select name from products', []);
Test::assertCount($rows->all(), 2);
}
// This runs after the last test, also when a test failed.
#[AfterClass]
public static function dropTable(): void
{
Db::connect('test')->execute('drop table products', []);
}
}
// This prints the statement `createTable` runs.
echo Seed::insertProducts(['tea', 'cake']), "\n";
Output
insert into products (name) values ('tea'), ('cake')

Keep the log of a failed test

<?nvs
// Shows hooks that keep the log of a failed test and delete the log of a passed
// one. A build server can then show the logs of the failed tests.
use Core\IO;
use Core\Path;
use Core\Test;
use Core\Test\AfterClass;
use Core\Test\AfterEachTest;
use Core\Test\Outcome;
use Core\Test\Summary;
class Evidence
{
// A retry is a new attempt, so the attempt number is part of the name.
public static function fileName(string $class, string $test, int $attempt): string
{
return $class . '-' . $test . '-' . $attempt . '.log';
}
}
class CheckoutTest
{
public string $log;
public function constructor()
{
$this->log = Path::fromWorkingDirectory('checkout-test.log');
}
#[Test]
public function itAddsTheShippingCost(): void
{
// The prices are in cents.
IO::write($this->log, "total 1250, shipping 490\n");
Test::assertSame(1250 + 490, 1740);
}
// `Outcome` says which test ran and whether it passed.
#[AfterEachTest]
public function keepTheLogIfItFailed(Outcome $outcome): void
{
if ($outcome->hasPassed()) {
IO::remove($this->log);
} else {
string $name = Evidence::fileName($outcome->class(), $outcome->name(), $outcome->attempt());
IO::move($this->log, Path::fromWorkingDirectory($name));
}
}
// `Summary` has the counts for the whole class.
#[AfterClass]
public static function report(Summary $summary): void
{
echo $summary->failed(), " failed, their logs are kept\n";
}
}
// This prints `CheckoutTest-itAddsTheShippingCost-2.log`.
echo Evidence::fileName('CheckoutTest', 'itAddsTheShippingCost', 2), "\n";
Output
CheckoutTest-itAddsTheShippingCost-2.log

The order the hooks run in

<?nvs
// Shows the order the hooks run in. `#[BeforeClass]` runs before the tests,
// and `#[AfterClass]` runs after them with the counts.
// proof: test
use Core\Test;
use Core\Test\AfterClass;
use Core\Test\AfterEachTest;
use Core\Test\BeforeClass;
use Core\Test\Outcome;
use Core\Test\Summary;
final class HookTest
{
#[BeforeClass]
public static function createTable(): void
{
echo "create the table\n";
}
#[AfterClass]
public static function dropTable(Summary $summary): void
{
echo 'drop the table, ', $summary->passed(), " passed\n";
}
// This hook runs after each test. Its output is shown only when the
// test fails, so this run does not print it.
#[AfterEachTest]
public function removeFiles(Outcome $outcome): void
{
echo 'remove the files of ', $outcome->name(), "\n";
}
#[Test]
public function first(): void
{
Test::assertSame(1 + 1, 2);
}
#[Test]
public function second(): void
{
Test::assertSame(2 + 2, 4);
}
}
Output
HookTest
create the table
✓ first
✓ second
drop the table, 2 passed
0 failed, 2 passed, 0 skipped, 0 flaky

Details

#[BeforeClass] takes no parameters. #[AfterClass] may take one Core\Test\Summary, and #[AfterEachTest] one Core\Test\Outcome. A hook with another parameter is E0862. So is a hook that returns a value or is not public. A class hook must be static, and #[AfterEachTest] must not be. Each of those is E0862 too.

A second hook of one kind in a class is E0304.

#[BeforeClass] and #[AfterClass] may not write a static property. That is E0863. Each test reads the declared value, so a fixture is the way to give the tests a value. #[AfterEachTest] runs with the test, and it may write one.

The class hooks run in this order: #[BeforeClass], then the fixtures, then the tests, then #[AfterClass]. They run when every test of the class is skipped. They do not run for a class with no test, or for a class that --filter leaves out.

What a class hook prints with echo is part of the report, under the class name. What #[AfterEachTest] prints belongs to the test, so it is shown only when the test fails.

#[AfterEachTest] runs after every attempt of a test, so also after each retry. It sees the properties the test set on the object.

Core\Test\Outcome has class(), name(), attempt(), hasPassed() and failures(), the messages of the failed assertions. Core\Test\Summary has class(), passed(), failed(), skipped(), flaky() and failedTests(), the names of the failed tests.

When #[BeforeClass] throws an error, each test fails. The message names the hook and gives the error's message. #[AfterClass] still runs.

When #[AfterClass] throws an error, the report has a line with ✗ and the hook's name, and the exit status is 1. When #[AfterEachTest] throws an error, that attempt fails.

A subclass runs the tests, the fixtures and the hooks of its parent under its own name. The parent also runs them under its name, unless it is abstract. A method that overrides a hook or a test without its attribute is E0862 or E0733.

There is no #[BeforeEachTest]. The constructor of the test class runs before each test.

Generated inputs

A property is a test that runs many times, with new inputs on every call. You say what must be true for every input, and the runner looks for an input where it is false.

#[Property] goes on a method with the same shape as a #[Test] method. Each parameter gets a generated value of its declared type. The runner calls the method 100 times, and runs: changes that number. gen: { level: "0..1000" } gives $level a whole number from 0 to 1000.

When a call fails, the runner tries smaller inputs that still fail. The report shows the smallest input it found, the input that failed first, and the seed. Write that seed as #[Property(seed: n)], and the test runs with the same inputs again.

Good to know: a generated string can have any character, including emoji and accents. A property that only holds for English letters fails.

A property holds for every input

<?nvs
// Shows a property: a test that runs many times, with new inputs on every call.
// proof: test
use Core\Test;
use Core\Test\Property;
final class Money
{
public static function add(int $a, int $b): int
{
return $a + $b;
}
}
final class MoneyTest
{
// `$a` and `$b` are whole numbers from -1000 to 1000. The test runs 100 times.
#[Property(gen: { a: '-1000..1000', b: '-1000..1000' })]
public function itAddsInEitherOrder(int $a, int $b): void
{
Test::assertSame(Money::add($a, $b), Money::add($b, $a));
}
}
Output
MoneyTest
✓ itAddsInEitherOrder
0 failed, 1 passed, 0 skipped, 0 flaky

A failure shrinks

<?nvs
// Shows a property that fails. The report gives the smallest input that still fails.
// proof: test
// proof: exit 1
use Core\Test;
use Core\Test\Property;
final class Volume
{
// This method has a bug. The highest level is 10, but the check uses 100.
public static function limit(int $level): int
{
if ($level > 100) {
return 10;
}
return $level;
}
}
final class VolumeTest
{
// The generated level can be any number from 0 to 1000.
// The report shows that 11 is the smallest level that fails.
#[Property(seed: 7, gen: { level: '0..1000' })]
public function itNeverGoesAboveTen(int $level): void
{
Test::assertTrue(Volume::limit($level) <= 10);
}
}
Output
VolumeTest
✗ itNeverGoesAboveTen
Core\Test::assertTrue failed: `$actual` is false
call 8 of 100 failed. The smallest inputs that still fail are (11). The generated inputs were (39). Write `#[Property(seed: 7)]` to run the same inputs again.
1 failed, 0 passed, 0 skipped, 0 flaky

A seed runs the same inputs again

<?nvs
// Shows that a seed gives the same inputs every time.
// proof: test
// proof: exit 1
use Core\Test;
use Core\Test\Property;
final class SeedTest
{
// Both tests use the seed 42, so both get the same inputs.
// The report shows the same generated input for each failure.
#[Property(seed: 42, gen: { n: '0..1000' })]
public function itFailsOnce(int $n): void
{
Test::assertTrue($n < 500);
}
#[Property(seed: 42, gen: { n: '0..1000' })]
public function itFailsTheSameWay(int $n): void
{
Test::assertTrue($n < 500);
}
}
Output
SeedTest
✗ itFailsOnce
Core\Test::assertTrue failed: `$actual` is false
call 4 of 100 failed. The smallest inputs that still fail are (500). The generated inputs were (827). Write `#[Property(seed: 42)]` to run the same inputs again.
✗ itFailsTheSameWay
Core\Test::assertTrue failed: `$actual` is false
call 4 of 100 failed. The smallest inputs that still fail are (500). The generated inputs were (827). Write `#[Property(seed: 42)]` to run the same inputs again.
2 failed, 0 passed, 0 skipped, 0 flaky

Details

A parameter can have any of these types: a number, bool, decimal, string, bytes, an enum, mixed, ?T, array<T>, a shape, a union, and a class of your program with a public constructor. A class is built with new, so its constructor runs. A function, an interface, an abstract class, a Core class and a secret value are E0890.

gen: takes a range for a parameter, written as "low..high". Both ends are included. On a number, the range is the value. On a string, bytes or array<T>, the range is the length, up to 10000. A string's length counts characters as a person reads them. On ?T, the range is for T. A range that names no parameter, or that does not fit the type, is E0890.

The options are those of #[Test], without retries: and because:. runs: is from 1 to 100000. A property never uses a #[TestWith] row or a fixture.

The seed also sets the test's own random numbers. Without seed:, every run has a new seed.

The runner tries at most 1000 smaller inputs. It also stops at the test's time limit. One call's inputs have at most 1048576 elements, bytes and characters together. A property that needs more fails before its first call.

In the JSON report, a failed property has a counterexample field. A subclass runs every property it inherits, the same way it runs an inherited #[Test].

Code that only tests can use

#[TestOnly] says that a class, an interface, an enum or a method is only for tests. You write it in your normal code, next to the code it marks. A fake service for your tests or a method that resets a cache between tests are typical uses.

  • On a method, only test code can call the method.
  • On a class, interface or enum, only test code can use the type. This includes every method and the constructor.

Test code is a method with a testing attribute, such as #[Test] or #[Fixture], and any #[TestOnly] code. Any other use of test-only code does not compile.

nvs run and nvs build leave all test-only code out of your program. nvs test compiles it.

Good to know: Core\Program::implementing never lists a test-only class, also under nvs test. So your tests see the same classes as your program.

A fake clock for tests

<?nvs
// Shows a fake clock that only tests can use. The program itself uses the real clock.
use Core\Test;
use Core\TestOnly;
interface Clock
{
public function hour(): int;
}
class SystemClock implements Clock
{
public function hour(): int
{
return 9;
}
}
class Shop
{
public function constructor(private Clock $clock)
{}
public function isOpen(): bool
{
int $hour = $this->clock->hour();
return $hour >= 8 && $hour < 18;
}
}
// `nvs run` and `nvs build` leave this class out. `nvs test` compiles it.
#[TestOnly]
class FakeClock implements Clock
{
public function constructor(private int $hour)
{}
public function hour(): int
{
return $this->hour;
}
}
class ShopTest
{
#[Test]
public function itIsClosedAtNight(): void
{
var $shop = new Shop(new FakeClock(23));
Test::assertSame(false, $shop->isOpen());
}
}
// This prints `open: yes`.
var $shop = new Shop(new SystemClock());
echo 'open: ', $shop->isOpen() ? 'yes' : 'no', "\n";
Output
open: yes

Empty a cache between tests

<?nvs
// Shows a cache with one method that only tests can call. A test calls it to empty
// the cache.
use Core\Arr;
use Core\Test;
use Core\TestOnly;
class Cache
{
private array<string> $items = [];
public function put(string $key, string $value): void
{
$this->items[$key] = $value;
}
public function count(): uint
{
return Arr::count($this->items);
}
// Only test code can call this method. Your program cannot.
#[TestOnly]
public function clearAll(): void
{
$this->items = [];
}
}
class CacheTest
{
#[Test]
public function itIsEmptyAfterClearAll(): void
{
var $cache = new Cache();
$cache->put('tea', '3.50');
$cache->clearAll();
Test::assertTrue($cache->count() == 0);
}
}
// This prints `items: 2`.
var $cache = new Cache();
$cache->put('tea', '3.50');
$cache->put('cake', '2.00');
echo 'items: ', $cache->count(), "\n";
Output
items: 2

A test helper for many test classes

<?nvs
// Shows one test helper class that two test classes share.
use Core\Test;
use Core\TestOnly;
class Product
{
public function constructor(public string $name, public int $cents)
{}
}
class Cart
{
private array<Product> $products = [];
public function add(Product $product): void
{
$this->products[] = $product;
}
public function totalCents(): int
{
int $total = 0;
foreach ($this->products as Product $product) {
$total += $product->cents;
}
return $total;
}
}
// This helper builds test data. Every test class can use it.
#[TestOnly]
class ShopTestData
{
public static function tea(): Product
{
return new Product('tea', 350);
}
public static function cartWithTea(): Cart
{
var $cart = new Cart();
$cart->add(self::tea());
return $cart;
}
}
class ProductTest
{
#[Test]
public function teaCostsThreeFifty(): void
{
Test::assertSame(350, ShopTestData::tea()->cents);
}
}
class CartTest
{
#[Test]
public function theTotalCountsEveryProduct(): void
{
var $cart = ShopTestData::cartWithTea();
$cart->add(ShopTestData::tea());
Test::assertSame(700, $cart->totalCents());
}
}
// This prints `total: 550`.
var $cart = new Cart();
$cart->add(new Product('cake', 200));
$cart->add(new Product('tea', 350));
echo 'total: ', $cart->totalCents(), "\n";
Output
total: 550

Details

You write use Core\TestOnly; and then #[TestOnly] above the declaration. The attribute has no options.

A use of test-only code outside test code is E0889. A use is a call, a new, a static property, a class constant, an enum case or Foo::class. A type is a use too. So a parameter type, a return type, a property type, is, catch and a type argument may name a test-only type only inside test code. The message is "Cache::clearAll is test code, so only test code can use it".

A test-only type may name another test-only type. An anonymous function written inside test code is test code too.

#[TestOnly] on a property, a constant, an enum case or a parameter does not compile. A test-only property would give an object a different shape under nvs test than under nvs run.

Your program cannot depend on test-only code. Each of these is E1019:

  • A class or interface that is not test-only extends or implements a test-only type.
  • A test-only method overrides a method that is not test-only. Your program calls that method through the parent type.
  • A method that is not test-only overrides a test-only method. It must be #[TestOnly] too.
  • A test-only class or method declares a route or a command.

A test-only class may implement an interface of your program. A fake Clock for your tests is an example. No object of the fake exists when the program runs.

When the program runs, test-only code does not exist. Core\Reflect::forClass with the name of a test-only class returns null, as it does for a class that does not exist. A call on a mixed value does not find a test-only method. Core\Program::implementing, implementingWith and constructors never list a test-only class.

A package's test-only code is test code in your program too. So your tests can use the test helpers of a framework.

In the editor, completion offers test-only code only inside test code. A hover on test-only code says "Only for tests."

Assertions

An assertion checks one thing about a value. When the check is false, the test fails.

Every assertion is a static method of Core\Test. You write the value your code produced first, and the value you expect second. An assertion that passes returns and does nothing. One that fails records the failure and throws Core\Test\Failure, and the error message names both values. You may add { message: "..." } at the end of any assertion to put your own sentence in front of that message.

Catching a Core\Test\Failure does not make a test pass. The runner keeps a record of every failed assertion, so a test that caught its own failure still fails. The report lists every failed assertion of a test.

Good to know: both sides of an assertion have the same type, so assertSame(1, "1") does not compile.

The assertions you reach for first

<?nvs
// Shows the four assertions most tests use. Each one takes the value your code
// produced, and then the value you expect. `nvs test` on this file runs the
// `#[Test]` methods.
use Core\Test;
class Order
{
public array<string> $lines = [];
public ?string $couponCode = null;
public function add(string $line): void
{
$this->lines[] = $line;
}
public function isEmpty(): bool
{
return Core\Arr::count($this->lines) == 0;
}
}
class OrderTest
{
#[Test]
public function aNewOrderIsEmpty(): void
{
var $order = new Order();
Test::assertTrue($order->isEmpty());
Test::assertCount($order->lines, 0);
Test::assertNull($order->couponCode);
}
#[Test]
public function addingALineKeepsItsText(): void
{
var $order = new Order();
$order->add('2 x Coffee');
Test::assertCount($order->lines, 1);
Test::assertSame($order->lines[0], '2 x Coffee');
}
}
var $order = new Order();
$order->add('2 x Coffee');
// This prints `2 x Coffee`.
echo $order->lines[0], "\n";
Output
2 x Coffee

What a failing assertion tells you

<?nvs
// Shows what a failing assertion tells you. It throws `Core\Test\Failure`, and
// the message names both sides. This program catches the error and prints that
// message, so you can see each one.
use Core\Test;
try {
Test::assertSame(2 + 2, 5);
} catch (Core\Test\Failure $f) {
echo $f->message, "\n";
}
// A trailing `{ message: "..." }` puts your own sentence in front of the report.
try {
Test::assertSame(0, 1, { message: 'a fresh counter is one' });
} catch (Core\Test\Failure $f) {
echo $f->message, "\n";
}
// `assertEqualsDeep` compares two arrays entry by entry. The message names the
// first place where they differ.
array<string> $sent = ['Berlin', '10115'];
array<string> $stored = ['Berlin', '10117'];
try {
Test::assertEqualsDeep($sent, $stored);
} catch (Core\Test\Failure $f) {
echo $f->message, "\n";
}
Output
Core\Test::assertSame failed: `$actual` is 4, `$expected` is 5
a fresh counter is one: Core\Test::assertSame failed: `$actual` is 0, `$expected` is 1
Core\Test::assertEqualsDeep failed: the two differ at `$actual["1"]`: `$actual` is "10115", `$expected` is "10117"

Checking that a call throws

<?nvs
// Shows how to check that a call throws. `assertThrows` runs the function you
// give it, and passes when that function throws the class you name.
// `assertDoesNotThrow` passes when the function returns.
use Core\Test;
class Age
{
public static function fromText(string $text): int
{
?int $value = $text as ?int;
if ($value == null) {
throw new ParseError('`' . $text . '` is not a number');
}
return $value;
}
}
// The call throws `ParseError`, so this assertion passes and prints nothing.
Test::assertThrows(fn(): void => { Age::fromText('tomorrow'); }, ParseError::class);
echo 'bad input throws', "\n";
// The call returns a number, so this assertion passes too.
Test::assertDoesNotThrow(fn(): void => { Age::fromText('41'); });
echo 'good input does not throw', "\n";
Output
bad input throws
good input does not throw

An assertion of your own

<?nvs
// Shows an assertion of your own. `Core\Test\Failure` is an ordinary error, so
// a method can catch one and throw a new one with a better message.
use Core\Test;
final class Checks
{
public static function assertEven(int $n): void
{
try {
Test::assertSame($n % 2, 0);
} catch (Core\Test\Failure $inner) {
throw new Core\Test\Failure($n . ' is odd: ' . $inner->message);
}
}
}
// 4 is even, so this assertion passes and returns.
Checks::assertEven(4);
echo '4 passed', "\n";
// 3 is odd. The message starts with your own text.
try {
Checks::assertEven(3);
} catch (Core\Test\Failure $f) {
echo $f->message, "\n";
}
// `{ message: … }` puts your own sentence in front of the report.
try {
Test::assertEquals(1, 2, { message: 'a new counter is one' });
} catch (Core\Test\Failure $f) {
echo $f->message, "\n";
}
// A `ParseError` is a `RuntimeError`, so this assertion passes.
Test::assertThrows(fn(): void => { throw new ParseError('bad input'); }, RuntimeError::class);
echo 'a ParseError is a RuntimeError', "\n";
Output
4 passed
3 is odd: Core\Test::assertSame failed: `$actual` is 1, `$expected` is 0
a new counter is one: Core\Test::assertEquals failed: `$actual` is 1, `$expected` is 2
a ParseError is a RuntimeError

Details

Core\Test::assertSame compares numbers, strings and arrays by value. Two objects pass only when they are the same object, so assertSame(new P(1), new P(1)) fails.

assertEquals is the same as assertSame, but it compares two objects with their compareTo method. It passes when compareTo returns 0. For a class without compareTo, it throws a RuntimeError, and the test fails.

assertEqualsDeep compares arrays entry by entry and objects property by property. The message names the first place where the two differ, such as $actual->rows["1"]->name. A secret property is compared, and the message shows «redacted» in place of its value.

Both sides of assertSame, assertEquals and assertEqualsDeep have one type. assertSame(1, "1") and assertSame(1, 1.0) are E0401. assertTrue takes a bool, so assertTrue(1) is E0401.

assertCount counts every entry, with any keys.

assertThrows passes when the function throws the class you name or a subclass of it. Its message names the class that was thrown instead, or says that the function returned. assertDoesNotThrow fails with the message of the error the function threw.

An assertion that fails inside the function you give assertThrows still makes the test fail. To test that an assertion fails, use Core\Test::expectFailure. It passes when an assertion inside the function failed, and that failure does not count against the test. It fails when no assertion inside the function failed.

A failing assertion throws, so the lines after it in the test do not run. A test that catches each Core\Test\Failure goes on, and the report lists every failed assertion.

Core\Test\Failure is a Throwable. It is not a RuntimeError and not a LogicError.

Under nvs run, an assertion that fails throws the same Core\Test\Failure. If nothing catches it, the program ends with exit status 1.

Core\Test::advance is not an assertion. It moves the clock that #[Test(at:)] fixed.

These are the assertions you use most. The Core\Test page lists every one.

Method Passes when
assertSame($actual, $expected) The values are the same. Two objects must be the same object.
assertEquals($actual, $expected) Like assertSame. For two objects, it calls their compareTo method and passes when it returns 0.
assertEqualsDeep($actual, $expected) Arrays and objects are equal in every entry.
assertTrue($value) The bool is true.
assertNull($value) The value is null.
assertCount($array, $n) The array has exactly $n entries.
assertThrows($body, C::class) The function throws C, or a class that extends C.
assertDoesNotThrow($body) The function returns.
expectFailure($body) An assertion inside the function failed. Use it to test that an assertion fails.

Use this when setup is slow or inputs repeat

Section titled “Use this when setup is slow or inputs repeat”

Put slow setup, like building a schema, in a fixture. It then runs once per class. Use #[TestWith] when the same check runs on many inputs.

  • Do write the value you check first: assertSame($actual, $expected).
  • Do use a hook to delete a file or a table that a test leaves behind.
  • Do mark a fake class or a test helper with #[TestOnly]. nvs run and nvs build leave it out.
  • Don’t catch Core\Test\Failure to hide a failed assertion. A failed assertion throws it, and the test fails anyway.