TExcelTAD
Home › Zig › Zig Testing

Zig Testing

Testing is built into the Zig language. You don't install a framework or learn a separate tool: you write test blocks right next to the code they check, and run them with zig test. Tests are compiled only when testing, so they cost nothing in the final program.

Test blocks

A test block has a name (a string) and a body. It fails if the body returns an error, so tests use try with the checking functions from std.testing:

zig
const std = @import("std");

fn celsiusToFahrenheit(c: f64) f64 {
    return c * 9.0 / 5.0 + 32.0;
}

fn isLeapYear(year: u32) bool {
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0;
}

test "freezing and boiling points" {
    try std.testing.expectEqual(32.0, celsiusToFahrenheit(0));
    try std.testing.expectEqual(212.0, celsiusToFahrenheit(100));
}

test "leap years" {
    try std.testing.expect(isLeapYear(2024));
    try std.testing.expect(!isLeapYear(1900));
    try std.testing.expect(isLeapYear(2000));
}

Save this as temps.zig and run:

bash · try it yourself
zig test temps.zig
All 2 tests passed.

When a test fails

Let's add a buggy function and a test that catches it:

zig
fn average(values: []const i32) i32 {
    var sum: i32 = 0;
    for (values) |v| sum += v;
    return @divTrunc(sum, @as(i32, @intCast(values.len)) + 1); // bug: + 1
}

test "average of three numbers" {
    try std.testing.expectEqual(20, average(&.{ 10, 20, 30 }));
}
bash · try it yourself
zig test temps.zig
1/3 temps.test.freezing and boiling points...OK
2/3 temps.test.leap years...OK
3/3 temps.test.average of three numbers...expected 20, found 15
FAIL (TestExpectedEqual)
/home/you/temps.zig:24:5: 0x1048f3c in test.average of three numbers (test)
    try std.testing.expectEqual(20, average(&.{ 10, 20, 30 }));
    ^
2 passed; 0 skipped; 1 failed.
error: the following test command failed with exit code 1:
.zig-cache/o/2f1c…/test --seed=0x8a51c2d7

The message tells you what was expected, what was found, and the exact line. (The addresses and paths will differ on your machine.)

The std.testing toolbox

Function Passes when
expect(cond) cond is true
expectEqual(expected, actual) the values are equal
expectEqualStrings(a, b) two strings are equal (shows a diff if not)
expectEqualSlices(T, a, b) two slices have equal elements
expectError(error.X, expr) expr returns exactly that error
expectApproxEqAbs(a, b, tol) floats are within tol of each other

Put the expected value first. These functions are ordinary code returning errors, so you can even try them outside a test:

zig · try it yourself
const std = @import("std");

fn add(a: i32, b: i32) i32 {
    return a + b;
}

pub fn main() void {
    std.testing.expectEqual(@as(i32, 5), add(2, 3)) catch unreachable;
    std.debug.print("first check passed\n", .{});

    std.testing.expectEqual(@as(i32, 6), add(2, 3)) catch |err| {
        std.debug.print("second check: {t}\n", .{err});
    };
}
first check passed
expected 6, found 5
second check: TestExpectedEqual

Testing errors

Use expectError to check that bad input is rejected the way you intended:

zig
fn parsePercent(text: []const u8) !u8 {
    const n = try std.fmt.parseInt(u8, text, 10);
    if (n > 100) return error.OutOfRange;
    return n;
}

test "parsePercent rejects bad input" {
    try std.testing.expectEqual(42, try parsePercent("42"));
    try std.testing.expectError(error.OutOfRange, parsePercent("150"));
    try std.testing.expectError(error.InvalidCharacter, parsePercent("4%"));
}

Tests and memory leaks

Inside tests, use std.testing.allocator. It is a debug allocator that fails the test if anything allocated is not freed:

zig
test "list does not leak" {
    const allocator = std.testing.allocator;
    var list: std.ArrayList(u32) = .empty;
    defer list.deinit(allocator); // remove this line and the test fails
    try list.append(allocator, 7);
    try std.testing.expectEqual(1, list.items.len);
}
bash · try it yourself
zig test list.zig
All 1 tests passed.

Test blocks don't affect normal builds

When you zig run or zig build-exe a file, its test blocks are skipped entirely. This program runs normally even though it contains a test that would fail:

zig · try it yourself
const std = @import("std");

fn double(x: i32) i32 {
    return x * 2;
}

test "this test is wrong on purpose" {
    try std.testing.expectEqual(5, double(2));
}

pub fn main() void {
    std.debug.print("double(21) = {d}\n", .{double(21)});
}
double(21) = 42

Useful options

Command Effect
zig test file.zig run all tests in the file (and files it imports)
zig test file.zig --test-filter "leap" run only tests whose name contains "leap"
zig build test run the test step defined in build.zig
return error.SkipZigTest; mark a test as skipped

Tip: Write the test first when fixing a bug: reproduce the bug as a failing test, then fix the code until it passes. The test then guards against the bug returning.

Test yourself

How does a Zig test block signal failure?

  1. By printing FAIL
  2. By returning an error, usually via try std.testing.expect…
  3. By calling exit(1)
  4. By panicking only

Which allocator should you use inside tests to catch leaks?

  1. std.heap.page_allocator
  2. std.testing.allocator
  3. No allocator
  4. std.heap.c_allocator

What happens to test blocks when you run zig build-exe main.zig?

  1. They run before main
  2. They are compiled but not run
  3. They are ignored entirely
  4. Compilation fails