Skip to content

Running tests

A test is a method with the #[Test] attribute. It must be public, return void and belong to a class. A test that checks nothing fails, so every test needs at least one assertion.

<?nvs
// This program has a class and three tests for it. `nvs test prices.nvs` runs the tests.
use Core\Test;
class Price
{
// `withTax` adds 20 percent to a price in cents.
public static function withTax(int $cents): int
{
return $cents + Core\Math::quotient($cents, 5);
}
}
final class PriceTest
{
#[Test]
public function addsTwentyPercent(): void
{
Test::assertSame(Price::withTax(1000), 1200);
}
#[Test]
public function zeroStaysZero(): void
{
Test::assertSame(Price::withTax(0), 0);
}
// `skip` turns a test off and prints the reason.
#[Test(skip: 'rounding is not decided yet')]
public function roundsHalfCents(): void
{
Test::assertSame(Price::withTax(3), 4);
}
}
// `nvs run prices.nvs` runs this line and not the tests.
echo Price::withTax(1000), "\n";
Output
1200

nvs run prices.nvs runs the program and skips the tests, so the output above is 1200. nvs test prices.nvs runs only the tests:

Terminal: prices
nvs test prices.nvs  PriceTest    ✓ addsTwentyPercent                0.3 ms    ✓ zeroStaysZero                    0.3 ms    - roundsHalfCents                  0.0 ms      skipped: rounding is not decided yet  0 failed, 2 passed, 1 skipped, 0 flaky in 1 ms

Each test has one line with its time. A skipped test has a - and the reason on the next line. The last line counts the results.

A failed assertion prints the value it got and the value it expected. In this file, the second test expects 650, but withTax(500) returns 600:

Terminal: fail
nvs test prices.nvs  PriceTest    ✓ addsTwentyPercent                0.3 ms    ✗ addsTwentyPercentToFiveEuros     0.5 ms      Core\Test::assertSame failed: `$actual` is 600, `$expected` is 650  1 failed, 1 passed, 0 skipped, 0 flaky in 2 msexit 1

When a test fails, nvs test exits with the status 1, so a CI build fails too. A skipped test is not a failure.

nvs test . reads every .nvs file in the current folder, and in the folders under it. Novis reads them as one program and runs every test in it. Run it from your project folder. Your entry file is in that folder, so the tests can use your classes.

A subfolder that has its own package.toml is not read. nvs test does not run the #[Test] methods of a package that your program loads. To run the tests of a package, give nvs test the folder of that package.

You can write the tests under src/, next to your classes. You can also keep them in a tests folder with one bootstrap.nvs that requires your entry file. nvs test . runs both. The editor and nvs check tests/CartTest.nvs use tests/bootstrap.nvs too, so a test file can use your classes without a require of its own. Read Project layout for both ways.

This file has three tests for a cart. The last one has the tag slow: #[Test(tags: ['slow'])].

Terminal: options
nvs test cart.nvs --listCartTest::anEmptyCartCostsNothing  cart.nvs:21CartTest::itAddsTwoPrices  cart.nvs:27CartTest::itAddsTenThousandPrices  cart.nvs:33nvs test cart.nvs --filter itAdds  CartTest    ✓ itAddsTwoPrices                  0.3 ms    ✓ itAddsTenThousandPrices          1.7 ms  0 failed, 2 passed, 0 skipped, 0 flaky, 1 left out in 3 msnvs test cart.nvs --skip-tag slow  CartTest    ✓ anEmptyCartCostsNothing          0.3 ms    ✓ itAddsTwoPrices                  0.2 ms  0 failed, 2 passed, 0 skipped, 0 flaky, 1 left out in 1 ms
  • --list prints every test with its file and line. It runs none of them.
  • --filter itAdds runs only the tests whose name contains itAdds. The name is Class::method.
  • --skip-tag slow does not run the tests with the tag slow. --tag slow runs only those tests.

The summary counts the tests that did not run as left out.

You can also choose tests by where they are, or by what you changed:

  • nvs test tests/CartTest.nvs:42 runs the test that contains line 42.
  • nvs test . --since main runs only the tests that reach code you changed or deleted since the git branch main. When it cannot tell which tests a change affects, it runs every test. Use it while you edit, and run every test in CI.

A build server often needs a report file. --format junit prints the result as JUnit XML, and --format json prints one JSON document:

Terminal window
nvs test . --format junit > report.xml

Other options stop at the first failure, run only the tests that failed last time, or run the tests again when you save a file. Read every option in Reference: nvs test.

A test with #[Property] runs 100 times. Each time, Novis generates new values for its parameters. gen: gives the range of each value. When a call fails, Novis looks for the smallest input that still fails.

This method has a bug. It should never return more than 10, but it checks against 100:

