8. Tests
Tests live in the same files as the code. A method with #[Test] is a test:
<?nvs// This program has a class and two tests for it. `nvs test` runs the tests.use Core\Test;
class Task{ public string $title; public bool $done = false;
public function constructor(string $title) { $this->title = $title; }
public function line(): string { return ($this->done ? '[x] ' : '[ ] ') . $this->title; }}
final class TaskTest{ // `#[Test]` makes this method a test. #[Test] public function newTaskIsOpen(): void { Test::assertSame((new Task('Buy milk'))->line(), '[ ] Buy milk'); }
#[Test] public function doneTaskIsChecked(): void { var $task = new Task('Buy milk'); $task->done = true; Test::assertSame($task->line(), '[x] Buy milk'); }}
// `nvs run` runs this line and not the tests.echo (new Task('Buy milk'))->line(), "\n";[ ] Buy milknvs run runs the program and skips the tests. nvs test tour.nvs runs only the tests, and
prints one line for each:
TaskTest ✓ newTaskIsOpen 0.3 ms ✓ doneTaskIsChecked 0.0 ms
0 failed, 2 passed, 0 skipped, 0 flaky in 2 msTest::assertSame checks that two values are the same. When they are not, the test fails.
Read more in Syntax: writing tests.
Next: step 9, HTML.
