Tests

for Zig 0.15.2 Buy

Tests

In Zig, we have a very simple way to test your code without running it manually: the zig test filename.zig command. This command automatically compiles and executes the tests defined in that file.

 const std = @import("std");

 const print = std.debug.print;

 // import std.testing for the tests

 const testing = std.testing;

 fn subzero(n_x: i8) i8 {

    return n_x - (n_x + 1);

 }

 // define the tests that will only run with zig test

 test "subzero" {

    try testing.expect(subzero(45) == -1);

 }

 pub fn main() void {

    print("A subzero attack: {}\n", .{subzero(42)});

 }

The truth is that in this first volume of Zen of Zig, we won't be writing tests this way. Not because it's not a good practice. It is, and the fact that Zig makes it so easy to write them is a big advantage. The thing is, the concepts and code in this volume are quite linear and short. I think that adding tests here wouldn’t help reinforce the fundamentals or maintain focus at all. It would only add noise.

The real usefulness of tests in software is to make sure everything keeps working correctly as new features are added or existing ones are modified. We’ll cover that in the following volumes.

Additionally, all the examples in this book can be executed interactively using the playgrounds at zenofzig.com/book and the full source code is available here:

codeberg.org/zenofzig/zoz1-learn-programming-with-zig.


Character Representation
Chapter summary
© 2025 - 2026 Zen of Zig