Написание блоков test
Тесты находятся прямо рядом с вашим кодом.
«Написание блоков test» — бесплатный урок Zig Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Tests Live in Your Code
In Zig you do not need a separate test file. A test block sits right beside the code it checks, in the very same source file.
The test Keyword
You start a test with the test keyword, a name in quotes, and a block. The compiler collects every one of these for you.
test "adds two numbers" {
// checks go here
}Name Your Tests Clearly
The string after test is its name. A clear name like "parses empty input" shows up in the report and tells you what failed.
test "parses empty input" {}Import std to Assert
Most tests need helpers, so you bring in the standard library at the top with an @import call and use std.testing inside.
const std = @import("std");A First Real Test
Inside the block you compute something and check it. Here expect passes only when the boolean condition is true.
test "two plus two" {
try std.testing.expect(2 + 2 == 4);
}Tests Can Fail
Assertion helpers return an error when the check is false. That is why you write try before them, letting the failure end the test.
try std.testing.expect(1 == 2);Test a Function You Wrote
A test usually calls one of your own functions and checks its result. The function and the test can share the same file.
fn add(a: i32, b: i32) i32 {
return a + b;
}Checking the Result
Now exercise that function from a test and confirm the output is what you expect with a single expect call.
test "add works" {
try std.testing.expect(add(2, 3) == 5);
}Many Tests, One File
You can stack as many test blocks as you like. Each runs in isolation, so a failure in one does not block the others.
Tests Are Compiled Code
A test block is normal Zig, fully type-checked. If it does not compile, the test run stops before anything even executes.
Why Inline Tests Help
Keeping checks next to the code means tests evolve with it. When you change a function, its test is right there to update.
Quick Check
You want to declare a unit test in a Zig source file. What is the right shape?
Recap
You met the test block: named, inline, fully compiled Zig that you assert with try. Tests live right next to the code they protect. ✅
Часто задаваемые вопросы
Урок «Написание блоков test» бесплатный?
Да — полный текст урока «Написание блоков test» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «Написание блоков test»?
Тесты находятся прямо рядом с вашим кодом. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Написание блоков test»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Написание блоков test
- Проверки с помощью std.testing
- Распределитель для тестирования обнаруживает утечки
- Запуск и фильтрация тестов