<?nvs
// A property test that finds a bug in `limit`.
use Core\Test;
use Core\Test\Property;
final class Volume
{
// The highest level is 10, but the check uses 100. This is the bug.
public static function limit(int $level): int
{
if ($level > 100) {
return 10;
}
return $level;
}
}
final class VolumeTest
{
// `$level` is a generated number from 0 to 1000. The test runs 100 times.
#[Property(seed: 7, gen: { level: '0..1000' })]
public function itNeverGoesAboveTen(int $level): void
{
Test::assertTrue(Volume::limit($level) <= 10);
}
}
Terminal: property
nvs test volume.nvs  VolumeTest    ✗ itNeverGoesAboveTen              1.0 ms      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 in 2 msexit 1

The 8th call failed with the input 39. The smallest input that still fails is 11. The seed: 7 in the attribute makes every run use the same inputs, so you can run the failure again.

nvs test --mutate checks whether your tests notice a small change in your code. It runs the tests once. Then it changes the program in one place, for example >= to >. This changed program is called a mutant. It runs the tests again, and a test should now fail.

<?nvs
// Orders of 50.00 or more ship free. The tests use 20.00 and 80.00 only.
use Core\Test;
class Shipping
{
// Prices are in cents.
public static function total(int $order): int
{
if ($order >= 5000) {
return $order;
}
return $order + 495;
}
}
final class ShippingTest
{
#[Test]
public function aSmallOrderPaysForShipping(): void
{
Test::assertSame(Shipping::total(2000), 2495);
}
#[Test]
public function aLargeOrderShipsFree(): void
{
Test::assertSame(Shipping::total(8000), 8000);
}
}
Terminal: mutate
nvs test shipping.nvs --mutate  ShippingTest    ✓ aSmallOrderPaysForShipping       0.2 ms    ✓ aLargeOrderShipsFree             0.2 ms  0 failed, 2 passed, 0 skipped, 0 flaky in 1 ms  5 of 5 lines run (100.0%)  3 mutants: each one runs the tests that reach its line  compiles: 1, for the 3 mutants that ran tests  mutants: 2 killed, 1 survived, 0 timed out, 0 not reached  mutation score: 66.7% (2 of 3 reached mutants made a test fail or time out)  survived in Shipping::total (1):    shipping.nvs:10  `>=` to `>`  mutant = "Shipping::total#1: `>=` to `>`"

The tests use the orders 2000 and 8000, and they still pass when >= on line 10 changes to >. So the mutant survived. A test with an order of exactly 5000 fails on that mutant. The mutation score is the share of mutants that made a test fail. A survived mutant does not make the run fail, so the exit status is 0.

The report lists survived mutants by method. Each line ends with the mutant’s key, such as Shipping::total#1: `>=` to `>` . If you checked a survivor and it is fine, copy that line into a file named mutants.toml and add a reason. The report then counts that mutant, but it does not list it.

A large program has many mutants, so you can choose which code changes:

  • --mutate=Shipping changes only that class. A folder, a file or a method such as Shipping::total works too.
  • --mutate --since main changes only the lines you edited since the git branch main.
  • #[NoMutate(because: '...')] on a class or a method keeps it out of every mutation run.

A run compiles your program once for all its mutants. A mutant that compiles to the same code as your program runs no test, and the report counts it as equivalent.

A method with #[Bench] is a bench. nvs test --bench runs every bench once, and runs no test. A plain nvs test runs no bench.

<?nvs
// A test and a bench for the same method.
use Core\Test;
use Core\Test\Bench;
final class Slug
{
// `of` turns a title into a lowercase slug with dashes.
public static function of(string $title): string
{
return Core\Str::replace(Core\Str::lower(Core\Str::trim($title)), ' ', '-');
}
}
final class SlugTest
{
#[Test]
public function itJoinsTheWordsWithDashes(): void
{
Test::assertSame(Slug::of(' Hello World '), 'hello-world');
}
// A bench needs no assertion. `nvs test --bench` runs it once and counts its work.
#[Bench]
public function slugsOfOneHundredTitles(): void
{
for (int $i = 0; $i < 100; $i++) {
Slug::of('Release Notes ' . $i);
}
}
}
Terminal: bench
nvs test slug.nvs --bench  SlugTest    ✓ slugsOfOneHundredTitles          0.8 ms      count: statements=302 calls=400 allocations=304 bytes=17878 gc=0, wall 0.523 ms (advisory)  0 failed, 1 passed, 0 skipped, 0 flaky in 1 ms

The count: line has the number of statements, calls, allocations, allocated bytes and garbage collections. These numbers are the same on every run and on every computer, so a build server can compare them with the last run. The time is marked (advisory), because it changes on every run.

nvs test can also write a coverage report: which lines of your code the tests ran. Read Coverage reports.